logo

adventofcode

Code used to solve https://adventofcode.com/, one branch per year
commit: 52287f3419080ae4230f97d71075896623e5a242
parent: 519e35d37da4221abe56a4ea21775cc29c5fbf39
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Tue,  3 Dec 2019 12:38:00 +0100

day2: fix position registration

forgetting the difference between point and line isn’t a good idea

Diffstat:

Mday2.go56++++++++++++++++++++++++++------------------------------
1 file changed, 26 insertions(+), 30 deletions(-)

diff --git a/day2.go b/day2.go @@ -6,32 +6,33 @@ import ( "strings" ) -func line_positions(line string) [][2]int { +func line_positions(line string) (positions [][2]int) { line_split := strings.Split(line, ",") fmt.Printf("%9s\n", line_split) position := [2]int{0, 0} // (x,y) - positions := make([][2]int, len(line_split)) - for i, move := range line_split { + for _, move := range line_split { direction := strings.Split(move, "")[0] amount, err := strconv.Atoi(move[1:]) if err != nil { fmt.Printf("Error: %s", err) } - switch direction { - case "U": - position[0] += amount - case "D": - position[0] -= amount - case "L": - position[1] += amount - case "R": - position[1] -= amount + for i := 0; i < amount; i++ { + switch direction { + case "U": + position[0]++ + case "D": + position[0]-- + case "L": + position[1]++ + case "R": + position[1]-- + } + + positions = append(positions, position) } - positions[i] = position - // fmt.Printf("%s%02d(% 4d,% 4d)\n", direction, amount, position[0], position[1]) } @@ -40,26 +41,21 @@ func line_positions(line string) [][2]int { return positions } -func Intersection(a, b [][2]int) (c [][2]int) { - m := make(map[[2]int]bool) - - for _, item := range a { - m[item] = true - } - - for _, item := range b { - if _, ok := m[item]; ok { - c = append(c, item) - } - } - return -} - func main() { //line1 := line_positions("R75,D30,R83,U83,L12,D49,R71,U7,L72") //line2 := line_positions("U62,R66,U55,R34,D71,R55,D58,R83") line1 := line_positions("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51") line2 := line_positions("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7") - fmt.Printf("%3d\n", Intersection(line1, line2)) + var intercepts [][2]int + + for _, pos1 := range line1 { + for _, pos2 := range line2 { + if pos1 == pos2 { + intercepts = append(intercepts, pos1) + } + } + } + + fmt.Printf("%3d\n", intercepts) }