diff --git a/AdventOfCode/Common/AOCExtensions.cs b/AdventOfCode/Common/AOCExtensions.cs index 9fab128..f94411c 100644 --- a/AdventOfCode/Common/AOCExtensions.cs +++ b/AdventOfCode/Common/AOCExtensions.cs @@ -11,7 +11,7 @@ namespace AdventOfCode.Common try { return Convert.ToInt32(str); - }catch (Exception e) + } catch (Exception e) { return 0; throw e; @@ -19,6 +19,12 @@ namespace AdventOfCode.Common } + public static string ReplaceMultipleSpaces(this string str) + { + while (str.Contains(" ")) str = str.Replace(" ", " "); + return str; + } + public static IEnumerable> Chunk(this IEnumerable source, int chunksize) { while (source.Any()) diff --git a/AdventOfCode/_2023/Day6.cs b/AdventOfCode/_2023/Day6.cs new file mode 100644 index 0000000..9997696 --- /dev/null +++ b/AdventOfCode/_2023/Day6.cs @@ -0,0 +1,87 @@ +using AdventOfCode.Common; +using AdventOfCode.Models; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; + +namespace AdventOfCode._2023 +{ + public class Day6 : AOCDay + { + + protected override AOCResponse ExecutePartA() + { + var splitInput = this.GetSplitInput().Select(x => x.Split(':')[1].Trim().ReplaceMultipleSpaces()).ToArray(); + + var races = new List(); + var timeArr = splitInput[0].Split(" ").Select(x => int.Parse(x)).ToArray(); + var distArr = splitInput[1].Split(" ").Select(x => int.Parse(x)).ToArray(); + for (int i = 0; i < timeArr.Length; i++) + { + races.Add(new Race(i, timeArr[i], distArr[i])); + } + + var result = 1; + foreach (var race in races) + { + var raceOptions = race.CalculateOptimalTimes(); + result *= raceOptions.Count; + Log($"Race {race.RaceId} has {raceOptions.Count} race options!"); + } + this.Answer = result; + return this._response; + } + + protected override AOCResponse ExecutePartB() + { + var splitInput = this.GetSplitInput().Select(x => x.Split(':')[1].Trim().Replace(" ", "")).ToArray(); + + var bigRace = new Race(1, long.Parse(splitInput[0]), long.Parse(splitInput[1])); + var raceOptions = bigRace.CalculateOptimalTimes(); + Log($"Race {bigRace.RaceId} has {raceOptions.Count} race options!"); + + this.Answer = raceOptions.Count; + return this._response; + } + } + + class Race + { + public int RaceId { get; set; } + private long _time; + private long _distance; + public Race(int raceId, long time, long distance) + { + RaceId = raceId; + _time = time; + _distance = distance; + } + + public List CalculateOptimalTimes() + { + var raceOption = new List(); + for (long i = 0; i < _time; i++) + { + var chargeTime = i; + var calcDistance = (_time - i) * chargeTime; + if (calcDistance > _distance) + { + raceOption.Add(new RaceOption() + { + SecondsPressed = chargeTime, + DistanceGone = calcDistance + }); + } + } + return raceOption; + } + } + + class RaceOption + { + public long SecondsPressed { get; set; } + public long DistanceGone { get; set; } + } +}