|
2 | 2 |
|
3 | 3 | var lines = Resources.GetInputFileLines(); |
4 | 4 |
|
5 | | -Console.WriteLine($"Part 1: {""}"); |
6 | | -Console.WriteLine($"Part 2: {""}"); |
| 5 | +var rules = lines |
| 6 | + .TakeWhile(l => l.Contains('|')) |
| 7 | + .Select(line => line.SplitToNumbers("|")) |
| 8 | + .Select(numbers => (First: numbers[0], Second: numbers[1])); |
| 9 | + |
| 10 | +var updates = lines |
| 11 | + .SkipWhile(l => l.Contains('|')) |
| 12 | + .Select(line => line.SplitToNumbers()); |
| 13 | + |
| 14 | +var dependentOn = new Dictionary<int, HashSet<int>>(); |
| 15 | +foreach (var (former, latter) in rules) |
| 16 | +{ |
| 17 | + if (!dependentOn.TryGetValue(latter, out HashSet<int>? deps)) |
| 18 | + { |
| 19 | + deps = []; |
| 20 | + dependentOn[latter] = deps; |
| 21 | + } |
| 22 | + |
| 23 | + deps.Add(former); |
| 24 | +} |
| 25 | + |
| 26 | +Console.WriteLine($"Part 1: {GetMiddlePage(false, dependentOn, updates)}"); |
| 27 | +Console.WriteLine($"Part 2: {GetMiddlePage(true, dependentOn, updates)}"); |
| 28 | + |
| 29 | +static int GetMiddlePage(bool takeIncorrectlyReordered, Dictionary<int, HashSet<int>> rules, IEnumerable<int[]> updates) |
| 30 | +{ |
| 31 | + var result = 0; |
| 32 | + foreach (var update in updates) |
| 33 | + { |
| 34 | + var isCorrect = true; |
| 35 | + for (int i = 0; i < update.Length; i++) |
| 36 | + { |
| 37 | + Again: |
| 38 | + var shouldBeEarlier = rules[update[i]]; |
| 39 | + for (int j = i + 1; j < update.Length; ++j) |
| 40 | + { |
| 41 | + if (shouldBeEarlier.Contains(update[j])) |
| 42 | + { |
| 43 | + isCorrect = false; |
| 44 | + if (takeIncorrectlyReordered) |
| 45 | + { |
| 46 | + (update[i], update[j]) = (update[j], update[i]); |
| 47 | + i = 0; |
| 48 | + goto Again; |
| 49 | + } |
| 50 | + else |
| 51 | + { |
| 52 | + break; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + if (!takeIncorrectlyReordered && !isCorrect) |
| 58 | + { |
| 59 | + break; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + if (takeIncorrectlyReordered != isCorrect) |
| 64 | + { |
| 65 | + result += update[update.Length / 2]; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return result; |
| 70 | +} |
0 commit comments