From 918618e0fdcd40b08b3746c69ed1806e202e17c4 Mon Sep 17 00:00:00 2001 From: Xander Sigler Date: Sun, 10 Dec 2023 21:35:10 -0800 Subject: [PATCH] Added day 9 --- AdventOfCode/_2023/Day9.cs | 106 +++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 AdventOfCode/_2023/Day9.cs diff --git a/AdventOfCode/_2023/Day9.cs b/AdventOfCode/_2023/Day9.cs new file mode 100644 index 0000000..556d9e7 --- /dev/null +++ b/AdventOfCode/_2023/Day9.cs @@ -0,0 +1,106 @@ +using AdventOfCode.Common; +using AdventOfCode.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace AdventOfCode._2023 +{ + public class Day9 : AOCDay + { + + protected override AOCResponse ExecutePartA() + { + long total = 0; + foreach(var input in this.GetSplitInput()) + { + var listOfValues = input.Split(' ').Select(x => long.Parse(x)).ToList(); + var entry = new Entry() + { + Values = listOfValues + }; + entry.CreateBelowRecord(this._request.Version); + if (this._request.Version == AOCVersion.A) + { + total += entry.Values.Last(); + } + else + { + total += entry.Values.First(); + } + + Log( "Result is : \n " +entry.GetPrint()); + } + this.Answer = total; + return this._response; + } + + protected override AOCResponse ExecutePartB() + { + return ExecutePartA(); + } + } + + class Entry + { + public Entry Above { get; set; } + public Entry Below { get; set; } + public List Values { get; set; } + + public void CreateBelowRecord(AOCVersion version) + { + var belowValues = new List(); + for (int i = 0; i < Values.Count-1; i++) + { + belowValues.Add(Values[i + 1] - Values[i]); + } + Below = new Entry() + { + Above = this, + Values = belowValues + }; + + //If the below record we just created consists of all 0s + if (Below.IsBottom()) + { + if (version == AOCVersion.A) + { + Below.Values.Add(0); //Extrapolated value + var currentAbove = this; + while (currentAbove != null) + { + currentAbove.Values.Add(currentAbove.Values.Last() + currentAbove.Below.Values.Last()); + currentAbove = currentAbove.Above; + } + } + else //Means it is part B + { + Below.Values.Insert(0, 0); //Append the 0 to the start + var currentAbove = this; + while (currentAbove != null) + { + currentAbove.Values.Insert(0, currentAbove.Values.First() - currentAbove.Below.Values.First()); + currentAbove = currentAbove.Above; + } + } + + } + else + { + Below.CreateBelowRecord(version); + } + } + + public bool IsBottom() + { + return Values.TrueForAll(x => x == 0); + } + + public string GetPrint() + { + return string.Join(" ", Values) + "\n " + (Below != null ? Below.GetPrint() : ""); + } + } + +}