|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "aocli/utils" |
| 5 | + "aocli/utils/minpresses" |
| 6 | + "strings" |
| 7 | + "sync" |
| 8 | +) |
| 9 | + |
| 10 | +func doPartTwo(input string) int { |
| 11 | + lines := strings.Split(strings.TrimSpace(input), "\n") |
| 12 | + |
| 13 | + type result struct { |
| 14 | + index int |
| 15 | + score int |
| 16 | + line string |
| 17 | + } |
| 18 | + |
| 19 | + results := make(chan result, len(lines)) |
| 20 | + var wg sync.WaitGroup |
| 21 | + |
| 22 | + // Process each line in parallel |
| 23 | + for idx, line := range lines { |
| 24 | + wg.Add(1) |
| 25 | + go func(index int, line string) { |
| 26 | + defer wg.Done() |
| 27 | + |
| 28 | + s := strings.Fields(line) |
| 29 | + |
| 30 | + // Parse buttons (middle section) |
| 31 | + buttonstring := s[1 : len(s)-1] |
| 32 | + buttonslen := len(buttonstring) |
| 33 | + buttonPositions := make([][]int, 0, buttonslen) |
| 34 | + for _, b := range buttonstring { |
| 35 | + s := strings.Split(strings.Trim(b, "()"), ",") |
| 36 | + positions := make([]int, 0, len(s)) |
| 37 | + for _, n := range s { |
| 38 | + positions = append(positions, utils.Atoi(n)) |
| 39 | + } |
| 40 | + buttonPositions = append(buttonPositions, positions) |
| 41 | + } |
| 42 | + |
| 43 | + // Parse target joltages (last section) |
| 44 | + targetJoltages := []int{} |
| 45 | + for _, c := range strings.Split(strings.Trim(s[len(s)-1], "{}"), ",") { |
| 46 | + targetJoltages = append(targetJoltages, utils.Atoi(c)) |
| 47 | + } |
| 48 | + |
| 49 | + // Solve for minimum presses to reach joltages |
| 50 | + score, possible := minpresses.SolveMinPresses(buttonPositions, targetJoltages) |
| 51 | + if !possible { |
| 52 | + score = 0 // No solution |
| 53 | + } |
| 54 | + |
| 55 | + results <- result{index: index, score: score, line: line} |
| 56 | + }(idx, line) |
| 57 | + } |
| 58 | + |
| 59 | + // Close results channel when all goroutines are done |
| 60 | + go func() { |
| 61 | + wg.Wait() |
| 62 | + close(results) |
| 63 | + }() |
| 64 | + |
| 65 | + // Collect results in order |
| 66 | + collected := make([]result, len(lines)) |
| 67 | + for r := range results { |
| 68 | + collected[r.index] = r |
| 69 | + } |
| 70 | + |
| 71 | + // Sum results |
| 72 | + ans := 0 |
| 73 | + for _, r := range collected { |
| 74 | + ans += r.score |
| 75 | + } |
| 76 | + |
| 77 | + return ans |
| 78 | +} |
0 commit comments