using AdventOfCode.Solutions._2022.Day_11; namespace AdventOfCode.Solutions._2022 { public class Day11Part2 : Answerable { public override int Year { get; set; } = 2022; public override int Day { get; set; } = 11; public override int Part { get; set; } = 2; public override string GetAnswer(byte[] data) { string[] monkeyString = GetAsString(data).Split(NewLine + NewLine); int lowestLcm = 1; Monkey[] monkeys = new Monkey[monkeyString.Length]; for (int monkeyIndex = 0; monkeyIndex < monkeys.Length; monkeyIndex++) { monkeys[monkeyIndex] = new(monkeyIndex, 1, monkeyString[monkeyIndex].Split(NewLine)); lowestLcm = CalculateLeastCommonMultiple(lowestLcm, monkeys[monkeyIndex].TestDevision); } for (int monkeyIndex = 0; monkeyIndex < monkeys.Length; monkeyIndex++) { string[] monkey = monkeyString[monkeyIndex].Split(NewLine); int trueMonkey = Convert.ToInt32(monkey[4].Split(' ')[^1]); int falseMonkey = Convert.ToInt32(monkey[5].Split(' ')[^1]); monkeys[monkeyIndex].SetThrowTargets(monkeys[trueMonkey], monkeys[falseMonkey]); monkeys[monkeyIndex].lcm = lowestLcm; } for (int round = 1; round <= 10_000; round++) { for (int monkey = 0; monkey < monkeys.Length; monkey++) { monkeys[monkey].DoTurn(false); } } long[] mostInspects = monkeys.Select(m => (long)m.TotalInspections).OrderByDescending(i => i).Take(2).ToArray(); return $"{mostInspects[0] * mostInspects[1]}"; } private int CalculateLeastCommonMultiple(int valueA, int valueB) { int num1, num2; if (valueA > valueB) { num1 = valueA; num2 = valueB; } else { num1 = valueB; num2 = valueA; } for (int i = 1; i <= num2; i++) { if ((num1 * i) % num2 == 0) { return i * num1; } } return num2; } } }