Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var input = await File.ReadAllLinesAsync("input.txt");
- var rules = new List<Rule>();
- var updates = new List<List<int>>();
- var parsingRules = true;
- foreach (var line in input)
- {
- if (parsingRules)
- {
- if (string.IsNullOrWhiteSpace(line))
- {
- parsingRules = false;
- }
- else
- {
- var numbers = line.Split('|').Select(int.Parse).ToArray();
- rules.Add(new Rule(numbers[0], numbers[1]));
- }
- }
- else
- {
- updates.Add(line.Split(',').Select(int.Parse).ToList());
- }
- }
- var part1 = 0;
- var part2 = 0;
- foreach (var update in updates)
- {
- var isValid = true;
- var matchingRules = new List<Rule>();
- foreach (var rule in rules)
- {
- var indexLeft = update.IndexOf(rule.Left);
- var indexRight = update.IndexOf(rule.Right);
- if (indexLeft == -1 || indexRight == -1)
- {
- continue;
- }
- matchingRules.Add(rule);
- if (indexLeft > indexRight)
- {
- isValid = false;
- }
- }
- if (isValid)
- {
- part1 += update[update.Count / 2];
- }
- else
- {
- update.Sort((a, b) =>
- {
- var rule = matchingRules.Find(r => r.Contains(a) && r.Contains(b));
- if (rule == default || rule.Left == a)
- {
- return -1;
- }
- return 1;
- });
- part2 += update[update.Count / 2];
- }
- }
- Console.WriteLine($"Part 1: {part1}");
- Console.WriteLine($"Part 2: {part2}");
- internal record Rule(int Left, int Right)
- {
- public bool Contains(int i) => Left == i || Right == i;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement