using BenTek.AdventOfCode.TwentyTwentyFive.Interfaces; namespace BenTek.AdventOfCode.TwentyTwentyFive.Days; public class Day2Part2 : IPuzzle { private class Bounds { public long Upper { get; } public long Lower { get; } public Bounds(long lower, long upper) { Upper = upper; Lower = lower; } public Bounds(string range) { string[] bounds = range.Split('-'); Lower = long.Parse(bounds[0]); Upper = long.Parse(bounds[1]); } } /// public string ExpectedTestValue1 => "4174379265"; public string TestDataPath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Day2", "sample_input.txt"); public string RealDataPath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Day2", "input.txt"); private string[] WrongAnswers => ["31210613313"]; /// public bool Test() { string input = Utilities.FileLoader.LoadFile(TestDataPath); string result = Logic(input); bool passing = result == ExpectedTestValue1; if (!passing) { Console.WriteLine($"Expected {ExpectedTestValue1} but got {result}"); } return passing; } /// public string Run() { string input = Utilities.FileLoader.LoadFile(RealDataPath); string result = Logic(input); if (!CheckAnswer(result)) { return $" - {result} is the wrong answer"; } return result; } /// public string Logic(string input) { List boundsList = new List(); string[] ranges = input.Split(','); foreach (string range in ranges) { boundsList.Add(new Bounds(range)); } List invalidIDs = new List(); for (int i = 0; i < boundsList.Count; i++) { Bounds bounds = boundsList[i]; for (long j = bounds.Lower; j <= bounds.Upper; j++) // Inclusive { if (!IsValid(j)) { invalidIDs.Add(j); } } } long total = 0; foreach (long invalidID in invalidIDs) { total += invalidID; } return total.ToString(); } private bool IsValid(long id) { string idStr = id.ToString(); int length = idStr.Length; for (int i = 2; i <= length; i++) { float strideFloat = length / (float)i; if (strideFloat % 1f > 0) { continue; } int stride = (int)strideFloat; List substrings = new List(); for (int j = 0; j < length / stride; j++) { substrings.Add(idStr.Substring(j * stride, stride)); } if (!UniformSubstrings(substrings)) { continue; } return false; } return true; } private bool UniformSubstrings(List substrings) { string prototype = substrings[0]; for (int j = 1; j < substrings.Count; j++) { if (substrings[j] != prototype) { return false; } } return true; } private bool CheckAnswer(string answer) { foreach (string wrongAnswer in WrongAnswers) { if (answer == wrongAnswer) { return false; } } return true; } }