Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #load "xunit"
- #load ".\AoCConnector"
- #load ".\2dArrayExtensions"
- async Task Main()
- {
- RunTests(); // Call RunTests() or press Alt+Shift+T to initiate testing.
- var aoc = AoC.GetAOC(2021, 7);
- var answerA = SolveA(aoc.GetLines);
- await aoc.SubmitAnswer(Part.Part1, answerA);
- var answerB = SolveB(aoc.GetLines);
- await aoc.SubmitAnswer(Part.Part2, answerB.ToString().Dump());
- }
- public int SolveA(string[] lines) => Solve(lines, true);
- public int SolveB(string[] lines) => Solve(lines, false);
- public int Solve(string[] lines, bool v1)
- {
- //parse the data
- var inputArray = lines[0].Split(',').Select(x => int.Parse(x)).ToArray();
- Dictionary<int, int> dicCache = new Dictionary<int, int>();
- int min = 0;
- int max = inputArray.Length - 1;
- while (min <= max)
- {
- int mid = (min + max) / 2;
- int midLeft = mid - ((mid - min) / 2);
- int midRight = mid + ((max - mid) / 2);
- int leftValue = GetValue(midLeft);
- int rightValue = GetValue(midRight);
- if (rightValue < leftValue)
- {
- min = midLeft;
- }
- else if (leftValue < rightValue)
- {
- max = midRight;
- }
- else
- {
- return GetValue(mid);
- }
- }
- throw new NotImplementedException();
- int GetValue(int target)
- {
- if (dicCache.TryGetValue(target, out var result) == false)
- {
- result = 0;
- for (int f = 0; f < inputArray.Length; f++)
- {
- var dist = Math.Abs(target - inputArray[f]);
- if(v1)
- result += dist;
- else
- result += dist * (dist + 1) / 2;
- }
- dicCache[target] = result;
- }
- return result;
- }
- }
- #region private::Tests
- string[] TestData = new []
- {
- "16,1,2,0,4,2,7,1,2,14"
- };
- [Fact] void Test_SolvaA() => Assert.Equal(37, SolveA(TestData));
- [Fact] void Test_SolveB() => Assert.Equal(168, SolveB(TestData));
- #endregion
Advertisement
Add Comment
Please, Sign In to add comment