Browse Source

Solved part2 for sample

Piotr Czajkowski 1 year ago
parent
commit
5e572b811b
1 changed files with 44 additions and 2 deletions
  1. 44 2
      08/code.go

+ 44 - 2
08/code.go

@@ -14,8 +14,9 @@ type Directions struct {
 }
 }
 
 
 type Network struct {
 type Network struct {
-	moves string
-	paths map[string]Directions
+	moves  string
+	paths  map[string]Directions
+	starts []string
 }
 }
 
 
 func readInput(file *os.File) Network {
 func readInput(file *os.File) Network {
@@ -53,6 +54,10 @@ func readInput(file *os.File) Network {
 			directions.left = strings.TrimLeft(parts[0], "(")
 			directions.left = strings.TrimLeft(parts[0], "(")
 			directions.right = strings.TrimRight(parts[1], ")")
 			directions.right = strings.TrimRight(parts[1], ")")
 			network.paths[from] = directions
 			network.paths[from] = directions
+
+			if strings.HasSuffix(from, "A") {
+				network.starts = append(network.starts, from)
+			}
 		}
 		}
 	}
 	}
 
 
@@ -83,6 +88,42 @@ func part1(network Network) int {
 	return steps
 	return steps
 }
 }
 
 
+func (n *Network) AtGoal() bool {
+	for i := range n.starts {
+		if !strings.HasSuffix(n.starts[i], "Z") {
+			return false
+		}
+	}
+
+	return true
+}
+
+func part2(network Network) int {
+	steps := 0
+	mod := len(network.moves)
+	index := 0
+	for {
+		if network.AtGoal() {
+			break
+		}
+
+		for i := range network.starts {
+			d := network.paths[network.starts[i]]
+			if network.moves[index] == 'L' {
+				network.starts[i] = d.left
+			} else {
+				network.starts[i] = d.right
+			}
+
+		}
+
+		steps++
+		index = (index + 1) % mod
+	}
+
+	return steps
+}
+
 func main() {
 func main() {
 	if len(os.Args) < 2 {
 	if len(os.Args) < 2 {
 		log.Fatal("You need to specify a file!")
 		log.Fatal("You need to specify a file!")
@@ -97,4 +138,5 @@ func main() {
 
 
 	network := readInput(file)
 	network := readInput(file)
 	fmt.Println("Part1:", part1(network))
 	fmt.Println("Part1:", part1(network))
+	fmt.Println("Part2:", part2(network))
 }
 }