Browse Source

Solved part2

Piotr Czajkowski 7 hours ago
parent
commit
288ea4b3fb
1 changed files with 38 additions and 0 deletions
  1. 38 0
      02/code.go

+ 38 - 0
02/code.go

@@ -47,6 +47,43 @@ func part1(program []byte, distances map[byte]map[byte]int) int {
 	return distance
 }
 
+func part2(program []byte, distances map[byte]map[byte]int) int {
+	var distance int
+	var current byte = 'r'
+
+	moves := make(map[byte]int)
+	for i := range program {
+		moves[program[i]]++
+	}
+
+	for current != 0 {
+		var next byte
+		var max int
+
+		distancesFromCurrent := distances[current]
+		for j := range path {
+			if moves[path[j]] == 0 {
+				continue
+			}
+
+			if distancesFromCurrent[path[j]] > max {
+				max = distancesFromCurrent[path[j]]
+				next = path[j]
+			}
+		}
+
+		if next == 0 {
+			break
+		}
+
+		distance += distances[current][next]
+		moves[next]--
+		current = next
+	}
+
+	return distance
+}
+
 func main() {
 	if len(os.Args) < 2 {
 		log.Fatal("You need to specify a file!")
@@ -61,4 +98,5 @@ func main() {
 	distances := getDistances()
 
 	fmt.Println("Part1:", part1(program, distances))
+	fmt.Println("Part2:", part2(program, distances))
 }