diff --git a/15input.txt b/15input.txt new file mode 100644 index 0000000..f9dd93a --- /dev/null +++ b/15input.txt @@ -0,0 +1 @@ +7,14,0,17,11,1,2 \ No newline at end of file diff --git a/2020.csproj b/2020.csproj index a2edf80..590b5b5 100644 --- a/2020.csproj +++ b/2020.csproj @@ -53,6 +53,9 @@ PreserveNewest + + PreserveNewest + diff --git a/Program.cs b/Program.cs index 5a0ab1a..c57c53e 100644 --- a/Program.cs +++ b/Program.cs @@ -19,6 +19,7 @@ Q12.Go(); Q13.Go(); Q14.Go(); + Q15.Go(); Util.Log($"Total time={(System.DateTime.Now - start).TotalMilliseconds}ms"); } } diff --git a/Q15.cs b/Q15.cs new file mode 100644 index 0000000..b5b8ca6 --- /dev/null +++ b/Q15.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace _2020 +{ + class Q15 + { + static List list = new List(); + + public static void Go() + { + var start = DateTime.Now; + MakeList(); + Util.Log($"Q15 MakeList took {(DateTime.Now - start).TotalMilliseconds}ms"); + var p1start = DateTime.Now; + Part1(); + Util.Log($"Q15 part1 took {(DateTime.Now - p1start).TotalMilliseconds}ms"); + var p2start = DateTime.Now; + Part2(); + Util.Log($"Q15 part2 took {(DateTime.Now - p2start).TotalMilliseconds}ms"); + + Util.Log($"Q15 took {(DateTime.Now - start).TotalMilliseconds}ms"); + } + + static void MakeList() + { + var input = File.ReadAllText("15input.txt"); + foreach (var num in input.Split(',')) + { + list.Add(Convert.ToInt32(num)); + } + } + + static int GetNumAt(int turn) + { + var numsSaidDict = new Dictionary>(); + + int lastNumSaid = 0; + List entry = null; + for (int i = 0; i < turn; i++) + { + if (i < list.Count) + { + numsSaidDict.Add(list[i], new List() { i }); + lastNumSaid = list[i]; + } + else + { + if (i == list.Count) + { + lastNumSaid = 0; + } + else + { + if (entry != null) + { + lastNumSaid = entry.Count == 1 ? 0 : entry[^1] - entry[^2]; + } + else + { + lastNumSaid = 0; + } + } + + numsSaidDict.TryGetValue(lastNumSaid, out entry); + if (entry == null) + { + entry = new List(); + numsSaidDict.Add(lastNumSaid, entry); + } + + entry.Add(i); + } + } + + return lastNumSaid; + } + + static void Part1() + { + Util.Log($"Q15Part1: last num said={GetNumAt(2020)}"); + } + + static void Part2() + { + Util.Log($"Q15Part2: last num said={GetNumAt(30000000)}"); + } + } +}