-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day9.cs
101 lines (87 loc) · 2.22 KB
/
Day9.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System.Text.RegularExpressions;
namespace AdventOfCode2023
{
internal class Day9
{
public static void RunPuzzle1()
{
string[] lines = File.ReadAllLines(@"Day9-Input.txt");
int sumHistory = 0;
foreach (string line in lines)
{
Regex regex = new Regex(@"[\d-]+");
List<int> list = new();
foreach (Match match in regex.Matches(line))
{
list.Add(int.Parse(match.Value));
}
List<int> lastNumber = new();
lastNumber.Add(list[^1]);
bool foundEnd = false;
List<int> listToCheck = list;
while (!foundEnd)
{
List<int> nextNumbers = new();
lastNumber.Add(listToCheck[^1] - listToCheck[^2]);
for (int i = 1; i < listToCheck.Count; i++)
{
int answer = listToCheck[i] - listToCheck[i - 1];
nextNumbers.Add(answer);
}
if (nextNumbers.Distinct().Count() == 1)
{
foundEnd = true;
}
listToCheck = nextNumbers;
}
int newNumber = lastNumber[^1];
for (int x = lastNumber.Count - 1; x > 0; x--)
{
newNumber += lastNumber[x - 1];
}
sumHistory += newNumber;
}
Console.WriteLine("Answer Puzzle 1: " + sumHistory);
}
public static void RunPuzzle2()
{
string[] lines = File.ReadAllLines(@"Day9-Input.txt");
int sumHistory = 0;
foreach (string line in lines)
{
Regex regex = new Regex(@"[\d-]+");
List<int> list = new();
foreach (Match match in regex.Matches(line))
{
list.Add(int.Parse(match.Value));
}
List<int> firstNumbers = new();
firstNumbers.Add(list[0]);
bool foundEnd = false;
List<int> listToCheck = list;
while (!foundEnd)
{
List<int> nextNumbers = new();
firstNumbers.Add(listToCheck[1] - listToCheck[0]);
for (int i = 1; i < listToCheck.Count; i++)
{
int answer = listToCheck[i] - listToCheck[i - 1];
nextNumbers.Add(answer);
}
if (nextNumbers.Distinct().Count() == 1)
{
foundEnd = true;
}
listToCheck = nextNumbers;
}
int newNumber = firstNumbers[^1];
for (int x = firstNumbers.Count - 1; x > 0; x--)
{
newNumber = firstNumbers[x - 1] - newNumber;
}
sumHistory += newNumber;
}
Console.WriteLine("Answer Puzzle 2: " + sumHistory);
}
}
}