Square peg in a hexagonal hole edition Previous thread →
adventofcode.com/ >Advent of Code is a series of small programming puzzles for a variety of skill levels. They are self-contained and are just as appropriate for an expert who wants to stay sharp as they are for a beginner who is just learning to code. Each puzzle calls upon different skills and has two parts that build on a theme. You need to register with an account but you can appear as anonymous.
The new leaderboard with empty space is join-code: 43046-941b8011
The old (full) leaderboard is join-code: 194764-c554ff91
path = [(0,0)] for step in steps: path.append((path[-1][0]+coords[step][0], path[-1][1]+coords[step][1]))
def dist(coord): f = max if coord[0]*coord[1]>0 else sum return f(map(abs, coord))
print dist(path[-1]) print max([dist(p) for p in path])
Guaranteed™ to work.
Christian Williams
Well, one more reason to get rid of them. We can clearly see day 3 filtered out a bunch, now there's nothing more to learn and having them replaced with active users from the other leaderboard would show with higher resolution where the other bumps might be.
Kinda sucks that we're split like that for no sensible reason.
Ryan Jackson
...
Caleb Ortiz
Yo, I might be confused, but I implemented my solution nearly the same way. However, my offsets for south east were (1, -1) and north west was (-1, 1). How come you have (-1, 0) and (1,0)?
Christopher Powell
make your own leaderboard and govern it how you want otherwise stfu
Sebastian Walker
As an user pointed out in the old thread, i might have my offsets wrong. I came upon these independently on a piece of scrap paper and they seem to work. I imagine different offsets will work so long as they're consistent and the distance function is correct.
Andrew Brooks
It appears from the second leaderboard that day 3 and day 7 were the two casual filters.
Chase Price
You can see that on the public leaderboard for how long it takes for it to fill up.
Jackson Bell
Good point, looks like #10 was a miniboss too.
Kayden Martin
Is it considered cheating if I googled "hexgrid coordinates system"?
Lincoln Young
You're not scoring any points for this puzzle, so at this point you're doing this to learn. And it's fair to use whatever you want to learn.
Austin Wood
Na
Xavier Watson
K
Daniel Green
Should have joined on day 1 instead of being inactive :^)
Luis Moore
Rb
Jordan Gomez
>tfw tasks are starting to become more tedious than anything >tfw no longer having fun
Meh.
Grayson Myers
I don't care about how it is in production, but for these puzzles, ruby is wonderful.
Jack Diaz
You can rotate your labeling, as long as its consistent.
Yeah, and I came here to get laid by some qt in programming socks. We can't always have what we want, user, it's up to you to make the best out of it anyway.
Kevin Cruz
Pretty easy once I found a guide on Hexagonal Coordinate systems. This cube coordinate stuff is neat.
Ryan Allen
this is the first rust program I see that doesn't look like complete garbage.
Charles James
Not to downplay your solution, but I think 3d coordinates are overkill for this puzzle.
for (move y += 1; z -= 1 case "ne" => x += 1; z -= 1 case "se" => x += 1; y -= 1 case "s" => z += 1; y -= 1 case "sw" => z += 1; x -= 1 case "nw" => y += 1; x -= 1 }
Knowing (about hex coord systems) is half (make that 95%) the battle.
William Ward
Knowing how to format code on 4chins is the other 95%
test:
print "hello world"
print "line 2"
end of test
Dominic Martin
I'm on day 3, the manhatten distance one
is there a 'clever' way to do this or do i just have to do it the brainlet ways?
Kayden Perez
I feel like a fucking idiot. I just wasted a few minutes not because of an error in the code, but because of one in a fucking multi-line comment. I was having some difficulty wrapping my head around the coordinate system, so I quickly made a diagram in a comment. """ +y-z _____ -z+x /z- y+\ +y-x /__\ / \ \x+ / -y+x \_____/ +z-x
-y+z """
It turns out that having a \x in exclusively multi-line comments in python will produce an error immediately without reporting a line number. Fucking hell.
Josiah Thompson
There is nothing wrong with generating the spiral
Robert Hall
Part 1 can be done with math.
Part 2 should be done by generating the spiral.
Luis Roberts
>It turns out that having a \x in exclusively multi-line comments in python will produce an error immediately without reporting a line number. Fucking hell.
I have never seen a statement that describes python better than this.
Jose Gonzalez
part 1 can be done with pure fucking math, and it's absolutely easy to do part 2 requires you to generate the spiral. If you're too much of a brainlet to code an algorithm for it you can just open excel and fucking generate it manually, won't take you more than 5 minutes since on average you add a digit every 300° or so
Lincoln Watson
...
Jeremiah Clark
It's OK user I was getting absurd distances because one of my offsets was (+ z) instead of (+ 1). Of course it was for NW so it didn't show up in the test inputs :^)
Landon Morris
>he doesn't get angry about everything how do you get out of bed, anime poster?
Daniel Baker
val moves = io.Source.fromFile("in").mkString.trim.split(',')
for (move y += 1; z -= 1 case "ne" => x += 1; z -= 1 case "se" => x += 1; y -= 1 case "s" => z += 1; y -= 1 case "sw" => z += 1; x -= 1 case "nw" => y += 1; x -= 1 }
>haskal doesn't have a standard function for splitting a string on a delimiter > not even one that splits a string on a predicate
I love it but it really is a meme lang
Jacob Morales
What language is this?
Luis Gutierrez
I'm guessing Scala.
Angel Morris
I think I have found the most elegant solution to problem 11 def AOC11(string): def reduc(x,y,z): mid = sorted((x,y,z))[1] return (x-mid, y-mid, z-mid) x,y,z, MAX = [0]*4 dist = lambda: sum(map(abs, reduc(x,y,z))) for step in string.strip().split(','): if step == 'sw': x += 1 elif step == 'ne': x -= 1 elif step == 'se': y += 1 elif step == 'nw': y -= 1 elif step == 'n': z += 1 elif step == 's': z -= 1 MAX = max(MAX, dist()) yield dist() yield MAX Although there may be a prettier way to write the switch
Zachary Cooper
An alternative using reduce and a map, you may notice the similarities with // using the flat topped cube coordinate system from // redblobgames.com/grids/hexagons case class P3(x: Int, y: Int, z: Int) { def +(p: P3) = P3(x + p.x, y + p.y, z + p.z) def manDist() = { import math.abs; (abs(x) + abs(y) + abs(z))/2 } }
Alternative approaches, you may start noticing similarities with 1. Case classes, take a bit more space: // flat top, cube coord sys: // redblobgames.com/grids/hexagons case class P3(x: Int, y: Int, z: Int) { def +(p: P3) = P3(p.x+x, p.y+y, p.z+z) def manDist = Array(x,y,z).map(math.abs).sum/2 }
2. Terse, more code-golfy and less readable due to less data modelling: // flat top, cube coord sys: // redblobgames.com/grids/hexagons val moves = io.Source.fromFile("in") .mkString.trim.split(',').map(Map( "n" -> Array( 0, 1, -1), "ne" -> Array( 1, 0, -1), "se" -> Array( 1, -1, 0), "s" -> Array( 0, -1, 1), "sw" -> Array(-1, 0, 1), "nw" -> Array(-1, 1, 0)))
val pos = moves reduce {(_,_).zipped map {_+_}}
println(pos.map(math.abs).sum/2)
Brandon Davis
What's the "correct" way of doing this one? My solution was to make a matrix and spiral around from the center until I got something bigger than my input.
Kevin Rodriguez
U
Lucas Garcia
>using excel
now that's truly a brainlet way to do it
Caleb Cooper
day 3 here
how do you generate the spiral? do you just have to make 5 ifs or what?
Lucas Rodriguez
I used excel but I wrote a formula to sum neighbors and copy pasted it around the origin
Landon Wright
If you really need to be spoonfed, you can just repeatedly trace a line and turn at the end, with the distance increasing by two for every two sides.
Aaron Ross
It literally tells you the error is in the comment.
Jose Williams
Perl solution for Day 8 Part 1. Using eval power. Blazing. Fucking. Fast.
use strict; use warnings;
my %registers;
while () { chomp; m/(\w+).*if\s(\w+)/; $registers{$1} = 0 if ! defined($registers{$1}); $registers{$2} = 0 if ! defined($registers{$2}); s/dec/\-=/; s/inc/\+=/; s/(\w+)(.*)if\s(\w+)/\$registers\{$1\}$2if \$registers\{$3\}/; eval $_;
func max(a, b int) int { if a > b { return a } return b }
func abs(a int) int { if a < 0 { return -a } return a }
func dist(x, y int) int { if (x < 0 && y < 0) || (x >= 0 && y >= 0) { return abs(x + y) } return max(abs(x), abs(y)) }
func main() { b, _ := ioutil.ReadAll(os.Stdin) t := strings.TrimSpace(string(b)) x, y := 0, 0 for _, f := range strings.Split(t, ",") { switch f { case "n": y++ case "ne": x++ case "nw": x-- y++ case "s": y-- case "se": x++ y-- case "sw": x-- } fmt.Println(dist(x, y)) } } and find max with piping it into sort -n
Noah Campbell
What if I don't know how to code. Should I die?
Connor Lopez
>having to write your own max and abs functions absolutely horrible. i don't get how go got so popular.
Justin Johnson
and also can't use ternary (a < b) ? a : b over 4 line if statement
Alexander Hill
>no generics >no abs >pipe into sort -n lmao
Kayden Allen
can't you do this? if a > b { return a; } else { return b; }
Bentley Campbell
Solve then in Scratch
Ryder Price
math.Min math.Max math.Abs
fucking mong
Austin Cruz
>func Min(x, y float64) float64 LOL
Austin Brooks
>func Max(x, y float64) float64 >float64 >int(math.Max(math.Abs(float64(a)), math.Abs(float64(b)))) no
Brandon Barnes
change x and y to float64s WHOAAAA
David Ramirez
>we javascript now how horrifying
Brayden Taylor
>mfw this puzzle
I think I'm done with this shit I will skip it and return later ,ay be
def part(total,n): if n>1: for i in range(0,total+1): for j in part(total-i,n-1): yield (i,)+j else: yield (total,)
import re from functools import reduce from operator import mul from collections import defaultdict
pattern = r'(\w+): \w+ (?P-?\d+), \w+ (?P-?\d+), \w+ '\ '(?P-?\d+), \w+ (?P-?\d+), \w+ (?P-?\d+)' things = dict() ingredients = list() properties = list() for m in re.finditer(pattern,data): ingredient = m[1] vals = m.groupdict() things[ingredient]={k:int(j) for k,j in vals.items()} for prop in vals: if prop not in properties: properties.append(prop) if ingredient not in ingredients: ingredients.append(ingredient)
properties.remove('calories') tots = defaultdict(dict) mmmm = 0 for par in part(100,len(things)): #if True = part 2 if True and not 500 == sum([par[n]*things[ingredient]['calories'] for n,ingredient in enumerate(ingredients)]): continue for prop in properties: sss = sum([par[n]*things[ingredient][prop] for n,ingredient in enumerate(ingredients)]) tots[par][prop] = (sss if sss > 0 else 0) gggg = reduce(int.__mul__,tots[par].values()) mmmm = max(mmmm,gggg) print(mmmm)
Alexander Peterson
>have to cast to double to get the abs of an int only the quacks behind C could come up with that