chore(*): Move old solutions into a separate folder

This commit is contained in:
Josh Creek
2023-11-30 12:51:45 +00:00
parent ed3eb9cb54
commit b78d79a3af
117 changed files with 141 additions and 141 deletions
+9
View File
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>Day_01</RootNamespace>
</PropertyGroup>
</Project>
+69
View File
@@ -0,0 +1,69 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace Day_01
{
class Program
{
static void Main(string[] args)
{
//Part1();
Part2();
}
static void Part1()
{
var frequency = 0;
var lines = File.ReadAllLines("input.txt");
foreach (var line in lines)
{
if (line.Substring(0,1) == "+")
{
frequency += Int32.Parse(line.Substring(1));
}
else
{
frequency -= Int32.Parse(line.Substring(1));
}
}
Console.WriteLine("Part 1: The resulting frequency is " + frequency);
}
static void Part2()
{
int frequency = 0;
List<int> frequencyHistory = new List<int>();
int loopCount = 0;
bool foundDuplicate = false;
var lines = File.ReadAllLines("input.txt");
while (!foundDuplicate) {
foreach (var line in lines)
{
if (line.Substring(0,1) == "+")
{
frequency += Int32.Parse(line.Substring(1));
}
else
{
frequency -= Int32.Parse(line.Substring(1));
}
if (frequencyHistory.Contains(frequency)) {
Console.WriteLine("The first repeated frequency is " + frequency);
foundDuplicate = true;
break;
}
else {
frequencyHistory.Add(frequency);
}
}
loopCount += 1;
}
Console.WriteLine("The loop count is " + loopCount);
}
}
}
+16
View File
@@ -0,0 +1,16 @@
After feeling like you've been falling for a few minutes, you look at the device's tiny screen. "Error: Device must be calibrated before first use. Frequency drift detected. Cannot maintain destination lock." Below the message, the device shows a sequence of changes in frequency (your puzzle input). A value like +6 means the current frequency increases by 6; a value like -3 means the current frequency decreases by 3.
For example, if the device displays frequency changes of +1, -2, +3, +1, then starting from a frequency of zero, the following changes would occur:
Current frequency 0, change of +1; resulting frequency 1.
Current frequency 1, change of -2; resulting frequency -1.
Current frequency -1, change of +3; resulting frequency 2.
Current frequency 2, change of +1; resulting frequency 3.
In this example, the resulting frequency is 3.
Here are other example situations:
+1, +1, +1 results in 3
+1, +1, -2 results in 0
-1, -2, -3 results in -6
Starting with a frequency of zero, what is the resulting frequency after all of the changes in frequency have been applied?
+20
View File
@@ -0,0 +1,20 @@
You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice.
For example, using the same list of changes above, the device would loop as follows:
Current frequency 0, change of +1; resulting frequency 1.
Current frequency 1, change of -2; resulting frequency -1.
Current frequency -1, change of +3; resulting frequency 2.
Current frequency 2, change of +1; resulting frequency 3.
(At this point, the device continues from the start of the list.)
Current frequency 3, change of +1; resulting frequency 4.
Current frequency 4, change of -2; resulting frequency 2, which has already been seen.
In this example, the first frequency reached twice is 2. Note that your device might need to repeat its list of frequency changes many times before a duplicate frequency is found, and that duplicates might be found while in the middle of processing the list.
Here are other examples:
+1, -1 first reaches 0 twice.
+3, +3, +4, -2, -4 first reaches 10 twice.
-6, +3, +8, +5, -6 first reaches 5 twice.
+7, +7, -2, -7, -4 first reaches 14 twice.
What is the first frequency your device reaches twice?
+977
View File
@@ -0,0 +1,977 @@
-12
-6
-12
+1
+3
+3
-1
+10
-8
-9
-11
-2
-7
+15
+16
+14
-2
-5
+11
-8
-5
-1
-19
-14
+6
-16
-8
-13
-19
-11
+3
-19
+3
-19
+9
-15
-11
+18
-9
+13
-17
-16
-13
-16
+19
+17
-18
-8
-5
+6
+9
+8
-7
-8
+2
-9
+2
-9
-5
-3
+4
-13
-5
+11
+14
+5
+17
-1
+9
+6
+14
-9
+4
-3
-13
-5
+13
-2
-10
-18
-12
+4
+13
-10
-11
-10
-17
-13
+12
-19
-7
-13
+5
-8
-11
+5
+7
+17
-14
+22
+14
+7
-8
+7
-19
+14
-20
+16
+12
+3
+5
+1
-8
+1
+15
+3
-6
-8
+9
+3
-19
-19
-19
+1
-16
-13
+5
-13
+2
-15
-15
-4
+12
+1
-10
-5
-11
-9
-11
-7
+10
-18
+16
-12
-19
-17
-18
+2
+15
+11
+9
-17
+4
+9
-18
-6
-1
-1
-18
-15
-18
-7
+16
+18
+18
-2
-4
+1
+15
+16
+18
+7
-18
+6
+8
+15
-8
-16
-3
+11
+9
+1
+4
-18
+3
-16
-14
-18
-10
+6
-12
-12
-2
-8
+1
-3
-11
+1
-5
-4
-5
+8
+8
-4
-10
+16
-1
+3
+9
+6
+24
+12
-2
+11
-1
-9
+21
-15
+12
+19
-3
+21
+20
+16
-4
+15
+9
+13
-16
+13
-1
-16
+13
+19
+14
+19
+14
-17
+18
+1
+11
+18
+18
+22
-8
+18
-1
+19
-11
-20
+11
+8
-11
+25
+13
+3
-1
-3
+17
+15
+7
+19
-7
+19
-1
-12
-14
+17
-15
-1
-18
+9
+14
-19
+10
-9
-11
+7
+20
+20
-1
+19
+1
+7
-19
-15
+3
+1
+17
+11
-7
+15
-7
-10
+13
-24
-21
-4
-4
-14
+6
+3
-25
+9
-7
+15
+12
+14
+20
-11
-11
-15
-14
-9
-2
-2
-3
-1
-18
-2
+6
+17
+9
-1
+18
+20
+21
+27
-17
-11
-4
-18
+24
+33
+4
+12
+8
+8
-1
-17
+6
-18
+16
+4
+1
+6
-1
-11
+18
+15
+17
-4
+13
+1
-20
+18
+3
-16
-4
-12
-10
+8
-18
+22
+21
+12
+1
+6
-24
+7
+1
+11
+14
+20
-5
-2
+4
+9
-20
+60
+15
+18
+14
-19
+13
+3
+7
+8
+5
-14
-13
+20
+5
-1
-15
+29
+14
-19
+7
-10
+13
+3
-7
-2
-19
+8
-15
-13
-13
-1
-9
-14
+10
-9
+18
-3
-12
-7
+21
+2
+7
+7
+10
-15
-16
-6
-8
-18
+11
+13
+7
+10
-14
-14
+17
+22
+23
+15
-4
+32
+7
-5
-3
-10
-14
+9
+12
+10
-12
+17
+1
-19
+16
+14
-2
+1
-7
+17
+16
-8
-15
+18
+19
+14
+52
+8
-22
-2
-2
+13
+6
-4
+2
+20
-14
-73
+119
+20
+26
+4
+9
+14
-42
-18
+44
+18
-23
+77
-11
+15
+52
+29
-7
-11
+31
-29
+5
-20
+435
+15
-156
+71279
-19
-2
+11
-4
-1
-15
+8
+14
+19
-16
-13
+19
+3
-7
-1
-12
-15
-14
-2
+14
+8
-1
-1
-7
-2
-4
-8
-8
+7
+10
-14
-2
-13
-1
+8
-14
-9
+1
+17
-11
-13
+10
+9
+17
-18
-1
+10
-7
+11
-3
+10
+1
+8
-7
+26
+17
-16
-12
+22
-16
+9
-17
-7
+3
+13
-18
+8
+6
+15
+19
+7
+7
-18
+15
+14
+3
+10
-3
+2
+8
+9
-6
+10
+1
+15
-3
-11
+5
-8
-15
+11
-3
-19
-15
-10
+12
-8
+7
+2
+8
+3
-18
+3
-2
-5
-7
+21
+4
-6
+1
+3
+15
-16
+24
+15
-16
-2
-11
+10
-11
+17
+15
+8
+11
+21
+5
+12
+13
-15
-16
-14
+2
-11
+14
-13
+12
-17
+6
-13
+9
-1
+20
-18
-18
-21
-6
+21
+13
-12
-15
-5
+39
+20
+13
+6
-1
+12
+1
-3
+14
-5
-3
+17
+12
-13
+18
+16
-12
-16
-9
+5
-7
-1
-17
-4
-8
+5
-13
+9
-19
+15
+13
-19
-15
-2
+14
-2
-8
+2
+15
-5
-13
+19
+21
+3
+11
-17
+12
+17
+19
-16
+17
+5
-10
+13
+3
-8
+18
-8
-9
-11
+5
-11
-10
-19
+7
-3
-7
-11
+26
-10
+16
+13
-10
+5
+7
-16
+22
-9
-6
+40
-13
+7
-9
+20
+7
+8
-6
+3
-10
-14
+10
-2
+15
-3
+2
+17
+4
+3
+13
+15
-8
+16
+9
-10
+7
+4
+9
-4
+1
-13
-1
+10
-19
+20
-8
-9
-6
-15
-8
+11
+17
+9
-7
-17
-7
+9
+4
-7
+6
+9
-13
-5
-8
+6
-2
-16
+10
-15
+7
+4
+3
-2
+6
-14
-12
-10
+11
-10
+2
-15
-6
+8
-6
-4
+22
-6
+17
+8
+6
-8
-4
-21
-7
+2
+9
-26
-6
+5
-20
-38
-4
-45
-15
+14
-3
-12
+22
+12
-15
+29
-95
-15
-3
+1
-31
-22
-17
-7
-15
-5
+2
-3
+15
+12
-5
-10
+1
+7
-6
+17
+2
+2
-19
-7
+15
-6
-7
-1
+7
-12
-6
-18
-14
+6
-4
-16
-13
+5
-13
+4
+16
-8
+13
+11
-2
-7
-5
-8
+1
+9
+6
-2
+19
-4
+5
+10
+2
-9
+10
-15
+7
+11
+6
-14
-11
-6
+3
-16
-19
-6
-3
-3
-11
+19
+16
-10
+14
+15
+2
+15
+21
+15
+7
+19
+2
+52
+13
+24
-32
-126
-18
+1
-17
-14
-14
+3
-19
-17
+13
+17
-20
-1
+17
+2
+14
-7
-8
+12
-1
-14
+1
+26
-14
-17
+3
-17
+13
-3
+5
-7
+20
-2
+24
+20
-13
-19
-22
-19
+12
+35
+5
+34
+8
+2
+11
-2
-1
+13
-9
-7
-2
-28
-33
-71491
+9
View File
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>Day_02</RootNamespace>
</PropertyGroup>
</Project>
+124
View File
@@ -0,0 +1,124 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace Day_02
{
class Program
{
static void Main(string[] args)
{
//Part1();
Part2();
}
static void Part1()
{
int twiceCounter = 0;
int thriceCounter = 0;
var lines = File.ReadAllLines("input.txt");
foreach (var line in lines)
{
List<char> searchCharHistory = new List<char>();
int lineTwiceCounter = 0;
int lineThriceCounter = 0;
for (int i = 0; i < line.Length; i++)
{
char searchChar = line[i];
if(!searchCharHistory.Any(s => s == searchChar))
{
// If we haven't already counted this letter
int matchCharCount = line.Count(f => f == searchChar);
// Check if a letter appears twice (and increment the counter)
if (matchCharCount == 2) {
lineTwiceCounter += 1;
}
// Check if a letter appears three times (and increment the counter)
else if (matchCharCount == 3) {
lineThriceCounter += 1;
}
}
searchCharHistory.Add(searchChar);
}
if (lineTwiceCounter > 0) {
twiceCounter += 1;
}
if (lineThriceCounter > 0) {
thriceCounter += 1;
}
}
Console.WriteLine(twiceCounter);
Console.WriteLine(thriceCounter);
// multiply the two counters together
Console.WriteLine("The checksum is " + (twiceCounter * thriceCounter));
}
static void Part2()
{
bool endLoop = false;
var lines = File.ReadAllLines("input.txt");
// For each line of the input file
for (int i = 0; i < lines.Length; i++)
{
// Compare this line with each other line in the array
for (int j = 0; j < lines.Length; j++) {
if (CompareStrings(lines[i],lines[j])) {
// If it finds a string with just one letter wrong
endLoop = true;
break;
}
}
if (endLoop) {
break;
}
}
}
static bool CompareStrings(string string1, string string2)
{
if (string1 == string2) {
// Do nothing, it's the same string
}
// Split the characters of both strings into arrays
List<char> arr1 = new List<char>();
List<char> arr2 = new List<char>();
for (int ii = 0; ii < string1.Length; ii++) {
arr1.Add(string1[ii]);
}
for (int jj = 0; jj < string2.Length; jj++) {
arr2.Add(string2[jj]);
}
int wrongCharCounter = 0;
List<char> sameChars = new List<char>();
// For each letter in the first array, check if it corresponds to the appropriate letter in the second array
for (int kk = 0; kk < arr1.Count(); kk++) {
if (arr1[kk] != arr2[kk]) {
wrongCharCounter += 1;
}
else {
sameChars.Add(arr1[kk]);
}
}
if (wrongCharCounter == 1) {
Console.WriteLine("Common letters are: " + string.Join( ",", sameChars).Replace(",", ""));
return true;
}
else {
return false;
}
}
}
}
+23
View File
@@ -0,0 +1,23 @@
--- Day 2: Inventory Management System ---
You stop falling through time, catch your breath, and check the screen on the device. "Destination reached. Current Year: 1518. Current Location: North Pole Utility Closet 83N10." You made it! Now, to find those anomalies.
Outside the utility closet, you hear footsteps and a voice. "...I'm not sure either. But now that so many people have chimneys, maybe he could sneak in that way?" Another voice responds, "Actually, we've been working on a new kind of suit that would let him fit through tight spaces like that. But, I heard that a few days ago, they lost the prototype fabric, the design plans, everything! Nobody on the team can even seem to remember important details of the project!"
"Wouldn't they have had enough fabric to fill several boxes in the warehouse? They'd be stored together, so the box IDs should be similar. Too bad it would take forever to search the warehouse for two similar box IDs..." They walk too far away to hear any more.
Late at night, you sneak to the warehouse - who knows what kinds of paradoxes you could cause if you were discovered - and use your fancy wrist device to quickly scan every box and produce a list of the likely candidates (your puzzle input).
To make sure you didn't miss any, you scan the likely candidate boxes again, counting the number that have an ID containing exactly two of any letter and then separately counting those with exactly three of any letter. You can multiply those two counts together to get a rudimentary checksum and compare it to what your device predicts.
For example, if you see the following box IDs:
abcdef contains no letters that appear exactly two or three times.
bababc contains two a and three b, so it counts for both.
abbcde contains two b, but no letter appears exactly three times.
abcccd contains three c, but no letter appears exactly two times.
aabcdd contains two a and two d, but it only counts once.
abcdee contains two e.
ababab contains three a and three b, but it only counts once.
Of these box IDs, four of them contain a letter which appears exactly twice, and three of them contain a letter which appears exactly three times. Multiplying these together produces a checksum of 4 * 3 = 12.
What is the checksum for your list of box IDs?
+15
View File
@@ -0,0 +1,15 @@
--- Part Two ---
Confident that your list of box IDs is complete, you're ready to find the boxes full of prototype fabric.
The boxes will have IDs which differ by exactly one character at the same position in both strings. For example, given the following box IDs:
abcde
fghij
klmno
pqrst
fguij
axcye
wvxyz
The IDs abcde and axcye are close, but they differ by two characters (the second and fourth). However, the IDs fghij and fguij differ by exactly one character, the third (h and u). Those must be the correct boxes.
What letters are common between the two correct box IDs? (In the example above, this is found by removing the differing character from either ID, producing fgij.)
+250
View File
@@ -0,0 +1,250 @@
mphcuiszrnjzxwkbgdzqeoyxfa
mihcuisgrnjzxwkbgdtqeoylia
mphauisvrnjgxwkbgdtqeiylfa
mphcuisnrnjzxwkbgdgqeoylua
mphcuisurnjzxwkbgdtqeoilfi
mkhcuisvrnjzowkbgdteeoylfa
mphcoicvrnjzxwksgdtqeoylfa
mxhcuisvrndzxwkbgdtqeeylfa
dphcuisijnjzxwkbgdtqeoylfa
mihvuisvrqjzxwkbgdtqeoylfa
mphcuisrrnvzxwkbgdtqeodlfa
mphtuisdrnjzxskbgdtqeoylfa
mphcutmvsnjzxwkbgdtqeoylfa
mphcunsvrnjzswkggdtqeoylfa
mphcuisvrwjzxwkbpdtqeoylfr
mphcujsdrnjzxwkbgdtqeovlfa
mpfcuisvrdjzxwkbgdtteoylfa
mppcuisvrpjzxwkbgdtqeoywfa
mphcuisvrnjzxwkbfptqroylfa
mphcuisvrnjzxwkbgstoeoysfa
mphcufsvrnjzcwkbgdeqeoylfa
mphcuissrnjzxwkbgdkquoylfa
sphcuxsvrnjzxwkbgdtqioylfa
mphcuiivrhjzxwkbgdtqevylfa
echcuisvrnjzxwkbgltqeoylfa
mphcuisvrljexwkbvdtqeoylfa
mpjcuisvrnjzxwkhidtqeoylfa
mphcuisvrfjzmwkbgdtqeoylfl
mwhcuisvrnjzxwkbgdtqeoytfm
mphcuisvrsjzxwkbgdaqeoylfh
mohcuisvrnjzxwkbgdtqtoymfa
maycuisvrnjzxwkbgdtqboylfa
pphcuisvqnjzxwkbgdtqeoylfd
mprcuisvrnjtxwmbgdtqeoylfa
mfhcuisgrnjzxckbgdtqeoylfa
mphiubsvrnjzxwkbgdtqeoyufa
dphctisvrnjzxwkbgdtqeoylfk
mphcuisvrnjznwksgdtqeoyzfa
mpwcuisvrnjziwkbgdtqaoylfa
mphduzsvrnjznwkbgdtqeoylfa
mphccisvrnjzxwebgdtqeoylqa
xphcuisvrnjzxwkfvdtqeoylfa
mphcupsvrnjzxwkbgdtfeoylpa
mphcuisvrtjzjwkbgdtqeoylfe
mpbcuisvrnjzxwkbgdmieoylfa
mphcuisvrnjzxwkbgjtqetylaa
mphcuisvrnjzxwpbgdtgdoylfa
ophcufsvrqjzxwkbgdtqeoylfa
iphcuhsvrnjzxwkbgetqeoylfa
mphcuisvunjzxwwbgdtqeoylqa
mphcpisvrnjzowkbgdtveoylfa
mphcuisvrnjzxhkbgdtqeotlla
mphcuisvrnjzxwkbodtgeoylha
mphcuisvrjjzxwkbwdtqtoylfa
mphcwisvrnjnxwkbgjtqeoylfa
mplcuicqrnjzxwkbgdtqeoylfa
mphcuisvrnjzxydbgdtqeoylfn
ophckisvrnjzxwkbgdtqeozlfa
mphcuisvrkjzxwkbgdtteoblfa
yphcuisvrnjcxwkbggtqeoylfa
mphcuisvrnazxwfbqdtqeoylfa
mphcuisvrmjzxwkbgdtlwoylfa
mphctksvrnjzxwibgdtqeoylfa
mphcuisprnjzxlebgdtqeoylfa
mphcuisnrnjzxakbgdtueoylfa
mphcuiavrnjoxwtbgdtqeoylfa
nphcuisvrnjzxwkbgdtqzoylfk
mphcuisrrnjmxwkbgdtqdoylfa
mphcuisvrujzxwkvgdtqehylfa
mphcuisvrnfzxwkogdtqebylfa
mphcuisvrnjwdwkbgdtqeoyxfa
mphcuisvrntzxwkrgxtqeoylfa
mpzcuisvrnjzxwebgdtqeoylsa
aphcuikvrnjzxwwbgdtqeoylfa
mphcqisvrnjzxwkpgdtqeoelfa
mphcuusvrnjzxwkbgdtjeodlfa
mphcuisvrnjzewkbgdtteoylza
mphcuisvanjzxwkbgdtheoylfc
mphcjishrnjzxwkbgltqeoylfa
mpxcuislrnjzxwkbgdtqeoynfa
mphcuisvrnjjxwkbgdtmeoxlfa
mphcimsvrnjzxwkbsdtqeoylfa
mphcxisvcnjzxwjbgdtqeoylfa
mphcuisbrvjzxwkbgdtqeoymfa
mplcuisvrnjzxwkbgdtaenylfa
mphcuihvrnjzxwkygytqeoylfa
mphcbisvrnjzxhkbgdtqezylfa
mphcuisarnjzxwkbgatqeoylfv
mphcumsvrnjzxwkbgdrqebylfa
mlhcuisvrnwzxwkbgdtqeoylfx
mpkcuisvrkjzxwkbgdtqeoylfo
mphcuissrnjzxwkbgdtqmoylfc
mphcuiwvrnjuxwkfgdtqeoylfa
mphcuicvlnjzxwkbgdvqeoylfa
mphcuisvrvvzxwkbfdtqeoylfa
myhcuisvrnjpxwkbgntqeoylfa
mpocuisvrnjzxwtbgitqeoylfa
mphcuisvrnjzxwkbgdtwewyqfa
mphcuisvtnjzxwwbgdtqeoolfa
mphcuisvrnjzxgkbgdyqeoyyfa
mphcuisvrdjzxwkbgpyqeoylfa
bphcuisvrnjzxwkbgxtqefylfa
sphcuisvrdjzxwktgdtqeoylfa
mphcuvsvrnjmxwobgdtqeoylfa
mphcuisvrnjzxwkbsdtqeuylfb
mnhcmisvynjzxwkbgdtqeoylfa
mphckisvrnjzxwkhgdkqeoylfa
mpacuisvrnjzxwkbgdtqeoolaa
mpgcuisvrnjzxwkbzdtqeoynfa
mphcuisvrojzxwkbzdtqeoylga
mphcuisvknjfxwkbydtqeoylfa
mphcuistrnjzxwkbgdqqeuylfa
bpvcuiszrnjzxwkbgdtqeoylfa
mphcuxsvrnjzswkbgdtqeoelfa
mphcuisvbnjzxwlbgdtqeoylla
mphcuisvonczxwkbgktqeoylfa
mphcuisvrnkzxwvbgdtquoylfa
mphcuisvrnjzxokfgdtqeoylia
tphcuisvrnjzxwkbjdwqeoylfa
mihcuisvrnjzpwibgdtqeoylfa
mphcuisvrejzxwkbgdtqjuylfa
mprcuisvrnjixwkxgdtqeoylfa
mpqcuiszrnjzxwkbgdtqeodlfa
mphcuasvrnjzzakbgdtqeoylva
mphcuisvrnjzmwkbtdtqeoycfa
mphcuisvrnjzxwkbcdtqioylxa
mphckisvrnjzxwkbcdtqeoylfm
mphcuisvrnjuxwbogdtqeoylfa
mphcuisdrnjzxwkbldtqeoylfx
mphcuisvrnjoxwkbgdtqeyyyfa
mphcuicvqnjzxwkbgdtqeoylna
mpmcuisvrnjzxwkbgdtqktylfa
mphcuisvrnqzxwkggdtqeoykfa
mphcuisvryjzxwkbydtqejylfa
mphcugsvrnjzxwkbghtqeeylfa
rphcuusvrnjzxwkwgdtqeoylfa
zphwuiyvrnjzxwkbgdtqeoylfa
cphcuivvrnjzxwkbgdtqenylfa
mphcuisvrnjzxwkagotqevylfa
mprcuisvrcjzxwkbgdtqeoytfa
mphjugsvrnezxwkbgdtqeoylfa
mphcuisvryjzxwkbgltqeoylaa
mphcursvrnjzxfkbgdtqeoydfa
mphcuisvrcuzxwkbgdtqeoylfw
mphcuisvrijzxwkbgdtqeoelfh
xphcuisvenjzxjkbgdtqeoylfa
mphcuisvrnazxwkbgdeqeoylaa
mphcuisbrsjzxwkbgdtqeoygfa
mlhvuisvrnjzxwkbgdtqeoylfh
mphcuisvrnjzxukbgdtqeoyhfy
mpzcuilvrnjzawkbgdtqeoylfa
hphcuisjfnjzxwkbgdtqeoylfa
mahcuisvrnjzxwkegdtqeoylfi
mphcuixvrnjzcwkbgdtqetylfa
mphcuisvrnjzxwkdgdtqeoklfj
mlhcuisvrnjzxwkbgdteeoylka
mphcuifvrnjbxwkrgdtqeoylfa
mphcuasvrnjzzwkbgdtqeoylva
mphcuisvrnjzxwkboutqeoylba
mbhcuisvcnjzxwklgdtqeoylfa
mpbcuisvrnjzxgkbgdtqesylfa
mphcuisvrnjfswkbgdtqeoylfd
mphcuisvrnjzxwkbgdoweoysfa
uphcuisvrnjzrwkbgdtqelylfa
mphcuisvrnjzxwkbgdtqyoylsi
mpqcuiqvxnjzxwkbgdtqeoylfa
mphcuisorfjzxwkbgatqeoylfa
mphcuisvrntfxwkbzdtqeoylfa
mphcuisvrnrzxwkbgdtueoylfl
mphcuisvrnjzewkagdtyeoylfa
mpocuisdrnjzxwkbgdtqeozlfa
mphcuisvrnjjxwkbgdtoeoylfm
mphcuisvenjzxwkbgdtqwoylza
mpmcuisvrnjzxwkbgdtqeoxlfr
mphcuisvgnjhxwkbgdtqeoplfa
mphcuisvrnjzowkdgdtqeoyyfa
mphcuisqynjzxwkbgdtqeoylda
hphcuisvgnjzxwkbgdtbeoylfa
iphcuipvrnuzxwkbgdtqeoylfa
mphcuisvrnjzsikbpdtqeoylfa
mpwcuhsvrnjzxbkbgdtqeoylfa
mnhjuisvcnjzxwkbgdtqeoylfa
mphcudsvrnjzxwkbgdtqloilfa
mpncuiwvrwjzxwkbgdtqeoylfa
mphcuisvrnjgawkbgdtqeoylya
mphcuisvrnjzxwkbggtteoslfa
mphcuisvrnjzxwkbgdvqeoylpe
mphcuisvrnczxfkbgktqeoylfa
mphcuifvrnjzxwkbgdbmeoylfa
mphcuisvrnjytwkbgdtqeoylla
mphcuisvrnjzxwkbgdtjeoxlfn
mphjuisvrnjzxwkbghtqeoyffa
mphcuisvrnjzxkrbgdtqeoylaa
mphcbisvrnjzxwkbgttqeoylfs
mphkuksvbnjzxwkbgdtqeoylfa
nphcuidvrnjzxwhbgdtqeoylfa
mphguzsvrnjzxwkbgdaqeoylfa
mihcuisfrnjzxwkbgdtqhoylfa
mphcuisvrnrzxwpbgdtqesylfa
zphcuisvrnjzxwkbddtqeoylaa
mphcuigvmnjzxwkbgdtqeoylba
mjhcuisvrnjzxjkbgdtqeoylha
mphnuisvrnjznwkbgdtqnoylfa
mkhcuisvrnjcxwkbgdqqeoylfa
mphcuisvenjzxwbbqdtqeoylfa
qphcuisnrnjzawkbgdtqeoylfa
mphcuisvrdjzxwkbgdtqeoywca
mphcuzsvvnjzxwfbgdtqeoylfa
pphcuxsvrnjzxwkbgdtmeoylfa
mphiuvsvrnjzxlkbgdtqeoylfa
mphlqisvrnjzxkkbgdtqeoylfa
mmhcuisvrnjzxwkbgatqeoylea
mphduisrrnjoxwkbgdtqeoylfa
mphcuisvrnjnxwkvgdyqeoylfa
mphcuvsvrnjzxgkbgdtqeoylfz
mphcuisvryjzxwkbggtqkoylfa
iphcuisvrdjzxwkbgotqeoylfa
mphcuisvrnjzxwhbgdtqwoyofa
mphcorbvrnjzxwkbgdtqeoylfa
mghcuisvrnpzxykbgdtqeoylfa
mphauisvrnjnxwkbzdtqeoylfa
mphcgisvrnjzxwkwgdtqeoygfa
mphcuisvrnjzxwkggotqeoylba
mphcuesvrnjzxwkbgdwqebylfa
yphcuisvrnjzxwkbgdxqeoylja
ephyuisvrnjzywkbgdtqeoylfa
mfhcuisqrnjzxwkbgdlqeoylfa
mphkuisvrnjzxwkbertqeoylfa
mphcuusgrnjzxwkbggtqeoylfa
mphcuildrnjvxwkbgdtqeoylfa
mphcuiuvrnjzlwkbgwtqeoylfa
mppcuisvrljzxwkbgdtqeoylfw
mphcwiwvrnjzxwsbgdtqeoylfa
mphcubivrnjzxwkqgdtqeoylfa
mphcuisvrnjpxwkngdtqeoylpa
pchcuisvrgjzxwkbgdtqeoylfa
mphcuisvlnjzxwkbgdtmeoylfw
mphcuisvrnjzywkbgdvqeoylfj
mpzcuisvrnezxwktgdtqeoylfa
mphcuisvrnjbxwkbgzrqeoylfa
mphcuisvrnjzxwktgdtqeodtfa
jphcuiavrnjzxwkbgdtqeoylfv
mphcuisvrnjzxwkbddppeoylfa
mphcuissrkjzxwkbgxtqeoylfa
mphcuisvrhjzxwxbgdtqeoylxa
mphcvisvgnjjxwkbgdtqeoylfa
mphcuisprnjwxwtbgdtqeoylfa
mphcuissrnjzxqkbgdtqeoymfa
mphcuiabrnjzxokbgdtqeoylfa
mphcuisvrnczxwkbgmtpeoylfa
+11
View File
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
namespace Day_03
{
public class Claim
{
public int ClaimId { get; set; }
public bool CellsUsedMoreThanOnce { get; set; }
}
}
+9
View File
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>Day_03</RootNamespace>
</PropertyGroup>
</Project>
+128
View File
@@ -0,0 +1,128 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Day_03
{
class Program
{
static void Main(string[] args)
{
// Declare an empty 2D array with 1000x1000 cells, material[x,y] from left and top respectively
int[,] material = new int[1000, 1000];
List<Claim> claims = new List<Claim>();
var lines = File.ReadAllLines("input.txt");
// For each line of the input file
foreach (var line in lines)
{
// A claim like #123 @ 3,2: 5x4 means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall.
// Remove the id number and everything prior to the left edge measurement
int startIndex = line.IndexOf("@") + 1;
int endIndex = line.Length;
var lineData = line.Substring(startIndex, endIndex - startIndex);
// Store all the data
Regex re1 = new Regex(@"(@ [0-9]+,)");
var leftPositionList = re1.Matches(line);
string leftPosition = leftPositionList[0].Value.Substring(2, leftPositionList[0].Value.Length -1 - 2);
Regex re2 = new Regex(@"(,[0-9]+:)");
var topPositionList = re2.Matches(line);
string topPosition = topPositionList[0].Value.Substring(1, topPositionList[0].Value.Length -1 - 1);
Regex re3 = new Regex(@"(: [0-9]+x)");
var widthList = re3.Matches(line);
int width = Int32.Parse(widthList[0].Value.Substring(1, widthList[0].Value.Length -1 - 1));
Regex re4 = new Regex(@"(x[0-9]+)");
var lengthList = re4.Matches(line);
int length = Int32.Parse(lengthList[0].Value.Substring(1));
// Store data in all cells horizontally and vertically
for (int i = 0; i < width; i++) {
for (int j = 0; j < length; j++) {
// Store a count of how many times the cell is used at the appropriate co-ordinates
material[(Int32.Parse(leftPosition) + i), (Int32.Parse(topPosition) + j)] += 1;
}
}
}
// Part 1
// Loop through both arrays and count how many cells have a recorded overlap
int overlapCounter = 0;
for(int i = 0; i < 1000; i++){
for(int j = 0; j < 1000; j++){
if(material[i, j] > 1){
overlapCounter += 1;
}
}
}
Console.WriteLine(material[0, 0]);
Console.WriteLine(material.Length);
Console.WriteLine("The number of overlapping square inches is " + overlapCounter);
// Part 2
// Loop through all claims (lines in the file) and find the one where the material is only used once in every cell
// For each line of the input file
foreach (var line in lines)
{
var claim = new Claim();
// A claim like #123 @ 3,2: 5x4 means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall.
// Remove the id number and everything prior to the left edge measurement
int startIndex = line.IndexOf("@") + 1;
int endIndex = line.Length;
var lineData = line.Substring(startIndex, endIndex - startIndex);
// Store all the data
Regex re0 = new Regex(@"(#(\d+))");
var claimIdList = re0.Matches(line);
string claimId = claimIdList[0].Value.Substring(1);
claim.ClaimId = Int32.Parse(claimId);
Regex re1 = new Regex(@"(@ [0-9]+,)");
var leftPositionList = re1.Matches(line);
string leftPosition = leftPositionList[0].Value.Substring(2, leftPositionList[0].Value.Length -1 - 2);
Regex re2 = new Regex(@"(,[0-9]+:)");
var topPositionList = re2.Matches(line);
string topPosition = topPositionList[0].Value.Substring(1, topPositionList[0].Value.Length -1 - 1);
Regex re3 = new Regex(@"(: [0-9]+x)");
var widthList = re3.Matches(line);
int width = Int32.Parse(widthList[0].Value.Substring(1, widthList[0].Value.Length -1 - 1));
Regex re4 = new Regex(@"(x[0-9]+)");
var lengthList = re4.Matches(line);
int length = Int32.Parse(lengthList[0].Value.Substring(1));
// Store data in all cells horizontally and vertically
for (int i = 0; i < width; i++) {
for (int j = 0; j < length; j++) {
// Check how many times the cell has been used at the appropriate co-ordinates
// If it has been used more than once, set CellsUsedMoreThanOnce to true
if (material[(Int32.Parse(leftPosition) + i), (Int32.Parse(topPosition) + j)] > 1)
{
claim.CellsUsedMoreThanOnce = true;
}
}
}
claims.Add(claim);
}
// Find the only claim that has no overlap
int finalClaimId = claims.First(c => !c.CellsUsedMoreThanOnce).ClaimId;
Console.WriteLine("The ID of the only claim that doesn't overlap is: " + finalClaimId);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
--- Day 3: No Matter How You Slice It ---
The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit (thanks to someone who helpfully wrote its box IDs on the wall of the warehouse in the middle of the night). Unfortunately, anomalies are still affecting them - nobody can even agree on how to cut the fabric.
The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.
Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:
The number of inches between the left edge of the fabric and the left edge of the rectangle.
The number of inches between the top edge of the fabric and the top edge of the rectangle.
The width of the rectangle in inches.
The height of the rectangle in inches.
A claim like #123 @ 3,2: 5x4 means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. Visually, it claims the square inches of fabric represented by # (and ignores the square inches of fabric represented by .) in the diagram below:
...........
...........
...#####...
...#####...
...#####...
...#####...
...........
...........
...........
The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
#1 @ 1,3: 4x4
#2 @ 3,1: 4x4
#3 @ 5,5: 2x2
Visually, these claim the following areas:
........
...2222.
...2222.
.11XX22.
.11XX22.
.111133.
.111133.
........
The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.)
If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
+6
View File
@@ -0,0 +1,6 @@
--- Part Two ---
Amidst the chaos, you notice that exactly one claim doesn't overlap by even a single square inch of fabric with any other claim. If you can somehow draw attention to it, maybe the Elves will be able to make Santa's suit after all!
For example, in the claims above, only claim 3 is intact after all claims are made.
What is the ID of the only claim that doesn't overlap?
File diff suppressed because it is too large Load Diff
+12
View File
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
namespace Day_04
{
public class Action
{
public string Date { get; set; }
public string Time { get; set; }
public string Description { get; set; }
}
}
+9
View File
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>Day_04</RootNamespace>
</PropertyGroup>
</Project>
+12
View File
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
namespace Day_04
{
public class Day
{
public string Date { get; set; }
public int GuardId { get; set; }
public List<bool> IsAsleepThisMinute { get; set; }
}
}
+12
View File
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
namespace Day_04
{
public class Guard
{
public int GuardId { get; set; }
public int TotalMinutesAsleep { get; set; }
public List<int> TimesSleptPerMinute { get; set; }
}
}
+81
View File
@@ -0,0 +1,81 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Day_04
{
class Program
{
static void Main(string[] args)
{
// Find the guard that has the most minutes asleep.
// What minute does that guard spend asleep the most?
// Make an empty list of guards
List<Guard> guards = new List<Guard>();
// Take in an unordered list of times and dates when guards start shifts, fall asleep and wake up
var lines = File.ReadAllLines("input.txt");
// Sort that into an ordered list, by date then time
List<Action> actions = new List<Action>();
foreach (var line in lines)
{
Action action = new Action();
Regex re1 = new Regex(@"((\d\d\d\d-\d\d-\d\d))");
var dateString = re1.Matches(line)[0].Value;
action.Date = dateString.Substring(0, dateString.Length);
Regex re2 = new Regex(@"((\d\d:\d\d))");
var timeString = re2.Matches(line)[0].Value;
action.Time = timeString.Substring(0, timeString.Length);
Regex re3 = new Regex(@"(\] (.*))");
Match match3 = re3.Match(line);
action.Description = match3.Groups[2].Value;
actions.Add(action);
}
actions = actions.OrderBy(a => a.Date).ThenBy(a => a.Time).ToList();
// Use the ordered list to create a list of days with the guard id and a breakdown of minutes slept and awake
List<Day> days = new List<Day>();
foreach (var action in actions)
{
Day day = new Day();
if(days.Any(d => d.Date == action.Date))
{
day = days.First
}
day.Date = action.Date;
Regex re1 = new Regex(@"(#(\d+))");
Match match1 = re1.Match(action.Description);
if (match1.Success)
{
day.GuardId = Int32.Parse(match1.Groups[2].Value);
}
else
{
// Use the ID from a previous action on the same day
day.GuardId = days.First(d => d.Date == day.Date).GuardId;
}
// Date
// GuardId
// IsAsleepThisMinute
}
// Use the list of days to populate the list of guards
}
}
}
+49
View File
@@ -0,0 +1,49 @@
--- Day 4: Repose Record ---
You've sneaked into another supply closet - this time, it's across from the prototype suit manufacturing lab. You need to sneak inside and fix the issues with the suit, but there's a guard stationed outside the lab, so this is as close as you can safely get.
As you search the closet for anything that might help, you discover that you're not the first person to want to sneak in. Covering the walls, someone has spent an hour starting every midnight for the past few months secretly observing this guard post! They've been writing down the ID of the one guard on duty that night - the Elves seem to have decided that one guard was enough for the overnight shift - as well as when they fall asleep or wake up while at their post (your puzzle input).
For example, consider the following records, which have already been organized into chronological order:
[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-01 00:30] falls asleep
[1518-11-01 00:55] wakes up
[1518-11-01 23:58] Guard #99 begins shift
[1518-11-02 00:40] falls asleep
[1518-11-02 00:50] wakes up
[1518-11-03 00:05] Guard #10 begins shift
[1518-11-03 00:24] falls asleep
[1518-11-03 00:29] wakes up
[1518-11-04 00:02] Guard #99 begins shift
[1518-11-04 00:36] falls asleep
[1518-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up
Timestamps are written using year-month-day hour:minute format. The guard falling asleep or waking up is always the one whose shift most recently started. Because all asleep/awake times are during the midnight hour (00:00 - 00:59), only the minute portion (00 - 59) is relevant for those events.
Visually, these records show that the guards are asleep at these times:
Date ID Minute
000000000011111111112222222222333333333344444444445555555555
012345678901234567890123456789012345678901234567890123456789
11-01 #10 .....####################.....#########################.....
11-02 #99 ........................................##########..........
11-03 #10 ........................#####...............................
11-04 #99 ....................................##########..............
11-05 #99 .............................................##########.....
The columns are Date, which shows the month-day portion of the relevant day; ID, which shows the guard on duty that day; and Minute, which shows the minutes during which the guard was asleep within the midnight hour. (The Minute column's header shows the minute's ten's digit in the first row and the one's digit in the second row.) Awake is shown as ., and asleep is shown as #.
Note that guards count as asleep on the minute they fall asleep, and they count as awake on the minute they wake up. For example, because Guard #10 wakes up at 00:25 on 1518-11-01, minute 25 is marked as awake.
If you can figure out the guard most likely to be asleep at a specific time, you might be able to trick that guard into working tonight so you can have the best chance of sneaking in. You have two strategies for choosing the best guard/minute combination.
Strategy 1: Find the guard that has the most minutes asleep. What minute does that guard spend asleep the most?
In the example above, Guard #10 spent the most minutes asleep, a total of 50 minutes (20+25+5), while Guard #99 only slept for a total of 30 minutes (10+10+10). Guard #10 was asleep most during minute 24 (on two days, whereas any other minute the guard was asleep was only seen on one day).
While this example listed the entries in chronological order, your entries are in the order you found them. You'll need to organize them before they can be analyzed.
What is the ID of the guard you chose multiplied by the minute you chose? (In the above example, the answer would be 10 * 24 = 240.)
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>Day_01</RootNamespace>
</PropertyGroup>
</Project>
+99
View File
@@ -0,0 +1,99 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace Day_01
{
class Program
{
static void Main(string[] args)
{
//Part1();
Part2();
//Test();
}
static void Part1()
{
// Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
var totalFuel = 0;
var lines = File.ReadAllLines("input.txt");
foreach (var line in lines)
{
var mass = Int32.Parse(line);
//divide by 3
decimal dividedAnswer = mass / 3;
// round down & subtract 2
var answer = Convert.ToInt32(Math.Floor(dividedAnswer)) - 2;
// add to total fuel count
totalFuel += answer;
}
// The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
// What is the sum of the fuel requirements for all of the modules on your spacecraft?
Console.WriteLine("Part 1: The sum of the fuel requirements for all of the modules on your spacecraft is " + totalFuel);
}
static int CalculateFuelNeeded(int mass)
{
//divide by 3
decimal dividedAnswer = mass / 3;
// round down & subtract 2
var answer = Convert.ToInt32(Math.Floor(dividedAnswer)) - 2;
// add to total fuel count
return answer;
}
static void Part2()
{
List<int> fuels = new List<int>();
var lines = File.ReadAllLines("input.txt");
foreach (var line in lines)
{
var mass = Int32.Parse(line);
// Calculate the fuel needed for the mass
var originalMassFuel = CalculateFuelNeeded(mass);
var nextFuel = CalculateFuelNeeded(originalMassFuel);
var totalFuel = originalMassFuel;
// Now calculate the fuel needed for the mass of the fuel, ad nauseum
// A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which would call for a negative fuel), so the total fuel required is still just 2.
// At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.
var keepCalculating = true;
if(nextFuel > 0)
{
Console.WriteLine(nextFuel);
while(keepCalculating)
{
totalFuel += nextFuel;
nextFuel = CalculateFuelNeeded(nextFuel);
Console.WriteLine(nextFuel);
if(nextFuel <= 0)
{
keepCalculating = false;
}
}
}
fuels.Add(totalFuel);
}
// The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
int finalTotal = fuels.Sum(x => x);
// What is the sum of the fuel requirements for all of the modules on your spacecraft?
Console.WriteLine("Part 2: The sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel is " + finalTotal);
}
}
}
+20
View File
@@ -0,0 +1,20 @@
--- Day 1: The Tyranny of the Rocket Equation ---
Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
The Elves quickly load you into a spacecraft and prepare to launch.
At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet.
Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
For example:
For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
For a mass of 1969, the fuel required is 654.
For a mass of 100756, the fuel required is 33583.
The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
What is the sum of the fuel requirements for all of the modules on your spacecraft?
+11
View File
@@ -0,0 +1,11 @@
--- Part Two ---
During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker stops the launch sequence. Apparently, you forgot to include additional fuel for the fuel you just added.
Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However, that fuel also requires fuel, and that fuel requires fuel, and so on. Any mass that would require negative fuel should instead be treated as if it requires zero fuel; the remaining mass, if any, is instead handled by wishing really hard, which has no mass and is outside the scope of this calculation.
So, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative. For example:
A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which would call for a negative fuel), so the total fuel required is still just 2.
At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.
The fuel required by a module of mass 100756 and its fuel is: 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.
What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel? (Calculate the fuel requirements for each module separately, then add them all up at the end.)
+100
View File
@@ -0,0 +1,100 @@
94794
58062
112067
139512
147400
99825
142617
107263
86294
97000
140204
72573
134981
111385
88303
79387
129111
122976
130685
75100
146566
73191
107641
109940
65518
102028
57370
144556
64017
64384
145114
115853
87939
90791
133443
139050
140657
85738
133749
92466
142918
96679
125035
127629
87906
104478
105147
121741
70312
73732
60838
82292
102931
103000
135903
78678
86314
50772
115673
106179
60615
105152
76550
140591
120916
62094
111273
63542
102974
78837
94840
89126
63150
52503
108530
101458
59660
116913
66440
83306
50693
58377
62005
130663
124304
79726
63001
73380
64395
124277
69742
63465
93172
142068
120081
119872
52801
100693
79229
90365
+9
View File
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>Day_02</RootNamespace>
</PropertyGroup>
</Project>
+114
View File
@@ -0,0 +1,114 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace Day_02
{
class Program
{
static void Main(string[] args)
{
//Part1();
Part2();
}
static List<int> RunProgram(List<int> inputList)
{
// Once you're done processing an opcode, move to the next one by stepping forward 4 positions.
for (int i = 0; i < inputList.Count(); i+=4)
{
int num1position = inputList[i+1];
int num1 = inputList[num1position];
int num2position = inputList[i+2];
int num2 = inputList[num2position];
switch (inputList[i])
{
case 1:
// Opcode 1 adds together numbers read from two positions and stores the result in a third position. The three integers immediately after the opcode tell you these three positions - the first two indicate the positions from which you should read the input values, and the third indicates the position at which the output should be stored.
// For example, if your Intcode computer encounters 1,10,20,30, it should read the values at positions 10 and 20, add those values, and then overwrite the value at position 30 with their sum.
int calculatedValue1 = num1 + num2;
int calculatedValue1Position = inputList[i+3];
inputList[calculatedValue1Position] = calculatedValue1;
break;
case 2:
// Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead of adding them. Again, the three integers after the opcode indicate where the inputs and outputs are, not their values.
int calculatedValue2 = num1 * num2;
int calculatedValue2Position = inputList[i+3];
inputList[calculatedValue2Position] = calculatedValue2;
break;
default:
// Finally return the list
return inputList;
}
}
// Finally return the list
return inputList;
}
static void Part1()
{
// There is only one line so get it
var input = File.ReadAllLines("input.txt")[0];
List<int> inputList = input.Split(',').Select(int.Parse).ToList();
// Replace position 1 with value 12
inputList[1] = 12;
// Replace position 2 with value 2
inputList[2] = 2;
// Run the program stored in the input
List<int> outputList = RunProgram(inputList);
Console.WriteLine("Part 1: The value is left at position 0 after the program halts is " + outputList[0]);
}
static void Part2()
{
// There is only one line so get it
var input = File.ReadAllLines("input.txt")[0];
List<int> inputList = input.Split(',').Select(int.Parse).ToList();
int finalNoun = 0;
int finalVerb = 0;
List<int> inputListModified = new List<int>(){};
for (int noun = 0; noun < 100; noun++)
{
for (int verb = 0; verb < 100; verb++)
{
// Reset the input list - .ToList() is needed here to ensure it's actually a new list, not just a reference to the original list
inputListModified = inputList.ToList();
// Replace position 1 with noun
inputListModified[1] = noun;
// Replace position 2 with verb
inputListModified[2] = verb;
// Run the program stored in the input
List<int> outputList = RunProgram(inputListModified);
if(outputList[0] == 19690720)
{
finalNoun = noun;
finalVerb = verb;
Console.WriteLine(noun + " - " + verb);
}
}
}
Console.WriteLine("Part 2: The pair of inputs that produce the output 19690720 are " + finalNoun + " and " + finalVerb);
Console.WriteLine($"100 * noun + verb is {100 * finalNoun + finalVerb}");
}
}
}
+45
View File
@@ -0,0 +1,45 @@
--- Day 2: 1202 Program Alarm ---
On the way to your gravity assist around the Moon, your ship computer beeps angrily about a "1202 program alarm". On the radio, an Elf is already explaining how to handle the situation: "Don't worry, that's perfectly norma--" The ship computer bursts into flames.
You notify the Elves that the computer's magic smoke seems to have escaped. "That computer ran Intcode programs like the gravity assist program it was working on; surely there are enough spare parts up there to build a new Intcode computer!"
An Intcode program is a list of integers separated by commas (like 1,0,0,3,99). To run one, start by looking at the first integer (called position 0). Here, you will find an opcode - either 1, 2, or 99. The opcode indicates what to do; for example, 99 means that the program is finished and should immediately halt. Encountering an unknown opcode means something went wrong.
Opcode 1 adds together numbers read from two positions and stores the result in a third position. The three integers immediately after the opcode tell you these three positions - the first two indicate the positions from which you should read the input values, and the third indicates the position at which the output should be stored.
For example, if your Intcode computer encounters 1,10,20,30, it should read the values at positions 10 and 20, add those values, and then overwrite the value at position 30 with their sum.
Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead of adding them. Again, the three integers after the opcode indicate where the inputs and outputs are, not their values.
Once you're done processing an opcode, move to the next one by stepping forward 4 positions.
For example, suppose you have the following program:
1,9,10,3,2,3,11,0,99,30,40,50
For the purposes of illustration, here is the same program split into multiple lines:
1,9,10,3,
2,3,11,0,
99,
30,40,50
The first four integers, 1,9,10,3, are at positions 0, 1, 2, and 3. Together, they represent the first opcode (1, addition), the positions of the two inputs (9 and 10), and the position of the output (3). To handle this opcode, you first need to get the values at the input positions: position 9 contains 30, and position 10 contains 40. Add these numbers together to get 70. Then, store this value at the output position; here, the output position (3) is at position 3, so it overwrites itself. Afterward, the program looks like this:
1,9,10,70,
2,3,11,0,
99,
30,40,50
Step forward 4 positions to reach the next opcode, 2. This opcode works just like the previous, but it multiplies instead of adding. The inputs are at positions 3 and 11; these positions contain 70 and 50 respectively. Multiplying these produces 3500; this is stored at position 0:
3500,9,10,70,
2,3,11,0,
99,
30,40,50
Stepping forward 4 more positions arrives at opcode 99, halting the program.
Here are the initial and final states of a few more small programs:
1,0,0,0,99 becomes 2,0,0,0,99 (1 + 1 = 2).
2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2 = 6).
2,4,4,5,99,0 becomes 2,4,4,5,99,9801 (99 * 99 = 9801).
1,1,1,4,99,5,6,0,99 becomes 30,1,1,4,2,5,6,0,99.
Once you have a working computer, the first step is to restore the gravity assist program (your puzzle input) to the "1202 program alarm" state it had just before the last computer caught fire. To do this, before running the program, replace position 1 with the value 12 and replace position 2 with the value 2. What value is left at position 0 after the program halts?
+18
View File
@@ -0,0 +1,18 @@
--- Part Two ---
"Good, the new computer seems to be working correctly! Keep it nearby during this mission - you'll probably use it again. Real Intcode computers support many more features than your new one, but we'll let you know what they are as you need them."
"However, your current priority should be to complete your gravity assist around the Moon. For this mission to succeed, we should settle on some terminology for the parts you've already built."
Intcode programs are given as a list of integers; these values are used as the initial state for the computer's memory. When you run an Intcode program, make sure to start by initializing memory to the program's values. A position in memory is called an address (for example, the first value in memory is at "address 0").
Opcodes (like 1, 2, or 99) mark the beginning of an instruction. The values used immediately after an opcode, if any, are called the instruction's parameters. For example, in the instruction 1,2,3,4, 1 is the opcode; 2, 3, and 4 are the parameters. The instruction 99 contains only an opcode and has no parameters.
The address of the current instruction is called the instruction pointer; it starts at 0. After an instruction finishes, the instruction pointer increases by the number of values in the instruction; until you add more instructions to the computer, this is always 4 (1 opcode + 3 parameters) for the add and multiply instructions. (The halt instruction would increase the instruction pointer by 1, but it halts the program instead.)
"With terminology out of the way, we're ready to proceed. To complete the gravity assist, you need to determine what pair of inputs produces the output 19690720."
The inputs should still be provided to the program by replacing the values at addresses 1 and 2, just like before. In this program, the value placed in address 1 is called the noun, and the value placed in address 2 is called the verb. Each of the two input values will be between 0 and 99, inclusive.
Once the program has halted, its output is available at address 0, also just like before. Each time you try a pair of inputs, make sure you first reset the computer's memory to the values in the program (your puzzle input) - in other words, don't reuse memory from a previous attempt.
Find the input noun and verb that cause the program to produce the output 19690720. What is 100 * noun + verb? (For example, if noun=12 and verb=2, the answer would be 1202.)
+1
View File
@@ -0,0 +1 @@
1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,6,1,19,1,5,19,23,2,6,23,27,1,27,5,31,2,9,31,35,1,5,35,39,2,6,39,43,2,6,43,47,1,5,47,51,2,9,51,55,1,5,55,59,1,10,59,63,1,63,6,67,1,9,67,71,1,71,6,75,1,75,13,79,2,79,13,83,2,9,83,87,1,87,5,91,1,9,91,95,2,10,95,99,1,5,99,103,1,103,9,107,1,13,107,111,2,111,10,115,1,115,5,119,2,13,119,123,1,9,123,127,1,5,127,131,2,131,6,135,1,135,5,139,1,139,6,143,1,143,6,147,1,2,147,151,1,151,5,0,99,2,14,0,0
+9
View File
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>Day_03</RootNamespace>
</PropertyGroup>
</Project>
+197
View File
@@ -0,0 +1,197 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace Day_03
{
class Program
{
static void Main(string[] args)
{
//Part1();
Part2();
}
public class WireTouchPoint
{
public int x { get; set; }
public int y { get; set; }
}
static List<WireTouchPoint> FindAllWireTouchPoints(List<string> wireCommands)
{
List<WireTouchPoint> touchPoints = new List<WireTouchPoint>(){};
int currentX = 0;
int currentY = 0;
WireTouchPoint initialWTP = new WireTouchPoint();
initialWTP.x = currentX;
initialWTP.y = currentY;
touchPoints.Add(initialWTP);
// For each command, record every co-ordinate the wire touches
foreach(string wireCommand in wireCommands)
{
// Not bothering with error catching for converting strings to ints as the data cannot be wrongly typed in the input file
int distance = System.Convert.ToInt32(wireCommand.Substring(1));
// Handle the different commands in the first letter of each command string
switch (wireCommand[0])
{
case 'U':
// Up
for(int i = 0; i < distance; i++)
{
currentY += 1;
WireTouchPoint wtp = new WireTouchPoint();
wtp.x = currentX;
wtp.y = currentY;
touchPoints.Add(wtp);
}
break;
case 'D':
// Down
for(int i = 0; i < distance; i++)
{
currentY -= 1;
WireTouchPoint wtp = new WireTouchPoint();
wtp.x = currentX;
wtp.y = currentY;
touchPoints.Add(wtp);
}
break;
case 'L':
// Left
for(int i = 0; i < distance; i++)
{
currentX -= 1;
WireTouchPoint wtp = new WireTouchPoint();
wtp.x = currentX;
wtp.y = currentY;
touchPoints.Add(wtp);
}
break;
case 'R':
// Right
for(int i = 0; i < distance; i++)
{
currentX += 1;
WireTouchPoint wtp = new WireTouchPoint();
wtp.x = currentX;
wtp.y = currentY;
touchPoints.Add(wtp);
}
break;
default:
break;
}
}
return touchPoints;
}
internal class WireTouchPointComparer : IEqualityComparer<WireTouchPoint>
{
public bool Equals(WireTouchPoint wtp1, WireTouchPoint wtp2)
{
if(wtp1.x == wtp2.x && wtp1.y == wtp2.y)
{
return true;
}
return false;
}
// public int GetHashCode(WireTouchPoint obj)
// {
// return obj.x.GetHashCode();
// }
public int GetHashCode(WireTouchPoint obj)
{
unchecked
{
int hash = 17;
hash = hash * 23 + obj.x.GetHashCode();
hash = hash * 23 + obj.y.GetHashCode();
return hash;
}
}
}
static void Part1()
{
// Each line is one wire's path trace
var wire1 = File.ReadAllLines("input.txt")[0];
var wire2 = File.ReadAllLines("input.txt")[1];
List<string> wire1Commands = wire1.Split(',').ToList();
List<string> wire2Commands = wire2.Split(',').ToList();
// Find all points each wire touches
List<WireTouchPoint> wire1TouchPoints = FindAllWireTouchPoints(wire1Commands);
List<WireTouchPoint> wire2TouchPoints = FindAllWireTouchPoints(wire2Commands);
// Find all points where the two wires cross
var crossingPoints = wire1TouchPoints.Intersect(wire2TouchPoints, new WireTouchPointComparer()).Where(cp => cp.x != 0 && cp.y != 0);
// Declare a large default shortest distance, probably should be setting as null and null-checking later but multitasking while writing this so cba
int shortestManhattanDistance = 9999999;
// For each crossing point, work out the Manhattan distance to the central port
foreach(WireTouchPoint crossingPoint in crossingPoints)
{
// Convert co-ordinates to be positive numbers for calculating distance
int xVal = crossingPoint.x > 0 ? crossingPoint.x : crossingPoint.x * -1;
int yVal = crossingPoint.y > 0 ? crossingPoint.y : crossingPoint.y * -1;
int manhattanDistance = (xVal - 0) + (yVal - 0);
// Work out if it is shorter than the previously found one
if(manhattanDistance < shortestManhattanDistance)
{
shortestManhattanDistance = manhattanDistance;
}
}
Console.WriteLine("Part 1: The Manhattan distance from the central port to the closest intersection is " + shortestManhattanDistance);
}
static void Part2()
{
// Each line is one wire's path trace
var wire1 = File.ReadAllLines("input.txt")[0];
var wire2 = File.ReadAllLines("input.txt")[1];
List<string> wire1Commands = wire1.Split(',').ToList();
List<string> wire2Commands = wire2.Split(',').ToList();
// Find all points each wire touches
List<WireTouchPoint> wire1TouchPoints = FindAllWireTouchPoints(wire1Commands);
List<WireTouchPoint> wire2TouchPoints = FindAllWireTouchPoints(wire2Commands);
// Find all points where the two wires cross
var crossingPoints = wire1TouchPoints.Intersect(wire2TouchPoints, new WireTouchPointComparer()).Where(cp => cp.x != 0 && cp.y != 0);
// Declare a large default minimum steps, probably should be setting as null and null-checking later but multitasking while writing this so cba
int minimumSteps = 9999999;
foreach(WireTouchPoint crossingPoint in crossingPoints)
{
// Calculate the number of steps each wire takes to reach each the intersection
// If a wire visits a position on the grid multiple times, use the steps value from the first time it visits that position when calculating the total value of a specific intersection.
// The number of steps a wire takes is the total number of grid squares the wire has entered to get to that location, including the intersection being considered.
// Calculate the minimum number of steps each wire takes to reach the crossing point (using the index rather than index + 1 as the lists are zero-indexed ordered by the route taken but we want to ignore the start co-ordinates) - this will always return the first (i.e. closest) index
int steps1 = wire1TouchPoints.FindIndex(tp => tp.x == crossingPoint.x && tp.y == crossingPoint.y);
int steps2 = wire2TouchPoints.FindIndex(tp => tp.x == crossingPoint.x && tp.y == crossingPoint.y);
int totalSteps = steps1 + steps2;
// Work out if it is fewer steps than the previously found one
if(totalSteps < minimumSteps)
{
minimumSteps = totalSteps;
}
}
Console.WriteLine("Part 2: The fewest combined steps the wires must take to reach an intersection is " + minimumSteps);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
--- Day 3: Crossed Wires ---
The gravity assist was successful, and you're well on your way to the Venus refuelling station. During the rush back on Earth, the fuel management system wasn't completely installed, so that's next on the priority list.
Opening the front panel reveals a jumble of wires. Specifically, two wires are connected to a central port and extend outward on a grid. You trace the path each wire takes as it leaves the central port, one wire per line of text (your puzzle input).
The wires twist and turn, but the two wires occasionally cross paths. To fix the circuit, you need to find the intersection point closest to the central port. Because the wires are on a grid, use the Manhattan distance for this measurement. While the wires do technically cross right at the central port where they both start, this point does not count, nor does a wire count as crossing with itself.
For example, if the first wire's path is R8,U5,L5,D3, then starting from the central port (o), it goes right 8, up 5, left 5, and finally down 3:
...........
...........
...........
....+----+.
....|....|.
....|....|.
....|....|.
.........|.
.o-------+.
...........
Then, if the second wire's path is U7,R6,D4,L4, it goes up 7, right 6, down 4, and left 4:
...........
.+-----+...
.|.....|...
.|..+--X-+.
.|..|..|.|.
.|.-X--+.|.
.|..|....|.
.|.......|.
.o-------+.
...........
These wires cross at two locations (marked X), but the lower-left one is closer to the central port: its distance is 3 + 3 = 6.
Here are a few more examples:
R75,D30,R83,U83,L12,D49,R71,U7,L72
U62,R66,U55,R34,D71,R55,D58,R83 = distance 159
R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7 = distance 135
What is the Manhattan distance from the central port to the closest intersection?
+28
View File
@@ -0,0 +1,28 @@
--- Part Two ---
It turns out that this circuit is very timing-sensitive; you actually need to minimize the signal delay.
To do this, calculate the number of steps each wire takes to reach each intersection; choose the intersection where the sum of both wires' steps is lowest. If a wire visits a position on the grid multiple times, use the steps value from the first time it visits that position when calculating the total value of a specific intersection.
The number of steps a wire takes is the total number of grid squares the wire has entered to get to that location, including the intersection being considered. Again consider the example from above:
...........
.+-----+...
.|.....|...
.|..+--X-+.
.|..|..|.|.
.|.-X--+.|.
.|..|....|.
.|.......|.
.o-------+.
...........
In the above example, the intersection closest to the central port is reached after 8+5+5+2 = 20 steps by the first wire and 7+6+4+3 = 20 steps by the second wire for a total of 20+20 = 40 steps.
However, the top-right intersection is better: the first wire takes only 8+5+2 = 15 and the second wire takes only 7+6+2 = 15, a total of 15+15 = 30 steps.
Here are the best steps for the extra examples from above:
R75,D30,R83,U83,L12,D49,R71,U7,L72
U62,R66,U55,R34,D71,R55,D58,R83 = 610 steps
R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7 = 410 steps
What is the fewest combined steps the wires must take to reach an intersection?
+2
View File
@@ -0,0 +1,2 @@
R1008,U336,R184,D967,R451,D742,L235,U219,R57,D439,R869,U207,L574,U670,L808,D675,L203,D370,L279,U448,L890,U297,R279,D613,L411,D530,L372,D88,R986,U444,R319,D95,L385,D674,R887,U855,R794,U783,R633,U167,L587,D545,L726,D196,R681,U609,R677,U881,R153,D724,L63,U246,R343,U315,R580,U872,L516,U95,R463,D809,R9,U739,R540,U670,L434,D699,L158,U47,L383,D483,L341,U61,R933,D269,R816,D589,R488,D169,R972,D534,L995,D277,L887,D657,R628,D322,R753,U813,L284,D237,R676,D880,L50,D965,L401,D619,R858,U313,L156,U535,R664,U447,L251,U168,L352,U881,L734,U270,L177,D903,L114,U998,L102,D149,R848,D586,L98,D157,R942,U496,R857,U362,R398,U86,R469,U358,L721,D631,R176,D365,L112,U472,L557,D153,R97,D639,L457,U566,R570,U106,R504,D292,L94,U499,R358,U653,L704,D627,R544,D24,L407,U513,R28,U643,L510,U579,R825,D376,L867,U999,R134,D734,R654,D989,L920,U872,R64,U626,R751,D425,R620,U274,L471,D83,R979,U577,L43,D320,R673,D187,R300,U134,L451,D717,R857,U576,R570,U988,R745,U840,R799,U809,R573,U354,L208,D976,L417,U473,L555,U563,L955,U823,R712,D869,L145,D735,L780,D74,R421,U42,L158,U689,R718,D455,L670,U128,L744,U401,R149,U102,L122,U832,R872,D40,R45,D325,L553,U980,L565,D497,L435,U647,L209,D822,L593,D28,R936,U95,R349,U511,L243,U895,R421,U336,L986,U264,R376,D183,R480,D947,R416,D706,R118,D799,R424,D615,R384,U185,L338,U14,R576,D901,L734,D417,L62,D254,R784,D973,R987,D848,R32,D72,L535,D633,L668,D664,R308,D474,L418,D39,L473,U388,L518,D544,R118,D948,L844,D956,R605,U14,L948,D78,L689,U443,L996,U932,R81,D879,R556,D633,R131
L993,U227,L414,U228,L304,U53,R695,U765,R162,D264,L530,U870,R771,D395,R27,D200,L235,D834,L559,D128,R284,U912,L959,U358,R433,U404,L539,U799,R271,D734,L104,U261,R812,D15,L474,U887,R606,U366,L694,U156,R385,D667,L329,D434,R745,U776,L319,U756,R208,D457,R705,U999,R284,U98,L657,U214,R639,D937,R675,U444,L891,D587,L914,D4,R294,D896,R534,D584,L887,U878,L807,U202,R505,U234,L284,D5,R667,U261,L127,D482,R777,D223,L707,D468,L606,U345,L509,D967,R437,U995,R28,D376,L2,D959,L814,U702,L38,D154,L79,D439,L259,U143,L376,U700,R894,U165,L300,D58,R631,D47,R684,U935,R262,D857,R797,D599,L705,U792,R439,D444,R398,D887,L81,D40,R671,U332,L820,U252,R691,U412,L794,D661,R810,U157,R858,U566,R892,D543,R10,D725,L653,D812,R733,D804,R816,U862,R994,U221,L33,U271,R766,D591,R575,D970,R152,D693,L916,U404,L658,D847,L605,D433,L583,U587,L129,D103,R407,U780,L901,D676,L846,D687,L9,D47,R295,D597,L808,U134,L186,D676,L62,U305,L73,D369,L468,U30,L472,U280,L413,U961,L98,D966,R308,D178,L21,D789,L871,D671,R665,U927,L906,U633,L135,D894,R110,D205,R324,D665,R143,D450,L978,U385,R442,D853,L518,U542,R211,U857,R119,D872,L246,U380,L874,U463,R153,U982,R832,D784,L652,U545,R71,U386,R427,D827,R986,U870,R959,U232,R509,U675,R196,U389,R944,U149,R152,U571,R527,U495,L441,U511,L899,D996,L707,D455,L358,D423,L14,D427,R144,D703,L243,U157,R876,D538,R26,D577,L385,U622,L149,D852,L225,U475,L811,D520,L226,U523,L338,D79,R565,U766,L609,U496,L189,D446,R63,U396,L629,U312,L841,D639,R466,U808,L60,D589,L146,U114,R165,U96,L809,D704,L61
+15
View File
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_01</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Creek.HelpfulExtensions" Version="1.3.0" />
</ItemGroup>
</Project>
+53
View File
@@ -0,0 +1,53 @@
using Creek.HelpfulExtensions;
// Part 1
int numberOfBiggerMeasurements = 0;
string[] lines = File.ReadAllLines("input.txt");
foreach (var (line, index) in lines.WithIndex())
{
if (index > 0)
{
int previousReading = Int32.Parse(lines[index-1]);
int currentReading = Int32.Parse(line);
if (currentReading > previousReading)
{
numberOfBiggerMeasurements += 1;
}
}
}
Console.WriteLine($"Part 1: {numberOfBiggerMeasurements}");
// Part 2
int numberOfBiggerSlidingTotals = 0;
List<int> slidingTotals = new List<int>();
for (int i = 0; i < lines.Count(); i++)
{
if (lines.Count() > i+2)
{
slidingTotals.Add(Int32.Parse(lines[i]) + Int32.Parse(lines[i+1]) + Int32.Parse(lines[i+2]));
}
}
foreach (var (total, index) in slidingTotals.WithIndex())
{
if (index > 0)
{
int previousTotal = slidingTotals[index-1];
int currentTotal = total;
if (currentTotal > previousTotal)
{
numberOfBiggerSlidingTotals += 1;
}
}
}
Console.WriteLine($"Part 2: {numberOfBiggerSlidingTotals}");
+42
View File
@@ -0,0 +1,42 @@
--- Day 1: Sonar Sweep ---
You're minding your own business on a ship at sea when the overboard alarm goes off! You rush to see if you can help. Apparently, one of the Elves tripped and accidentally sent the sleigh keys flying into the ocean!
Before you know it, you're inside a submarine the Elves keep ready for situations like this. It's covered in Christmas lights (because of course it is), and it even has an experimental antenna that should be able to track the keys if you can boost its signal strength high enough; there's a little meter that indicates the antenna's signal strength by displaying 0-50 stars.
Your instincts tell you that in order to save Christmas, you'll need to get all fifty stars by December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
As the submarine drops below the surface of the ocean, it automatically performs a sonar sweep of the nearby sea floor. On a small screen, the sonar sweep report (your puzzle input) appears: each line is a measurement of the sea floor depth as the sweep looks further and further away from the submarine.
For example, suppose you had the following report:
199
200
208
210
200
207
240
269
260
263
This report indicates that, scanning outward from the submarine, the sonar sweep found depths of 199, 200, 208, 210, and so on.
The first order of business is to figure out how quickly the depth increases, just so you know what you're dealing with - you never know if the keys will get carried into deeper water by an ocean current or a fish or something.
To do this, count the number of times a depth measurement increases from the previous measurement. (There is no measurement before the first measurement.) In the example above, the changes are as follows:
199 (N/A - no previous measurement)
200 (increased)
208 (increased)
210 (increased)
200 (decreased)
207 (increased)
240 (increased)
269 (increased)
260 (decreased)
263 (increased)
In this example, there are 7 measurements that are larger than the previous measurement.
How many measurements are larger than the previous measurement?
+32
View File
@@ -0,0 +1,32 @@
--- Part Two ---
Considering every single measurement isn't as useful as you expected: there's just too much noise in the data.
Instead, consider sums of a three-measurement sliding window. Again considering the above example:
199 A
200 A B
208 A B C
210 B C D
200 E C D
207 E F D
240 E F G
269 F G H
260 G H
263 H
Start by comparing the first and second three-measurement windows. The measurements in the first window are marked A (199, 200, 208); their sum is 199 + 200 + 208 = 607. The second window is marked B (200, 208, 210); its sum is 618. The sum of measurements in the second window is larger than the sum of the first, so this first comparison increased.
Your goal now is to count the number of times the sum of measurements in this sliding window increases from the previous sum. So, compare A with B, then compare B with C, then C with D, and so on. Stop when there aren't enough measurements left to create a new three-measurement sum.
In the above example, the sum of each three-measurement window is as follows:
A: 607 (N/A - no previous sum)
B: 618 (increased)
C: 618 (no change)
D: 617 (decreased)
E: 647 (increased)
F: 716 (increased)
G: 769 (increased)
H: 792 (increased)
In this example, there are 5 sums that are larger than the previous sum.
Consider sums of a three-measurement sliding window. How many sums are larger than the previous sum?
File diff suppressed because it is too large Load Diff
+11
View File
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_02</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+56
View File
@@ -0,0 +1,56 @@
// Part 1
string[] lines = File.ReadAllLines("input.txt");
int horizontalPosition = 0;
int verticalPosition = 0;
foreach (string line in lines)
{
string[] parts = line.Split(' ');
if (parts[0] == "forward")
{
horizontalPosition += Int32.Parse(parts[1]);
}
else if (parts[0] == "down")
{
verticalPosition += Int32.Parse(parts[1]);
}
else if (parts[0] == "up")
{
verticalPosition -= Int32.Parse(parts[1]);
}
}
Console.WriteLine($"Final position: {horizontalPosition},{verticalPosition}");
Console.WriteLine($"Multiplied together, that is: {horizontalPosition * verticalPosition}");
// Part 2
int newHorizontalPosition = 0;
int newVerticalPosition = 0;
int aim = 0;
foreach (string line in lines)
{
string[] parts = line.Split(' ');
if (parts[0] == "forward")
{
newHorizontalPosition += Int32.Parse(parts[1]);
newVerticalPosition += (aim * Int32.Parse(parts[1]));
}
else if (parts[0] == "down")
{
aim += Int32.Parse(parts[1]);
}
else if (parts[0] == "up")
{
aim -= Int32.Parse(parts[1]);
}
}
Console.WriteLine($"Final position: {newHorizontalPosition},{newVerticalPosition}");
Console.WriteLine($"Multiplied together, that is: {newHorizontalPosition * newVerticalPosition}");
+29
View File
@@ -0,0 +1,29 @@
--- Day 2: Dive! ---
Now, you need to figure out how to pilot this thing.
It seems like the submarine can take a series of commands like forward 1, down 2, or up 3:
forward X increases the horizontal position by X units.
down X increases the depth by X units.
up X decreases the depth by X units.
Note that since you're on a submarine, down and up affect your depth, and so they have the opposite result of what you might expect.
The submarine seems to already have a planned course (your puzzle input). You should probably figure out where it's going. For example:
forward 5
down 5
forward 8
up 3
down 8
forward 2
Your horizontal position and depth both start at 0. The steps above would then modify them as follows:
forward 5 adds 5 to your horizontal position, a total of 5.
down 5 adds 5 to your depth, resulting in a value of 5.
forward 8 adds 8 to your horizontal position, a total of 13.
up 3 decreases your depth by 3, resulting in a value of 2.
down 8 adds 8 to your depth, resulting in a value of 10.
forward 2 adds 2 to your horizontal position, a total of 15.
After following these instructions, you would have a horizontal position of 15 and a depth of 10. (Multiplying these together produces 150.)
Calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth?
+23
View File
@@ -0,0 +1,23 @@
--- Part Two ---
Based on your calculations, the planned course doesn't seem to make any sense. You find the submarine manual and discover that the process is actually slightly more complicated.
In addition to horizontal position and depth, you'll also need to track a third value, aim, which also starts at 0. The commands also mean something entirely different than you first thought:
down X increases your aim by X units.
up X decreases your aim by X units.
forward X does two things:
It increases your horizontal position by X units.
It increases your depth by your aim multiplied by X.
Again note that since you're on a submarine, down and up do the opposite of what you might expect: "down" means aiming in the positive direction.
Now, the above example does something different:
forward 5 adds 5 to your horizontal position, a total of 5. Because your aim is 0, your depth does not change.
down 5 adds 5 to your aim, resulting in a value of 5.
forward 8 adds 8 to your horizontal position, a total of 13. Because your aim is 5, your depth increases by 8*5=40.
up 3 decreases your aim by 3, resulting in a value of 2.
down 8 adds 8 to your aim, resulting in a value of 10.
forward 2 adds 2 to your horizontal position, a total of 15. Because your aim is 10, your depth increases by 2*10=20 to a total of 60.
After following these new instructions, you would have a horizontal position of 15 and a depth of 60. (Multiplying these produces 900.)
Using this new interpretation of the commands, calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth?
File diff suppressed because it is too large Load Diff
+11
View File
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_03</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+17
View File
@@ -0,0 +1,17 @@
public class BinaryData
{
public int Digit0 { get; set; }
public int Digit1 { get; set; }
public int Digit2 { get; set; }
public int Digit3 { get; set; }
public int Digit4 { get; set; }
public int Digit5 { get; set; }
public int Digit6 { get; set; }
public int Digit7 { get; set; }
public int Digit8 { get; set; }
public int Digit9 { get; set; }
public int Digit10 { get; set; }
public int Digit11 { get; set; }
}
+179
View File
@@ -0,0 +1,179 @@
namespace Day03
{
class Program
{
static void Main(string[] args)
{
//Part1();
Part2();
}
static void Part1()
{
// Part 1
string[] lines = File.ReadAllLines("input.txt");
List<BinaryData> binaryDataList = new List<BinaryData>();
foreach (string line in lines)
{
BinaryData binaryData = new BinaryData()
{
Digit0 = Int32.Parse(line[0].ToString()),
Digit1 = Int32.Parse(line[1].ToString()),
Digit2 = Int32.Parse(line[2].ToString()),
Digit3 = Int32.Parse(line[3].ToString()),
Digit4 = Int32.Parse(line[4].ToString()),
Digit5 = Int32.Parse(line[5].ToString()),
Digit6 = Int32.Parse(line[6].ToString()),
Digit7 = Int32.Parse(line[7].ToString()),
Digit8 = Int32.Parse(line[8].ToString()),
Digit9 = Int32.Parse(line[9].ToString()),
Digit10 = Int32.Parse(line[10].ToString()),
Digit11 = Int32.Parse(line[11].ToString()),
};
binaryDataList.Add(binaryData);
}
// for first digit find most common, 2nd digit most common, etc to get the gamma rate
int mostOccurred0 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit0).ToList());
int mostOccurred1 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit1).ToList());
int mostOccurred2 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit2).ToList());
int mostOccurred3 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit3).ToList());
int mostOccurred4 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit4).ToList());
int mostOccurred5 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit5).ToList());
int mostOccurred6 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit6).ToList());
int mostOccurred7 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit7).ToList());
int mostOccurred8 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit8).ToList());
int mostOccurred9 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit9).ToList());
int mostOccurred10 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit10).ToList());
int mostOccurred11 = GetMostOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit11).ToList());
string mostOccurred = "" + mostOccurred0 + mostOccurred1 + mostOccurred2 + mostOccurred3 + mostOccurred4 + mostOccurred5 + mostOccurred6 + mostOccurred7 + mostOccurred8 + mostOccurred9 + mostOccurred10 + mostOccurred11;
// for first digit find least common, 2nd digit least common, etc to get the epsilon rate
int leastOccurred0 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit0).ToList());
int leastOccurred1 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit1).ToList());
int leastOccurred2 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit2).ToList());
int leastOccurred3 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit3).ToList());
int leastOccurred4 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit4).ToList());
int leastOccurred5 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit5).ToList());
int leastOccurred6 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit6).ToList());
int leastOccurred7 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit7).ToList());
int leastOccurred8 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit8).ToList());
int leastOccurred9 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit9).ToList());
int leastOccurred10 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit10).ToList());
int leastOccurred11 = GetLeastOccurredCharacterAtPosition(binaryDataList.Select(x => x.Digit11).ToList());
string leastOccurred = "" + leastOccurred0 + leastOccurred1 + leastOccurred2 + leastOccurred3 + leastOccurred4 + leastOccurred5 + leastOccurred6 + leastOccurred7 + leastOccurred8 + leastOccurred9 + leastOccurred10 + leastOccurred11;
Console.WriteLine($"MO: {mostOccurred} LO: {leastOccurred}");
string gammaRate = string.Join("", mostOccurred);
int gammaRateDenary = Convert.ToInt32(gammaRate, 2);
string epsilonRate = string.Join("", leastOccurred);
int epsilonRateDenary = Convert.ToInt32(epsilonRate, 2);
// multiply gamma rate by epislon rate to get power consumption
int powerConsumption = gammaRateDenary * epsilonRateDenary;
Console.WriteLine($"Gamma rate: {gammaRate} Epsilon rate: {epsilonRate} Power consumption: {powerConsumption}");
}
static void Part2()
{
string[] lines = File.ReadAllLines("input.txt");
List<string> linesForOxygen = lines.ToList();
List<string> linesForCo2 = lines.ToList();
for (int i = 0; i < lines[0].Length; i++)
{
if (linesForOxygen.Count > 1)
{
int mostCommon = GetMostOccurredCharacterAtPositionWithEqualHandling(linesForOxygen.Select(x => Int32.Parse(x[i].ToString())).ToList());
linesForOxygen = linesForOxygen.Where(x => x[i] == mostCommon.ToString()[0]).ToList();
}
if (linesForCo2.Count > 1)
{
int leastCommon = GetLeastOccurredCharacterAtPositionWithEqualHandling(linesForCo2.Select(x => Int32.Parse(x[i].ToString())).ToList());
linesForCo2 = linesForCo2.Where(x => x[i] == leastCommon.ToString()[0]).ToList();
}
}
Console.WriteLine($"Oxygen: {linesForOxygen[0]} CO2: {linesForCo2[0]}");
int oxygenDenary = Convert.ToInt32(linesForOxygen[0], 2);
int co2Denary = Convert.ToInt32(linesForCo2[0], 2);
// life support rating = oxygen generator rating * co2 scrubber rating
int lifeSupportRating = oxygenDenary * co2Denary;
Console.WriteLine($"Oxygen: {oxygenDenary} CO2: {co2Denary} Life support rating: {lifeSupportRating}");
}
public static int GetMostOccurredCharacterAtPositionWithEqualHandling(List<int> list)
{
var count0 = list.Where(x => x == 0).Count();
var count1 = list.Where(x => x == 1).Count();
if (count0 == count1)
{
return 1;
}
else
{
if (count0 > count1)
{
return 0;
}
else
{
return 1;
}
}
}
public static int GetLeastOccurredCharacterAtPositionWithEqualHandling(List<int> list)
{
var count0 = list.Where(x => x == 0).Count();
var count1 = list.Where(x => x == 1).Count();
if (count0 == count1)
{
return 0;
}
else
{
if (count0 > count1)
{
return 1;
}
else
{
return 0;
}
}
}
public static int GetMostOccurredCharacterAtPosition(List<int> list)
{
return list
.GroupBy(x => x)
.OrderByDescending(group => group.Count())
.Select(x => x.Key)
.First();
}
public static int GetLeastOccurredCharacterAtPosition(List<int> list)
{
return list
.GroupBy(x => x)
.OrderBy(group => group.Count())
.Select(x => x.Key)
.First();
}
}
}
+32
View File
@@ -0,0 +1,32 @@
--- Day 3: Binary Diagnostic ---
The submarine has been making some odd creaking noises, so you ask it to produce a diagnostic report just in case.
The diagnostic report (your puzzle input) consists of a list of binary numbers which, when decoded properly, can tell you many useful things about the conditions of the submarine. The first parameter to check is the power consumption.
You need to use the binary numbers in the diagnostic report to generate two new binary numbers (called the gamma rate and the epsilon rate). The power consumption can then be found by multiplying the gamma rate by the epsilon rate.
Each bit in the gamma rate can be determined by finding the most common bit in the corresponding position of all numbers in the diagnostic report. For example, given the following diagnostic report:
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
Considering only the first bit of each number, there are five 0 bits and seven 1 bits. Since the most common bit is 1, the first bit of the gamma rate is 1.
The most common second bit of the numbers in the diagnostic report is 0, so the second bit of the gamma rate is 0.
The most common value of the third, fourth, and fifth bits are 1, 1, and 0, respectively, and so the final three bits of the gamma rate are 110.
So, the gamma rate is the binary number 10110, or 22 in decimal.
The epsilon rate is calculated in a similar way; rather than use the most common bit, the least common bit from each position is used. So, the epsilon rate is 01001, or 9 in decimal. Multiplying the gamma rate (22) by the epsilon rate (9) produces the power consumption, 198.
Use the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate, then multiply them together. What is the power consumption of the submarine? (Be sure to represent your answer in decimal, not binary.)
+29
View File
@@ -0,0 +1,29 @@
--- Part Two ---
Next, you should verify the life support rating, which can be determined by multiplying the oxygen generator rating by the CO2 scrubber rating.
Both the oxygen generator rating and the CO2 scrubber rating are values that can be found in your diagnostic report - finding them is the tricky part. Both values are located using a similar process that involves filtering out values until only one remains. Before searching for either rating value, start with the full list of binary numbers from your diagnostic report and consider just the first bit of those numbers. Then:
Keep only numbers selected by the bit criteria for the type of rating value for which you are searching. Discard numbers which do not match the bit criteria.
If you only have one number left, stop; this is the rating value for which you are searching.
Otherwise, repeat the process, considering the next bit to the right.
The bit criteria depends on which type of rating value you want to find:
To find oxygen generator rating, determine the most common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 1 in the position being considered.
To find CO2 scrubber rating, determine the least common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 0 in the position being considered.
For example, to determine the oxygen generator rating value using the same example diagnostic report from above:
Start with all 12 numbers and consider only the first bit of each number. There are more 1 bits (7) than 0 bits (5), so keep only the 7 numbers with a 1 in the first position: 11110, 10110, 10111, 10101, 11100, 10000, and 11001.
Then, consider the second bit of the 7 remaining numbers: there are more 0 bits (4) than 1 bits (3), so keep only the 4 numbers with a 0 in the second position: 10110, 10111, 10101, and 10000.
In the third position, three of the four numbers have a 1, so keep those three: 10110, 10111, and 10101.
In the fourth position, two of the three numbers have a 1, so keep those two: 10110 and 10111.
In the fifth position, there are an equal number of 0 bits and 1 bits (one each). So, to find the oxygen generator rating, keep the number with a 1 in that position: 10111.
As there is only one number left, stop; the oxygen generator rating is 10111, or 23 in decimal.
Then, to determine the CO2 scrubber rating value from the same example above:
Start again with all 12 numbers and consider only the first bit of each number. There are fewer 0 bits (5) than 1 bits (7), so keep only the 5 numbers with a 0 in the first position: 00100, 01111, 00111, 00010, and 01010.
Then, consider the second bit of the 5 remaining numbers: there are fewer 1 bits (2) than 0 bits (3), so keep only the 2 numbers with a 1 in the second position: 01111 and 01010.
In the third position, there are an equal number of 0 bits and 1 bits (one each). So, to find the CO2 scrubber rating, keep the number with a 0 in that position: 01010.
As there is only one number left, stop; the CO2 scrubber rating is 01010, or 10 in decimal.
Finally, to find the life support rating, multiply the oxygen generator rating (23) by the CO2 scrubber rating (10) to get 230.
Use the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating, then multiply them together. What is the life support rating of the submarine? (Be sure to represent your answer in decimal, not binary.)
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_04</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Creek.HelpfulExtensions" Version="1.3.0" />
</ItemGroup>
</Project>
+199
View File
@@ -0,0 +1,199 @@
using Creek.HelpfulExtensions;
namespace Day04
{
class Program
{
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("input.txt");
// first line is the order in which to draw numbers, comma separated
List<int> numbersToDraw = lines[0].Split(',').Select(int.Parse).ToList();
// second line is blank line
// 5 groups of 5 lines, space separated numbers in rows
List<(int value, bool isMatched)[,]> grids = new List<(int value, bool isMatched)[,]>();
// Skip the first line and second blank line, then go ahead 5 lines + the blank line each time
// repeat for additional groups and blank lines
for (int i = 2; i < lines.Length; i+=6)
{
(int value, bool isMatched)[,] grid = new(int value, bool isMatched) [5,5];
for (int j = 0; j < 5; j++)
{
// Get all in each row, space separated + remove starting spaces and double spaces
string line = lines[i + j].StartsWith(" ") ? lines[i + j].Substring(1).Replace(" ", " ") : lines[i + j].Replace(" ", " ");
List<int> row = line.Split(' ').Select(int.Parse).ToList();
for (int k = 0; k < row.Count(); k++)
{
grid[j,k] = (row[k], false);
}
}
grids.Add(grid);
}
//Part1(numbersToDraw, grids);
Part2(numbersToDraw, grids);
}
static void Part1(List<int> numbersToDraw, List<(int value, bool isMatched)[,]> grids)
{
int winningNumber = 0;
(int value, bool isMatched)[,] winningGrid = new(int value, bool isMatched) [5,5];
// Start going through the numbers now the grids are set up
foreach (int number in numbersToDraw)
{
bool breakLoops = false;
// need to be able to record when each number in a grid has been matched
foreach (var grid in grids)
{
RecordAMatchInAGrid(grid, number);
}
// need to be able to record when a row OR column has had all numbers matched
foreach (var grid in grids)
{
// when one grid has a complete row or column, that grid wins
if (ARowOrColumnHasAllNumbersMatched(grid))
{
Console.WriteLine($"Winning number: {number}");
// Exit the two foreach loops
// and record the final number called for the win
winningNumber = number;
winningGrid = grid;
breakLoops = true;
break;
}
}
if (breakLoops)
{
break;
}
}
// find the sum of all unmatched numbers of the board
int sumOfAllUnmatchedFromWinningBoard = CalculateSumOfAllUnmatchedFromWinningBoard(winningGrid);
// multiply that by the final number that gave a grid the win
Console.WriteLine(sumOfAllUnmatchedFromWinningBoard * winningNumber);
}
static void Part2(List<int> numbersToDraw, List<(int value, bool isMatched)[,]> grids)
{
// Figure out which board will win last
int lastWinningNumber = 0;
(int value, bool isMatched)[,] lastWinningGrid = new(int value, bool isMatched) [5,5];
List<int> gridsThatHaveAlreadyWon = new List<int>();
// Start going through the numbers now the grids are set up
foreach (int number in numbersToDraw)
{
bool breakLoops = false;
// need to be able to record when each number in a grid has been matched
foreach (var grid in grids)
{
RecordAMatchInAGrid(grid, number);
}
// need to be able to record when a row OR column has had all numbers matched
foreach (var (grid, index) in grids.WithIndex())
{
// when one grid has a complete row or column, that grid wins
if (ARowOrColumnHasAllNumbersMatched(grid))
{
if (!gridsThatHaveAlreadyWon.Contains(index))
{
gridsThatHaveAlreadyWon.Add(index);
if (gridsThatHaveAlreadyWon.Count == grids.Count)
{
// Exit the two foreach loops
// and record the final number called for the win
lastWinningNumber = number;
lastWinningGrid = grid;
breakLoops = true;
break;
}
}
}
}
if (breakLoops)
{
break;
}
}
// find the sum of all unmatched numbers of the board
int sumOfAllUnmatchedFromWinningBoard = CalculateSumOfAllUnmatchedFromWinningBoard(lastWinningGrid);
// multiply that by the final number that gave a grid the win
Console.WriteLine(sumOfAllUnmatchedFromWinningBoard * lastWinningNumber);
}
static int CalculateSumOfAllUnmatchedFromWinningBoard((int value, bool isMatched)[,] grid)
{
int runningTotal = 0;
for (int i = 0; i < 5; i++)
{
for (int k = 0; k < 5; k++)
{
if (!grid[i,k].isMatched)
{
runningTotal += grid[i,k].value;
}
}
}
return runningTotal;
}
static void RecordAMatchInAGrid((int value, bool isMatched)[,] grid, int number)
{
// Go through all numbers in the grid and record any matches
for (int i = 0; i < 5; i++)
{
for (int k = 0; k < 5; k++)
{
if (grid[i,k].value == number)
{
grid[i,k].isMatched = true;
}
}
}
}
static bool ARowOrColumnHasAllNumbersMatched((int value, bool isMatched)[,] grid)
{
for (int i = 0; i < 5; i++)
{
// Check the row, then the column
if (grid[i,0].isMatched && grid[i,1].isMatched && grid[i,2].isMatched && grid[i,3].isMatched && grid[i,4].isMatched)
{
return true;
}
else if (grid[0,i].isMatched && grid[1,i].isMatched && grid[2,i].isMatched && grid[3,i].isMatched && grid[4,i].isMatched)
{
return true;
}
}
return false;
}
}
}
+54
View File
@@ -0,0 +1,54 @@
--- Day 4: Giant Squid ---
You're already almost 1.5km (almost a mile) below the surface of the ocean, already so deep that you can't see any sunlight. What you can see, however, is a giant squid that has attached itself to the outside of your submarine.
Maybe it wants to play bingo?
Bingo is played on a set of boards each consisting of a 5x5 grid of numbers. Numbers are chosen at random, and the chosen number is marked on all boards on which it appears. (Numbers may not appear on all boards.) If all numbers in any row or any column of a board are marked, that board wins. (Diagonals don't count.)
The submarine has a bingo subsystem to help passengers (currently, you and the giant squid) pass the time. It automatically generates a random order in which to draw numbers and a random set of boards (your puzzle input). For example:
7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
22 13 17 11 0
8 2 23 4 24
21 9 14 16 7
6 10 3 18 5
1 12 20 15 19
3 15 0 2 22
9 18 13 17 5
19 8 7 25 23
20 11 10 24 4
14 21 16 12 6
14 21 17 24 4
10 16 15 9 19
18 8 23 26 20
22 11 13 6 5
2 0 12 3 7
After the first five numbers are drawn (7, 4, 9, 5, and 11), there are no winners, but the boards are marked as follows (shown here adjacent to each other to save space):
22 13 17 11 0 3 15 0 2 22 14 21 17 24 4
8 2 23 4 24 9 18 13 17 5 10 16 15 9 19
21 9 14 16 7 19 8 7 25 23 18 8 23 26 20
6 10 3 18 5 20 11 10 24 4 22 11 13 6 5
1 12 20 15 19 14 21 16 12 6 2 0 12 3 7
After the next six numbers are drawn (17, 23, 2, 0, 14, and 21), there are still no winners:
22 13 17 11 0 3 15 0 2 22 14 21 17 24 4
8 2 23 4 24 9 18 13 17 5 10 16 15 9 19
21 9 14 16 7 19 8 7 25 23 18 8 23 26 20
6 10 3 18 5 20 11 10 24 4 22 11 13 6 5
1 12 20 15 19 14 21 16 12 6 2 0 12 3 7
Finally, 24 is drawn:
22 13 17 11 0 3 15 0 2 22 14 21 17 24 4
8 2 23 4 24 9 18 13 17 5 10 16 15 9 19
21 9 14 16 7 19 8 7 25 23 18 8 23 26 20
6 10 3 18 5 20 11 10 24 4 22 11 13 6 5
1 12 20 15 19 14 21 16 12 6 2 0 12 3 7
At this point, the third board wins because it has at least one complete row or column of marked numbers (in this case, the entire top row is marked: 14 21 17 24 4).
The score of the winning board can now be calculated. Start by finding the sum of all unmarked numbers on that board; in this case, the sum is 188. Then, multiply that sum by the number that was just called when the board won, 24, to get the final score, 188 * 24 = 4512.
To guarantee victory against the giant squid, figure out which board will win first. What will your final score be if you choose that board?
+8
View File
@@ -0,0 +1,8 @@
--- Part Two ---
On the other hand, it might be wise to try a different strategy: let the giant squid win.
You aren't sure how many bingo boards a giant squid could play at once, so rather than waste time counting its arms, the safe thing to do is to figure out which board will win last and choose that one. That way, no matter which boards it picks, it will win for sure.
In the above example, the second board is the last to win, which happens after 13 is eventually called and its middle column is completely marked. If you were to keep playing until this point, the second board would have a sum of unmarked numbers equal to 148 for a final score of 148 * 13 = 1924.
Figure out which board will win last. Once it wins, what would its final score be?
+601
View File
@@ -0,0 +1,601 @@
57,9,8,30,40,62,24,70,54,73,12,3,71,95,58,88,23,81,53,80,22,45,98,37,18,72,14,20,66,0,19,31,82,34,55,29,27,96,48,28,87,83,36,26,63,21,5,46,33,86,32,56,6,38,52,16,41,74,99,77,13,35,65,4,78,91,90,43,1,2,64,60,94,85,61,84,42,76,68,10,49,89,11,17,79,69,39,50,25,51,47,93,44,92,59,75,7,97,67,15
45 57 55 43 31
32 52 79 65 80
21 98 16 64 6
19 78 48 59 51
37 2 69 56 99
87 20 29 96 75
83 34 84 72 98
70 89 90 73 38
86 2 47 62 11
24 60 64 65 31
11 20 22 49 30
59 87 10 31 68
64 24 82 26 6
92 38 48 4 54
93 81 28 80 99
29 4 62 28 85
71 2 77 3 98
74 57 25 33 92
64 95 61 73 99
76 36 81 87 1
79 59 96 61 95
81 77 56 68 36
69 39 0 55 14
16 3 4 34 63
84 80 99 37 9
86 33 77 30 59
19 54 48 28 89
26 38 82 68 69
87 76 85 22 50
74 72 58 81 49
3 8 39 15 69
14 72 90 81 58
54 13 59 53 97
84 20 43 57 89
22 92 28 51 45
86 91 63 52 27
50 75 94 89 31
79 44 92 29 97
34 60 42 37 80
73 28 7 96 10
85 60 89 34 6
41 81 39 37 57
23 70 79 46 15
74 54 59 88 9
58 97 5 51 1
54 82 22 26 18
46 12 21 36 79
83 71 14 29 45
42 24 73 58 68
63 32 9 86 98
59 83 13 34 44
80 55 81 67 3
74 58 32 43 6
61 73 21 23 66
2 9 52 29 86
29 24 37 21 2
81 0 22 59 41
44 40 72 31 71
9 99 50 65 97
55 69 88 58 96
3 69 94 88 12
40 81 77 38 6
8 35 91 18 85
2 14 73 62 44
46 9 37 1 20
86 58 85 43 65
92 44 69 2 14
83 3 93 16 49
42 59 29 75 32
45 4 48 21 68
87 65 80 18 46
66 49 78 60 31
20 74 29 96 86
12 35 47 93 16
38 91 54 73 28
26 68 98 32 67
46 61 64 35 38
92 77 70 76 88
86 0 58 13 51
96 1 62 53 8
2 40 32 62 33
84 96 99 76 95
9 1 12 7 90
67 11 14 97 24
42 54 57 45 83
39 99 37 0 95
18 2 73 31 17
32 66 21 62 9
4 78 22 53 45
41 33 71 6 50
14 12 2 42 7
52 71 90 28 75
0 40 79 39 93
84 16 82 31 94
74 36 59 72 15
7 92 42 41 22
28 31 91 68 12
45 84 83 34 56
70 43 37 54 60
61 40 98 77 17
12 81 17 27 66
49 95 82 97 85
16 58 13 11 56
88 31 36 96 23
0 51 55 22 62
8 36 9 63 71
79 97 60 16 91
93 68 54 28 32
42 57 20 43 47
99 26 67 76 33
1 55 58 48 92
66 71 89 46 96
15 37 94 14 47
22 61 91 80 51
33 44 63 10 88
5 63 34 56 0
97 22 48 11 85
29 10 61 30 26
55 1 32 27 77
80 81 70 62 33
77 72 75 41 66
7 54 58 21 70
95 30 14 71 99
20 79 22 91 94
45 10 86 18 63
55 22 21 79 86
35 95 99 60 1
25 68 82 93 14
74 28 41 73 78
15 61 70 56 3
80 35 25 22 12
37 24 97 59 44
54 84 1 33 11
9 28 74 30 95
67 81 19 71 40
10 78 74 83 8
90 86 41 82 31
17 51 54 12 29
32 62 87 2 0
98 33 27 22 64
86 80 85 28 26
44 25 5 78 87
50 70 57 75 32
11 20 52 97 88
68 43 0 7 38
88 16 10 34 75
76 84 41 1 61
49 94 14 26 36
85 77 22 98 70
12 38 3 74 92
34 91 21 73 99
28 82 69 18 85
97 25 65 61 55
96 33 63 2 77
12 41 72 39 23
0 45 95 55 34
31 77 54 66 79
90 11 49 68 93
61 15 56 4 53
57 69 97 7 6
94 11 44 83 87
27 47 93 50 38
29 55 10 49 32
76 73 91 37 34
51 62 4 85 46
66 64 5 33 99
95 34 65 69 27
49 17 46 53 76
75 9 92 94 7
59 60 2 40 70
28 80 27 88 79
26 49 81 64 69
90 51 42 83 70
46 10 53 5 96
29 99 84 22 8
86 49 31 53 28
85 94 4 98 30
51 7 48 88 1
76 92 64 29 73
81 6 21 36 74
14 19 15 97 81
92 37 98 77 33
20 24 4 51 79
99 66 43 75 73
46 87 58 93 5
69 76 46 21 57
49 90 40 34 99
70 89 4 0 23
5 86 44 62 53
36 13 61 51 15
88 37 14 50 26
76 83 24 46 5
43 42 72 17 59
6 11 36 25 19
70 53 52 98 30
87 93 25 46 74
62 16 9 30 85
60 21 29 17 5
35 49 84 53 42
13 90 99 70 48
19 91 10 89 52
71 1 42 75 83
81 32 96 53 5
26 60 3 95 51
44 12 33 76 64
77 17 29 55 43
62 52 92 53 21
74 71 46 38 7
23 79 65 61 89
50 90 83 26 19
58 85 18 17 29
76 78 91 87 31
49 82 95 89 6
53 79 9 97 25
48 68 98 13 21
40 90 77 45 48
18 54 15 56 57
82 11 36 92 35
50 68 86 0 97
24 78 49 75 62
63 91 7 16 8
90 60 93 40 45
49 28 41 35 21
79 54 5 0 13
68 20 37 55 59
38 26 33 78 76
42 63 73 98 24
77 27 67 8 30
90 13 20 59 5
32 22 1 46 79
15 39 72 27 73
14 29 34 30 8
91 43 66 75 21
7 16 78 48 41
93 83 77 94 57
22 41 70 14 73
64 4 13 60 98
59 71 12 53 93
68 11 54 95 37
58 35 43 48 87
81 7 49 42 24
86 76 36 34 16
55 73 27 28 88
66 83 58 80 48
62 9 18 96 77
64 15 37 61 17
80 69 67 98 89
22 12 32 74 47
97 23 49 30 91
38 68 53 40 82
17 1 56 75 46
20 2 98 71 96
34 35 63 73 59
7 89 95 51 16
69 81 37 91 61
3 17 45 36 59
7 24 70 86 72
77 15 34 69 37
84 60 76 33 5
26 21 48 61 12
19 56 90 95 3
68 50 37 65 27
39 35 72 61 22
49 80 24 23 58
7 12 89 94 9
45 32 90 66 73
22 7 41 21 20
49 63 93 59 15
2 82 96 30 27
40 85 6 97 42
49 12 67 7 0
24 79 48 6 85
38 29 13 11 17
1 60 70 34 87
46 75 64 76 14
27 96 15 23 54
56 39 67 34 76
43 62 14 7 57
86 24 35 94 55
38 51 84 29 16
60 33 9 97 20
92 26 30 42 7
36 56 65 99 94
43 86 41 50 15
80 98 44 96 88
86 15 65 31 22
92 3 40 46 68
39 64 69 47 74
87 19 50 34 91
66 27 2 43 32
30 73 45 93 56
65 82 0 28 60
77 31 70 46 27
7 15 58 76 35
43 92 91 18 86
31 32 76 63 61
18 40 38 87 3
33 82 65 93 89
98 67 78 70 74
6 37 48 71 0
10 58 67 66 61
60 13 45 23 96
48 73 4 63 56
87 75 94 31 98
70 97 40 19 86
0 24 58 22 84
48 36 70 40 33
94 93 4 77 56
44 18 45 89 16
75 35 79 64 6
2 47 41 21 56
33 44 51 38 13
0 29 88 12 66
64 78 46 67 50
49 94 80 42 54
71 8 90 94 5
19 43 17 96 16
73 81 53 61 93
11 15 78 56 30
66 87 3 65 52
16 92 5 78 42
56 54 39 87 61
96 28 29 59 73
1 36 8 35 13
47 32 37 81 38
34 89 41 61 28
73 74 51 63 11
6 88 32 13 92
69 57 33 27 79
12 35 43 84 44
37 84 77 75 19
22 17 99 85 95
10 48 36 56 32
82 29 13 89 2
16 74 53 43 3
87 9 18 33 77
7 26 68 46 61
5 36 8 96 16
88 3 92 94 74
60 15 22 49 43
96 94 89 48 55
84 5 8 83 51
12 11 40 97 53
75 62 71 18 63
16 19 58 82 44
31 39 17 45 16
54 92 95 37 65
55 30 34 3 59
41 66 48 56 91
18 88 61 15 28
12 26 96 2 56
65 9 31 51 17
78 54 94 80 76
87 16 30 20 59
45 64 10 29 71
24 26 47 90 97
82 86 20 17 30
93 11 41 3 68
42 52 88 22 57
83 49 69 0 73
55 90 51 38 92
96 61 50 34 63
78 72 8 73 85
25 76 45 89 32
58 54 1 9 16
32 89 12 43 58
59 6 54 91 17
2 37 99 78 45
57 63 29 90 21
66 83 34 0 61
58 55 63 0 6
15 90 57 39 56
8 76 20 89 30
61 79 83 70 42
78 81 43 64 41
93 14 57 55 53
84 0 24 22 54
5 90 87 26 13
4 46 64 18 17
9 58 67 68 92
39 76 85 24 9
36 27 93 64 33
40 73 31 74 41
0 10 57 5 91
4 16 59 54 96
34 82 54 14 87
59 21 1 30 60
27 45 71 58 97
4 72 70 85 39
38 74 96 12 91
48 78 3 42 24
26 85 56 4 80
35 8 29 93 55
91 73 7 75 54
1 61 88 74 99
68 40 41 63 17
73 61 45 57 66
14 15 78 0 6
33 46 47 95 82
92 48 10 1 70
79 19 88 55 81
40 35 15 63 21
85 26 57 97 39
71 24 60 89 22
5 27 49 28 38
3 90 23 80 78
74 89 53 63 14
48 56 72 71 29
15 36 45 83 39
50 44 28 67 97
91 22 63 55 26
69 4 11 42 75
92 65 48 28 72
51 79 15 80 68
98 59 24 64 9
48 87 47 81 6
35 60 59 69 20
62 99 41 21 63
51 46 19 12 84
80 57 28 64 32
86 53 52 33 25
39 90 40 95 88
6 61 78 46 91
2 74 76 70 89
18 96 56 12 16
65 17 39 45 85
31 87 63 47 22
38 1 3 80 20
25 62 13 12 72
95 36 11 86 67
75 92 82 14 8
16 20 72 77 23
0 61 9 50 18
96 19 21 63 70
76 80 53 64 41
60 20 69 68 35
64 9 29 14 15
49 75 53 88 98
95 28 7 42 25
5 74 80 1 4
41 6 58 42 85
75 65 50 0 7
82 80 12 5 61
19 48 21 87 47
71 14 24 8 23
95 81 9 27 75
93 33 63 89 32
46 8 59 51 28
37 6 67 57 52
68 4 0 44 14
5 88 61 35 85
68 92 48 74 6
13 53 55 94 25
12 15 52 86 96
23 76 16 45 82
54 35 90 57 30
58 25 97 89 41
62 75 5 0 94
86 93 77 37 16
68 48 33 76 20
61 87 30 76 49
36 39 74 63 23
92 82 21 45 79
33 59 57 83 10
6 51 93 85 81
13 50 17 52 73
59 38 46 87 96
35 63 21 3 8
6 97 90 23 71
95 27 66 77 15
87 69 71 2 38
0 64 14 92 33
12 46 15 89 97
48 41 43 52 44
16 21 74 31 60
6 71 87 35 74
40 16 19 73 69
1 67 42 78 23
49 59 65 45 53
48 82 30 72 39
39 31 13 2 38
60 65 18 7 1
74 23 78 51 4
50 61 83 94 25
34 3 80 6 87
87 15 42 55 64
93 30 83 80 46
24 81 26 31 8
84 14 67 82 23
75 22 94 74 40
40 21 75 2 78
25 15 49 61 55
98 70 92 93 63
53 1 0 33 32
12 59 18 44 73
78 11 12 58 61
26 8 51 28 69
64 35 89 95 1
20 79 62 13 83
53 7 84 18 34
+21
View File
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_05</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Creek.HelpfulExtensions" Version="1.3.0" />
</ItemGroup>
<ItemGroup>
<None Update="input.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+151
View File
@@ -0,0 +1,151 @@
using Creek.HelpfulExtensions;
namespace Day04
{
class Program
{
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("input.txt");
//Part1(lines);
Part2(lines);
}
static void Part1(string[] lines)
{
int[,] ventLines = CreateVentLinesArray(lines, true);
// determine the number of points where at least two lines overlap
int counter = 0;
for (int i = 0; i < ventLines.GetLength(0); i++)
{
for (int j = 0; j < ventLines.GetLength(1); j++)
{
if (ventLines[i, j] >= 2)
{
counter += 1;
}
}
}
Console.WriteLine($"At least two lines overlap at {counter} points");
}
static void Part2(string[] lines)
{
int[,] ventLines = CreateVentLinesArray(lines, false);
// determine the number of points where at least two lines overlap
int counter = 0;
for (int i = 0; i < ventLines.GetLength(0); i++)
{
for (int j = 0; j < ventLines.GetLength(1); j++)
{
if (ventLines[i, j] >= 2)
{
counter += 1;
}
}
}
Console.WriteLine($"At least two lines overlap at {counter} points");
}
static int[,] CreateVentLinesArray(string[] lines, bool onlyVerticalAndHorizontal)
{
int[,] ventLines = new int[1000,1000];
foreach (var line in lines)
{
// e.g. 645,570 -> 517,570
int startX = int.Parse(line.Substring(0, line.IndexOf(",")));
int startY = int.Parse(line.SubstringBetween(",", " ").Substring(1));
int endX = int.Parse(line.SubstringBetween("-> ", ",", true).Substring(3));
int endY = int.Parse(line.Substring(line.LastIndexOf(",") + 1));
if (onlyVerticalAndHorizontal)
{
if(startX == endX || startY == endY)
{
// They are not always in size order, so get their size order
int smallX = startX > endX ? endX : startX;
int bigX = startX > endX ? startX : endX;
int smallY = startY > endY ? endY : startY;
int bigY = startY > endY ? startY : endY;
for (int i = smallX; i <= bigX; i++)
{
for (int j = smallY; j <= bigY; j++)
{
ventLines[i, j] += 1;
}
}
}
}
else
{
if (startX == endX || startY == endY)
{
// They are not always in size order, so get their size order
int smallX = startX > endX ? endX : startX;
int bigX = startX > endX ? startX : endX;
int smallY = startY > endY ? endY : startY;
int bigY = startY > endY ? startY : endY;
for (int i = smallX; i <= bigX; i++)
{
for (int j = smallY; j <= bigY; j++)
{
ventLines[i, j] += 1;
}
}
}
else
{
// Diagonal
int currentX = startX;
int currentY = startY;
while (true)
{
ventLines[currentX, currentY] += 1;
if (currentX == endX && currentY == endY)
{
break;
}
if (startX > endX)
{
currentX -= 1;
}
else
{
currentX += 1;
}
if (startY > endY)
{
currentY -= 1;
}
else
{
currentY += 1;
}
}
}
}
}
return ventLines;
}
}
}
+38
View File
@@ -0,0 +1,38 @@
--- Day 5: Hydrothermal Venture ---
You come across a field of hydrothermal vents on the ocean floor! These vents constantly produce large, opaque clouds, so it would be best to avoid them if possible.
They tend to form in lines; the submarine helpfully produces a list of nearby lines of vents (your puzzle input) for you to review. For example:
0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2
Each line of vents is given as a line segment in the format x1,y1 -> x2,y2 where x1,y1 are the coordinates of one end the line segment and x2,y2 are the coordinates of the other end. These line segments include the points at both ends. In other words:
An entry like 1,1 -> 1,3 covers points 1,1, 1,2, and 1,3.
An entry like 9,7 -> 7,7 covers points 9,7, 8,7, and 7,7.
For now, only consider horizontal and vertical lines: lines where either x1 = x2 or y1 = y2.
So, the horizontal and vertical lines from the above list would produce the following diagram:
.......1..
..1....1..
..1....1..
.......1..
.112111211
..........
..........
..........
..........
222111....
In this diagram, the top left corner is 0,0 and the bottom right corner is 9,9. Each position is shown as the number of lines which cover that point or . if no line covers that point. The top-left pair of 1s, for example, comes from 2,2 -> 2,1; the very bottom row is formed by the overlapping lines 0,9 -> 5,9 and 0,9 -> 2,9.
To avoid the most dangerous areas, you need to determine the number of points where at least two lines overlap. In the above example, this is anywhere in the diagram with a 2 or larger - a total of 5 points.
Consider only horizontal and vertical lines. At how many points do at least two lines overlap?
+22
View File
@@ -0,0 +1,22 @@
--- Part Two ---
Unfortunately, considering only horizontal and vertical lines doesn't give you the full picture; you need to also consider diagonal lines.
Because of the limits of the hydrothermal vent mapping system, the lines in your list will only ever be horizontal, vertical, or a diagonal line at exactly 45 degrees. In other words:
An entry like 1,1 -> 3,3 covers points 1,1, 2,2, and 3,3.
An entry like 9,7 -> 7,9 covers points 9,7, 8,8, and 7,9.
Considering all lines from the above example would now produce the following diagram:
1.1....11.
.111...2..
..2.1.111.
...1.2.2..
.112313211
...1.2....
..1...1...
.1.....1..
1.......1.
222111....
You still need to determine the number of points where at least two lines overlap. In the above example, this is still anywhere in the diagram with a 2 or larger - now a total of 12 points.
Consider all of the lines. At how many points do at least two lines overlap?
+500
View File
@@ -0,0 +1,500 @@
645,570 -> 517,570
100,409 -> 200,409
945,914 -> 98,67
22,934 -> 22,681
935,781 -> 524,370
750,304 -> 854,408
974,27 -> 26,975
529,58 -> 979,58
979,515 -> 550,944
925,119 -> 17,119
178,594 -> 45,461
252,366 -> 92,206
25,593 -> 250,593
956,34 -> 21,969
200,671 -> 200,369
628,614 -> 628,637
697,428 -> 237,428
554,40 -> 554,949
927,197 -> 469,197
504,779 -> 593,868
227,882 -> 227,982
56,905 -> 56,81
438,874 -> 566,746
989,73 -> 113,949
82,36 -> 616,570
670,423 -> 670,873
100,435 -> 291,435
242,81 -> 978,817
367,335 -> 367,332
890,584 -> 116,584
572,192 -> 572,561
391,516 -> 391,559
525,62 -> 525,540
787,540 -> 812,515
749,732 -> 423,406
745,911 -> 694,911
805,18 -> 972,18
701,565 -> 280,144
930,92 -> 129,893
15,989 -> 970,34
409,920 -> 409,345
192,743 -> 312,863
724,12 -> 29,707
323,664 -> 323,897
161,423 -> 391,653
59,363 -> 250,554
407,676 -> 19,288
449,585 -> 449,301
914,798 -> 914,806
917,401 -> 288,401
588,800 -> 647,800
897,883 -> 897,276
115,606 -> 41,532
692,482 -> 777,482
428,736 -> 69,736
405,44 -> 405,632
198,482 -> 198,620
988,816 -> 988,598
254,461 -> 186,393
560,783 -> 208,783
856,766 -> 215,125
182,30 -> 569,30
504,242 -> 656,242
393,929 -> 131,929
597,359 -> 26,930
502,690 -> 255,443
149,608 -> 149,748
293,662 -> 622,662
697,154 -> 697,228
587,804 -> 983,804
715,63 -> 715,709
496,831 -> 23,358
461,48 -> 68,441
927,565 -> 595,565
972,350 -> 689,350
728,438 -> 728,221
173,134 -> 173,804
720,368 -> 121,368
690,66 -> 201,66
218,680 -> 841,680
80,792 -> 80,467
624,319 -> 624,461
248,348 -> 532,64
357,260 -> 505,408
296,814 -> 13,531
819,216 -> 819,932
696,233 -> 696,840
219,93 -> 868,93
537,63 -> 905,63
777,940 -> 777,84
286,133 -> 286,735
969,967 -> 969,823
254,222 -> 859,827
426,728 -> 426,388
854,561 -> 854,363
755,861 -> 755,947
570,754 -> 439,754
333,351 -> 333,828
436,693 -> 436,262
982,987 -> 172,177
267,178 -> 267,270
218,201 -> 747,730
811,602 -> 829,584
602,659 -> 766,659
536,544 -> 483,597
280,881 -> 547,881
584,125 -> 129,125
386,210 -> 757,210
605,855 -> 605,668
19,985 -> 988,16
980,655 -> 836,655
73,189 -> 267,383
621,645 -> 533,645
36,12 -> 255,231
538,889 -> 130,481
921,217 -> 921,724
873,59 -> 873,311
76,918 -> 970,24
694,448 -> 694,983
573,891 -> 573,337
796,358 -> 403,358
532,928 -> 351,928
123,717 -> 123,446
874,714 -> 874,886
350,458 -> 728,458
798,140 -> 798,242
832,406 -> 864,406
188,55 -> 188,641
903,376 -> 509,376
50,954 -> 989,15
42,294 -> 25,294
544,273 -> 974,273
804,756 -> 103,55
398,184 -> 570,12
82,179 -> 902,179
461,728 -> 905,284
429,241 -> 26,241
128,715 -> 207,715
239,545 -> 934,545
978,769 -> 978,576
250,77 -> 515,77
521,533 -> 521,434
955,844 -> 314,203
144,601 -> 702,43
313,784 -> 339,784
388,692 -> 805,275
540,872 -> 540,72
971,19 -> 17,973
816,540 -> 386,540
933,246 -> 560,619
800,600 -> 387,187
272,791 -> 129,934
908,133 -> 110,931
759,191 -> 910,40
420,479 -> 749,150
604,946 -> 804,946
633,404 -> 771,266
948,974 -> 948,734
735,198 -> 105,828
889,653 -> 889,688
157,172 -> 822,837
206,670 -> 297,670
50,122 -> 792,864
656,664 -> 27,664
966,33 -> 523,33
985,40 -> 101,924
394,367 -> 574,547
440,573 -> 268,573
159,989 -> 159,130
867,123 -> 867,891
316,153 -> 316,249
680,59 -> 773,152
52,928 -> 52,182
128,595 -> 225,595
508,719 -> 591,719
595,447 -> 709,333
930,783 -> 283,136
366,236 -> 283,236
820,512 -> 381,951
135,450 -> 135,766
750,838 -> 534,838
259,304 -> 626,671
414,631 -> 916,129
193,862 -> 901,154
362,595 -> 362,209
377,215 -> 377,499
723,16 -> 577,16
335,238 -> 790,693
670,266 -> 871,65
288,313 -> 213,313
48,423 -> 592,967
960,323 -> 911,323
177,182 -> 177,235
773,918 -> 757,918
216,432 -> 147,432
808,500 -> 656,500
205,451 -> 776,451
598,985 -> 598,608
193,253 -> 241,205
912,384 -> 912,532
214,194 -> 214,738
508,356 -> 508,792
16,372 -> 30,372
384,854 -> 986,252
361,569 -> 851,569
923,550 -> 923,441
271,257 -> 318,304
651,345 -> 651,397
885,14 -> 929,14
199,547 -> 925,547
803,176 -> 104,875
840,302 -> 197,945
971,743 -> 355,127
684,951 -> 684,292
58,867 -> 58,953
351,187 -> 351,831
701,413 -> 701,728
482,159 -> 134,159
118,52 -> 950,884
115,968 -> 115,137
437,739 -> 627,929
653,153 -> 549,153
604,504 -> 560,460
538,865 -> 840,563
114,876 -> 114,124
152,899 -> 925,126
973,224 -> 973,387
492,360 -> 861,729
927,902 -> 108,83
754,678 -> 754,647
526,671 -> 423,671
675,608 -> 243,608
147,241 -> 147,242
456,770 -> 456,665
953,50 -> 102,901
415,869 -> 415,733
979,533 -> 169,533
336,385 -> 336,18
927,176 -> 927,587
370,317 -> 933,880
450,349 -> 450,103
755,235 -> 408,235
342,55 -> 931,55
417,707 -> 887,237
141,95 -> 131,85
776,209 -> 590,23
39,732 -> 469,302
743,602 -> 743,358
473,439 -> 473,545
270,290 -> 270,640
904,963 -> 949,963
71,91 -> 956,976
865,757 -> 276,757
59,72 -> 966,979
46,184 -> 788,926
360,833 -> 561,833
120,452 -> 528,452
704,927 -> 158,381
140,481 -> 140,350
929,920 -> 929,342
328,381 -> 328,866
897,389 -> 227,389
341,614 -> 29,614
609,327 -> 609,582
727,858 -> 727,941
349,536 -> 349,500
280,959 -> 259,959
973,637 -> 832,637
161,255 -> 979,255
512,826 -> 149,826
308,769 -> 22,769
60,692 -> 60,262
787,31 -> 753,31
932,166 -> 932,127
514,77 -> 514,646
535,434 -> 535,979
838,799 -> 838,332
565,956 -> 565,477
74,195 -> 274,195
916,715 -> 907,715
721,655 -> 721,542
180,784 -> 928,784
16,128 -> 313,128
23,330 -> 23,704
530,723 -> 530,88
869,272 -> 765,376
878,185 -> 353,185
72,800 -> 514,800
319,117 -> 307,117
436,405 -> 496,345
327,459 -> 641,145
358,309 -> 661,612
60,225 -> 811,976
113,130 -> 794,130
559,950 -> 32,423
626,110 -> 626,319
50,39 -> 989,978
257,627 -> 799,627
581,843 -> 581,493
869,18 -> 208,18
184,395 -> 184,263
454,888 -> 165,599
637,920 -> 637,544
170,982 -> 273,982
98,354 -> 668,924
32,409 -> 32,925
154,175 -> 273,294
425,896 -> 870,451
198,319 -> 615,736
170,582 -> 170,712
141,645 -> 141,639
482,768 -> 486,768
940,969 -> 24,53
680,360 -> 959,360
315,905 -> 315,96
22,666 -> 22,247
722,40 -> 722,714
585,31 -> 585,21
479,254 -> 307,254
291,182 -> 291,855
684,698 -> 402,698
20,984 -> 988,16
256,424 -> 17,663
825,380 -> 820,385
254,622 -> 254,315
98,855 -> 98,694
220,719 -> 220,117
615,653 -> 656,694
427,12 -> 427,745
20,64 -> 828,872
739,203 -> 434,203
546,576 -> 130,160
730,835 -> 299,835
927,512 -> 927,586
411,192 -> 868,192
917,630 -> 678,630
620,588 -> 620,26
786,488 -> 486,488
746,640 -> 251,145
585,556 -> 585,119
977,202 -> 762,202
587,244 -> 587,877
693,479 -> 693,859
59,816 -> 59,475
191,941 -> 878,254
150,920 -> 926,144
856,397 -> 856,739
380,965 -> 549,796
637,323 -> 909,595
848,219 -> 304,763
123,146 -> 589,146
546,122 -> 651,122
131,711 -> 814,28
727,274 -> 296,274
101,546 -> 479,168
508,517 -> 615,410
492,115 -> 492,250
212,65 -> 770,623
118,938 -> 857,199
623,843 -> 98,843
86,153 -> 701,768
81,98 -> 81,604
173,313 -> 173,533
792,396 -> 792,242
975,985 -> 10,20
762,661 -> 726,661
216,327 -> 216,122
446,658 -> 98,658
85,184 -> 314,184
165,750 -> 313,750
729,583 -> 729,640
382,36 -> 382,326
487,32 -> 225,32
389,722 -> 582,915
954,965 -> 86,965
747,376 -> 747,96
254,259 -> 254,482
149,256 -> 149,871
893,207 -> 708,22
195,907 -> 195,82
342,686 -> 457,571
647,469 -> 468,469
150,525 -> 832,525
90,907 -> 90,31
389,554 -> 389,318
138,327 -> 138,310
861,126 -> 861,549
355,583 -> 355,534
591,182 -> 181,592
73,84 -> 897,908
326,989 -> 425,989
835,688 -> 724,799
844,493 -> 844,974
172,436 -> 172,12
536,933 -> 48,445
192,531 -> 287,531
286,547 -> 80,547
929,795 -> 697,795
790,681 -> 433,681
692,229 -> 731,229
377,667 -> 14,304
535,226 -> 116,645
338,861 -> 338,343
668,160 -> 853,160
188,157 -> 667,636
62,934 -> 951,45
948,820 -> 978,820
860,884 -> 157,884
794,251 -> 783,251
317,381 -> 591,655
459,876 -> 459,307
146,822 -> 903,65
374,739 -> 891,739
619,575 -> 973,929
544,351 -> 544,124
300,335 -> 818,335
158,220 -> 418,480
107,953 -> 988,953
304,753 -> 543,753
948,95 -> 140,903
832,451 -> 526,145
966,34 -> 402,598
72,123 -> 716,123
336,294 -> 84,294
116,605 -> 116,889
700,742 -> 700,217
551,554 -> 973,554
684,181 -> 66,799
86,949 -> 86,173
834,361 -> 834,942
508,668 -> 627,549
213,695 -> 704,695
260,979 -> 868,371
825,435 -> 825,67
956,854 -> 66,854
390,444 -> 697,444
360,450 -> 720,810
153,514 -> 794,514
253,261 -> 253,298
925,679 -> 925,499
391,282 -> 441,282
86,366 -> 779,366
687,312 -> 687,629
304,172 -> 732,600
571,518 -> 263,518
814,252 -> 118,252
108,920 -> 108,162
154,965 -> 928,191
635,875 -> 635,947
986,31 -> 47,970
746,35 -> 746,636
735,849 -> 334,448
826,510 -> 906,590
834,745 -> 834,949
843,401 -> 564,122
179,212 -> 179,32
354,906 -> 233,906
593,439 -> 196,42
707,446 -> 242,446
511,84 -> 511,406
109,299 -> 100,290
410,79 -> 410,784
806,923 -> 54,171
592,83 -> 592,189
413,28 -> 413,469
17,844 -> 17,691
130,419 -> 205,344
374,247 -> 849,247
650,344 -> 653,344
563,942 -> 563,726
771,966 -> 450,966
499,693 -> 788,693
962,458 -> 962,356
28,683 -> 765,683
432,546 -> 432,708
519,974 -> 176,974
797,744 -> 280,227
505,228 -> 547,228
401,366 -> 401,754
356,470 -> 123,470
57,909 -> 229,909
343,880 -> 539,880
221,851 -> 221,297
520,677 -> 894,677
216,805 -> 688,805
158,901 -> 847,901
98,129 -> 98,969
793,203 -> 210,786
852,855 -> 135,138
944,90 -> 103,931
691,768 -> 583,768
784,617 -> 637,764
222,160 -> 819,757
145,982 -> 145,216
837,355 -> 99,355
324,121 -> 324,14
773,851 -> 773,413
778,550 -> 686,458
81,56 -> 338,313
356,512 -> 356,441
+19
View File
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_06</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0" />
</ItemGroup>
</Project>
@@ -0,0 +1,37 @@
// <auto-generated />
using Day06;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace _06.Migrations
{
[DbContext(typeof(FishContext))]
[Migration("20211206123902_InitialCreate")]
partial class InitialCreate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "6.0.0");
modelBuilder.Entity("Day06.Fish", b =>
{
b.Property<int>("FishId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("InternalTimer")
.HasColumnType("INTEGER");
b.HasKey("FishId");
b.ToTable("Fishes");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,31 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace _06.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Fishes",
columns: table => new
{
FishId = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
InternalTimer = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Fishes", x => x.FishId);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Fishes");
}
}
}
@@ -0,0 +1,35 @@
// <auto-generated />
using Day06;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace _06.Migrations
{
[DbContext(typeof(FishContext))]
partial class FishContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "6.0.0");
modelBuilder.Entity("Day06.Fish", b =>
{
b.Property<int>("FishId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("InternalTimer")
.HasColumnType("INTEGER");
b.HasKey("FishId");
b.ToTable("Fishes");
});
#pragma warning restore 612, 618
}
}
}
+31
View File
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace Day06
{
public class FishContext : DbContext
{
public DbSet<Fish> Fishes { get; set; }
public string DbPath { get; }
public FishContext()
{
var folder = Environment.SpecialFolder.LocalApplicationData;
var path = Environment.GetFolderPath(folder);
DbPath = System.IO.Path.Join(path, "fishes.db");
}
// The following configures EF to create a Sqlite database file in the
// special "local" folder for your platform.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite($"Data Source={DbPath}");
}
public class Fish
{
public int FishId { get; set; }
public int InternalTimer { get; set; }
}
}
+118
View File
@@ -0,0 +1,118 @@
namespace Day06
{
class Program
{
static void Main(string[] args)
{
string input = File.ReadAllLines("input.txt")[0];
List<int> lanternFish = input.Split(',').Select(int.Parse).ToList();
//Part1(lanternFish);
Part2(lanternFish);
}
static void SimulateLanternFish(ref List<int> lanternFishPopulation, int daysToSimulate)
{
// A lanternfish that creates a new fish resets its timer to 6, not 7 (because 0 is included as a valid timer value). The new lanternfish starts with an internal timer of 8 and does not start counting down until the next day.
int currentDay = 1;
while (currentDay <= daysToSimulate)
{
Console.WriteLine($"Day: {currentDay} - there are {lanternFishPopulation.Count()} lantern fish");
for (int i = 0; i < lanternFishPopulation.Count; i++)
{
switch (lanternFishPopulation[i])
{
case 0:
// its internal timer would reset to 6, and it would create a new lanternfish with an internal timer of 8.
lanternFishPopulation[i] = 6;
// Adding a new one with 9 though it should be 8 as this loop will catch new fish and decrement them. It's dirty, but fast way to solve the issue
lanternFishPopulation.Add(9);
break;
default:
// remove one day from the fish's countdown
lanternFishPopulation[i] -= 1;
break;
}
}
currentDay += 1;
}
}
static void SimulateLanternFishBigDatasets(ref List<int> lanternFishPopulation, int daysToSimulate)
{
// A lanternfish that creates a new fish resets its timer to 6, not 7 (because 0 is included as a valid timer value). The new lanternfish starts with an internal timer of 8 and does not start counting down until the next day.
// Store dataset into db
using (var db = new FishContext())
{
foreach (var fish in lanternFishPopulation)
{
db.Add(new Fish { InternalTimer = fish });
db.SaveChanges();
}
}
int currentDay = 1;
while (currentDay <= daysToSimulate)
{
using (var db = new FishContext())
{
int fishCount = db.Fishes.Count();
Console.WriteLine($"Day: {currentDay} - there are {fishCount} lantern fish");
List<int> fishIds = db.Fishes.Select(x => x.FishId).ToList();
foreach (int fishId in fishIds)
{
Fish fish = db.Fishes.First(x => x.FishId == fishId);
switch (fish.InternalTimer)
{
case 0:
// its internal timer would reset to 6, and it would create a new lanternfish with an internal timer of 8.
fish.InternalTimer = 6;
// Adding a new one with 9 though it should be 8 as this loop will catch new fish and decrement them. It's dirty, but fast way to solve the issue
db.Add(new Fish { InternalTimer = 9 });
break;
default:
// remove one day from the fish's countdown
fish.InternalTimer -= 1;
break;
}
}
db.SaveChanges();
}
currentDay += 1;
}
}
static void Part1(List<int> lanternFish)
{
SimulateLanternFish(ref lanternFish, 80);
Console.WriteLine($"After 80 days there are {lanternFish.Count()} lantern fish.");
}
static void Part2(List<int> lanternFish)
{
SimulateLanternFishBigDatasets(ref lanternFish, 256);
// TODO - redo this using a database for large datasets, and entity framework, so as to avoid the HUGE memory usage
using (var db = new FishContext())
{
int fishCount = db.Fishes.Count();
Console.WriteLine($"After 256 days there are {fishCount} lantern fish.");
}
}
}
}
+49
View File
@@ -0,0 +1,49 @@
--- Day 6: Lanternfish ---
The sea floor is getting steeper. Maybe the sleigh keys got carried this way?
A massive school of glowing lanternfish swims past. They must spawn quickly to reach such large numbers - maybe exponentially quickly? You should model their growth rate to be sure.
Although you know nothing about this specific species of lanternfish, you make some guesses about their attributes. Surely, each lanternfish creates a new lanternfish once every 7 days.
However, this process isn't necessarily synchronized between every lanternfish - one lanternfish might have 2 days left until it creates another lanternfish, while another might have 4. So, you can model each fish as a single number that represents the number of days until it creates a new lanternfish.
Furthermore, you reason, a new lanternfish would surely need slightly longer before it's capable of producing more lanternfish: two more days for its first cycle.
So, suppose you have a lanternfish with an internal timer value of 3:
After one day, its internal timer would become 2.
After another day, its internal timer would become 1.
After another day, its internal timer would become 0.
After another day, its internal timer would reset to 6, and it would create a new lanternfish with an internal timer of 8.
After another day, the first lanternfish would have an internal timer of 5, and the second lanternfish would have an internal timer of 7.
A lanternfish that creates a new fish resets its timer to 6, not 7 (because 0 is included as a valid timer value). The new lanternfish starts with an internal timer of 8 and does not start counting down until the next day.
Realizing what you're trying to do, the submarine automatically produces a list of the ages of several hundred nearby lanternfish (your puzzle input). For example, suppose you were given the following list:
3,4,3,1,2
This list means that the first fish has an internal timer of 3, the second fish has an internal timer of 4, and so on until the fifth fish, which has an internal timer of 2. Simulating these fish over several days would proceed as follows:
Initial state: 3,4,3,1,2
After 1 day: 2,3,2,0,1
After 2 days: 1,2,1,6,0,8
After 3 days: 0,1,0,5,6,7,8
After 4 days: 6,0,6,4,5,6,7,8,8
After 5 days: 5,6,5,3,4,5,6,7,7,8
After 6 days: 4,5,4,2,3,4,5,6,6,7
After 7 days: 3,4,3,1,2,3,4,5,5,6
After 8 days: 2,3,2,0,1,2,3,4,4,5
After 9 days: 1,2,1,6,0,1,2,3,3,4,8
After 10 days: 0,1,0,5,6,0,1,2,2,3,7,8
After 11 days: 6,0,6,4,5,6,0,1,1,2,6,7,8,8,8
After 12 days: 5,6,5,3,4,5,6,0,0,1,5,6,7,7,7,8,8
After 13 days: 4,5,4,2,3,4,5,6,6,0,4,5,6,6,6,7,7,8,8
After 14 days: 3,4,3,1,2,3,4,5,5,6,3,4,5,5,5,6,6,7,7,8
After 15 days: 2,3,2,0,1,2,3,4,4,5,2,3,4,4,4,5,5,6,6,7
After 16 days: 1,2,1,6,0,1,2,3,3,4,1,2,3,3,3,4,4,5,5,6,8
After 17 days: 0,1,0,5,6,0,1,2,2,3,0,1,2,2,2,3,3,4,4,5,7,8
After 18 days: 6,0,6,4,5,6,0,1,1,2,6,0,1,1,1,2,2,3,3,4,6,7,8,8,8,8
Each day, a 0 becomes a 6 and adds a new 8 to the end of the list, while each other number decreases by 1 if it was present at the start of the day.
In this example, after 18 days, there are a total of 26 fish. After 80 days, there would be a total of 5934.
Find a way to simulate lanternfish. How many lanternfish would there be after 80 days?
+6
View File
@@ -0,0 +1,6 @@
--- Part Two ---
Suppose the lanternfish live forever and have unlimited food and space. Would they take over the entire ocean?
After 256 days in the example above, there would be a total of 26984457539 lanternfish!
How many lanternfish would there be after 256 days?
+1
View File
@@ -0,0 +1 @@
3,4,3,1,2
+3
View File
@@ -0,0 +1,3 @@
Run dotnet ef database update to initialise the database
Delete the database if you want to run the code again
It's at C:\Users\Josh\AppData\Local as fishes.db and other associated files
+11
View File
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_07</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+79
View File
@@ -0,0 +1,79 @@
namespace Day07
{
class Program
{
static void Main(string[] args)
{
string input = File.ReadAllLines("input.txt")[0];
List<int> initialCrabPositions = input.Split(',').Select(int.Parse).ToList();
//Part1(initialCrabPositions);
Part2(initialCrabPositions);
}
static void Part1(List<int> initialCrabPositions)
{
// double mean = initialCrabPositions.Average();
// int meanAverage = Convert.ToInt32(mean);
int medianAverage = initialCrabPositions.OrderBy(x=>x).Skip(initialCrabPositions.Count()/2).First();
// int modalAverage = initialCrabPositions.GroupBy(n=> n).
// OrderByDescending(g=> g.Count()).
// Select(g => g.Key).FirstOrDefault();
// Console.WriteLine($"Mean average: {meanAverage}");
Console.WriteLine($"Median average: {medianAverage}");
// Console.WriteLine($"Modal average: {modalAverage}");
int totalFuelConsumption = 0;
foreach (int position in initialCrabPositions)
{
// Find the difference
totalFuelConsumption += Math.Abs(position - medianAverage);
}
Console.WriteLine($"Total fuel consumption: {totalFuelConsumption}");
}
static void Part2(List<int> initialCrabPositions)
{
// Calculate optimal position
// Loop through all possible positions and work out the total fuel consumption
int minPosition = initialCrabPositions.Min();
int maxPosition = initialCrabPositions.Max();
Dictionary<int, int> possiblePositions = new Dictionary<int, int>();
for (int i = minPosition; i <= maxPosition; i++)
{
possiblePositions.Add(i,CalculateTotalFuelConsumption(initialCrabPositions, i));
}
// Find lowest fuel consumption
var lowestFuelConsumptionPosition = possiblePositions.OrderBy(kvp => kvp.Value).First();
Console.WriteLine($"Position: {lowestFuelConsumptionPosition.Key} Fuel consumption: {lowestFuelConsumptionPosition.Value}");
}
public static int CalculateTotalFuelConsumption(List<int> initialCrabPositions, int targetPosition)
{
int totalFuelConsumption = 0;
foreach (int position in initialCrabPositions)
{
// Find the difference
int difference = Math.Abs(position - targetPosition);
totalFuelConsumption += Convert.ToInt32(GetTriangularNumber(difference));
}
return totalFuelConsumption;
}
public static double GetTriangularNumber(int n)
{
return n*(n + 1) / 2;
}
}
}
+31
View File
@@ -0,0 +1,31 @@
--- Day 7: The Treachery of Whales ---
A giant whale has decided your submarine is its next meal, and it's much faster than you are. There's nowhere to run!
Suddenly, a swarm of crabs (each in its own tiny submarine - it's too deep for them otherwise) zooms in to rescue you! They seem to be preparing to blast a hole in the ocean floor; sensors indicate a massive underground cave system just beyond where they're aiming!
The crab submarines all need to be aligned before they'll have enough power to blast a large enough hole for your submarine to get through. However, it doesn't look like they'll be aligned before the whale catches you! Maybe you can help?
There's one major catch - crab submarines can only move horizontally.
You quickly make a list of the horizontal position of each crab (your puzzle input). Crab submarines have limited fuel, so you need to find a way to make all of their horizontal positions match while requiring them to spend as little fuel as possible.
For example, consider the following horizontal positions:
16,1,2,0,4,2,7,1,2,14
This means there's a crab with horizontal position 16, a crab with horizontal position 1, and so on.
Each change of 1 step in horizontal position of a single crab costs 1 fuel. You could choose any horizontal position to align them all on, but the one that costs the least fuel is horizontal position 2:
Move from 16 to 2: 14 fuel
Move from 1 to 2: 1 fuel
Move from 2 to 2: 0 fuel
Move from 0 to 2: 2 fuel
Move from 4 to 2: 2 fuel
Move from 2 to 2: 0 fuel
Move from 7 to 2: 5 fuel
Move from 1 to 2: 1 fuel
Move from 2 to 2: 0 fuel
Move from 14 to 2: 12 fuel
This costs a total of 37 fuel. This is the cheapest possible outcome; more expensive outcomes include aligning at position 1 (41 fuel), position 3 (39 fuel), or position 10 (71 fuel).
Determine the horizontal position that the crabs can align to using the least fuel possible. How much fuel must they spend to align to that position?
+20
View File
@@ -0,0 +1,20 @@
--- Part Two ---
The crabs don't seem interested in your proposed solution. Perhaps you misunderstand crab engineering?
As it turns out, crab submarine engines don't burn fuel at a constant rate. Instead, each change of 1 step in horizontal position costs 1 more unit of fuel than the last: the first step costs 1, the second step costs 2, the third step costs 3, and so on.
As each crab moves, moving further becomes more expensive. This changes the best horizontal position to align them all on; in the example above, this becomes 5:
Move from 16 to 5: 66 fuel
Move from 1 to 5: 10 fuel
Move from 2 to 5: 6 fuel
Move from 0 to 5: 15 fuel
Move from 4 to 5: 1 fuel
Move from 2 to 5: 6 fuel
Move from 7 to 5: 3 fuel
Move from 1 to 5: 10 fuel
Move from 2 to 5: 6 fuel
Move from 14 to 5: 45 fuel
This costs a total of 168 fuel. This is the new cheapest possible outcome; the old alignment position (2) now costs 206 fuel instead.
Determine the horizontal position that the crabs can align to using the least fuel possible so they can make you an escape route! How much fuel must they spend to align to that position?
+1
View File
@@ -0,0 +1 @@
1101,1,29,67,1102,0,1,65,1008,65,35,66,1005,66,28,1,67,65,20,4,0,1001,65,1,65,1106,0,8,99,35,67,101,99,105,32,110,39,101,115,116,32,112,97,115,32,117,110,101,32,105,110,116,99,111,100,101,32,112,114,111,103,114,97,109,10,161,185,311,752,668,728,210,741,636,381,1222,509,282,156,806,624,31,300,711,128,146,368,306,239,7,519,441,368,179,155,704,274,237,710,164,55,217,1007,0,701,812,713,127,536,320,163,454,310,726,433,426,102,1350,736,408,951,307,15,333,462,755,797,265,540,680,357,914,195,468,1034,583,413,1293,450,88,2,208,1006,336,98,17,164,95,455,511,113,710,636,308,330,479,62,197,591,390,148,933,1060,10,564,137,422,1756,494,1205,79,13,1257,205,738,245,462,313,249,1580,929,914,512,370,152,413,6,223,197,777,885,1387,52,824,1308,422,728,298,123,922,234,33,109,747,231,916,1452,432,397,222,857,113,119,437,1474,129,1214,69,595,347,293,885,363,72,315,77,1131,55,1541,1244,37,724,553,65,327,341,619,800,547,104,33,272,1557,1316,141,476,510,505,188,1734,175,52,222,1392,732,303,959,75,432,224,293,112,99,923,396,1069,241,246,1146,823,961,593,367,394,324,390,20,63,403,602,571,125,649,60,327,190,1661,140,486,420,833,1464,218,80,74,345,366,191,119,109,399,1596,431,445,1179,1195,144,136,51,215,19,106,998,664,89,49,1041,101,814,995,279,810,702,738,471,315,217,60,24,272,490,7,1294,322,594,804,165,130,125,18,1422,208,0,148,544,901,1530,50,207,364,904,197,585,153,536,1014,571,1086,782,727,125,1174,453,1773,0,106,790,634,385,39,91,599,48,98,128,562,595,901,1269,108,219,583,162,101,182,645,371,17,872,73,156,313,243,678,75,727,566,282,193,28,75,576,394,176,132,172,27,758,496,57,32,73,1791,208,1660,429,38,1518,419,1748,52,1193,353,175,198,186,105,195,75,867,380,417,341,574,628,1076,116,1441,1353,528,530,205,0,1434,827,556,493,884,172,187,441,182,227,954,1016,3,336,786,947,155,373,52,26,969,686,837,477,8,31,288,952,574,159,511,351,440,774,948,213,45,773,294,75,742,300,686,395,315,1658,264,119,28,993,392,99,759,384,317,1105,562,324,416,375,938,329,988,1334,439,1284,557,28,225,438,216,501,358,743,206,1150,378,30,850,1149,296,279,132,387,64,895,157,528,138,12,688,1045,153,42,54,1281,535,427,297,1037,253,68,424,428,205,138,93,82,383,93,1061,1116,287,888,204,777,35,548,784,268,897,1167,201,532,151,198,388,3,306,1689,555,207,852,723,173,655,535,963,46,54,1705,490,244,67,299,543,333,185,196,361,147,891,370,797,195,386,371,1111,156,1587,641,1252,430,40,715,930,1560,774,227,122,179,45,72,744,27,6,1479,1178,969,108,395,37,31,426,1131,495,246,36,63,121,286,594,856,2,1773,1724,5,421,51,344,1312,382,24,15,246,921,562,20,818,493,44,239,1047,368,37,245,245,851,35,2,442,792,235,516,450,282,812,510,161,731,788,93,475,205,222,1005,1002,358,860,875,1330,354,724,114,207,956,597,234,206,55,637,7,48,751,123,241,858,255,508,200,1064,79,169,85,768,255,21,708,340,145,385,1130,281,39,1072,100,285,1355,360,283,560,153,488,689,319,929,309,1013,95,88,843,208,126,146,3,328,75,251,18,1053,782,556,94,743,299,66,311,18,789,1323,45,777,281,75,676,741,340,1055,870,1935,203,80,93,1372,747,6,79,560,33,67,1,197,193,1245,40,466,1144,557,16,664,144,984,590,1105,165,131,41,455,77,33,572,477,854,18,157,48,453,487,25,423,181,800,615,25,374,183,380,262,219,81,466,691,119,754,122,918,920,410,1102,156,1355,101,395,1837,89,40,341,264,393,547,564,480,13,24,259,1054,19,390,1199,664,205,645,274,43,115,354,329,473,812,1302,771,308,94,838,593,942,1107,153,394,596,194,119,719,1392,1094,26,252,1276,162,310,23,1681,106,160,1206,509,684,432,1659,129,172,99,630,417,151,69,211,874,310,1109,740,589,496,508,742,407,1156,1920,209,218,375,468,971,705,68,1603,158,236,121,63,1615,822,198,322,946,368,128,231,125,125,41,278,574,359,28,20,322,785,382,990,266,1586,324,710,159,727,28,11,15,211,620,762,73,1,75,33,239,327,1105,228,4,1256,1578,729,1164,44,222,1177,186,1593,605,43,239,1353,877,300,75,54,324,1487,1655,715,597,540,202,266,1030,576,251,14,669,833,66,1285,170,109,433,1760,60,948,542,129,5,165,173,659,743
+17
View File
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_08</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Update="input.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+166
View File
@@ -0,0 +1,166 @@
namespace Day08
{
class Program
{
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("input.txt");
//Part1(lines);
Part2(lines);
}
static void Part1(string[] lines)
{
// 8 has only 7 segments/letters
// 7 has only 3 segments/letters
// 4 has only 4 segments/letters
// 1 has only 2 segments/letters
// Count how often groups of letters with 2/3/4/7 segments occur after the split
int count = 0;
foreach (string line in lines)
{
string secondHalf = line.Substring(line.IndexOf("|") + 1);
List<string> numberSegments = secondHalf.Split(' ').ToList();
foreach (string numberSegment in numberSegments)
{
switch (numberSegment.Length)
{
case 7:
case 3:
case 4:
case 2:
count += 1;
break;
default:
// code block
break;
}
}
}
Console.WriteLine(count);
}
static void Part2(string[] lines)
{
int total = 0;
foreach (string line in lines)
{
string secondHalf = line.Substring(line.IndexOf("|") + 1);
List<string> numberSegments = secondHalf.Split(' ').ToList();
string lineTotal = string.Empty;
foreach (string numberSegment in numberSegments)
{
// Go through sorted in alphabetical order
string alphabetisedNumberSegment = String.Concat(numberSegment.OrderBy(c => c));
Console.WriteLine(alphabetisedNumberSegment);
if(alphabetisedNumberSegment == String.Concat("acedgfb".OrderBy(c => c)))
{
lineTotal += "8";
}
else if(alphabetisedNumberSegment == String.Concat("cdfbe".OrderBy(c => c)))
{
lineTotal += "5";
}
else if(alphabetisedNumberSegment == String.Concat("gcdfa".OrderBy(c => c)))
{
lineTotal += "2";
}
else if(alphabetisedNumberSegment == String.Concat("fbcad".OrderBy(c => c)))
{
lineTotal += "3";
}
else if(alphabetisedNumberSegment == String.Concat("dab".OrderBy(c => c)))
{
lineTotal += "7";
}
else if(alphabetisedNumberSegment == String.Concat("cefabd".OrderBy(c => c)))
{
lineTotal += "9";
}
else if(alphabetisedNumberSegment == String.Concat("cdfgeb".OrderBy(c => c)))
{
lineTotal += "6";
}
else if(alphabetisedNumberSegment == String.Concat("eafb".OrderBy(c => c)))
{
lineTotal += "4";
}
else if(alphabetisedNumberSegment == String.Concat("cagedb".OrderBy(c => c)))
{
lineTotal += "0";
}
else if(alphabetisedNumberSegment == String.Concat("ab".OrderBy(c => c)))
{
lineTotal += "1";
}
Console.WriteLine(lineTotal);
}
Console.WriteLine(lineTotal);
if (!string.IsNullOrEmpty(lineTotal))
{
total += int.Parse(lineTotal);
}
}
Console.WriteLine(total);
}
static Dictionary<int, string> DetermineMapping(string[] lines)
{
Dictionary<int, string> mapping = new Dictionary<int, string>();
foreach (string line in lines)
{
string secondHalf = line.Substring(line.IndexOf("|") + 1);
List<string> numberSegments = secondHalf.Split(' ').ToList();
foreach (string numberSegment in numberSegments)
{
switch (numberSegment.Length)
{
case 7:
// 8 has only 7 segments/letters
mapping.Add(8, numberSegment);
break;
case 3:
// 7 has only 3 segments/letters
mapping.Add(7, numberSegment);
break;
case 4:
// 4 has only 4 segments/letters
mapping.Add(4, numberSegment);
break;
case 2:
// 1 has only 2 segments/letters
mapping.Add(1, numberSegment);
break;
default:
// handle the non-unique lengths (0,2,3,5,6,9)
break;
}
}
}
return mapping;
}
}
}
+67
View File
@@ -0,0 +1,67 @@
--- Day 8: Seven Segment Search ---
You barely reach the safety of the cave when the whale smashes into the cave mouth, collapsing it. Sensors indicate another exit to this cave at a much greater depth, so you have no choice but to press on.
As your submarine slowly makes its way through the cave system, you notice that the four-digit seven-segment displays in your submarine are malfunctioning; they must have been damaged during the escape. You'll be in a lot of trouble without them, so you'd better figure out what's wrong.
Each digit of a seven-segment display is rendered by turning on or off any of seven segments named a through g:
0: 1: 2: 3: 4:
aaaa .... aaaa aaaa ....
b c . c . c . c b c
b c . c . c . c b c
.... .... dddd dddd dddd
e f . f e . . f . f
e f . f e . . f . f
gggg .... gggg gggg ....
5: 6: 7: 8: 9:
aaaa aaaa aaaa aaaa aaaa
b . b . . c b c b c
b . b . . c b c b c
dddd dddd .... dddd dddd
. f e f . f e f . f
. f e f . f e f . f
gggg gggg .... gggg gggg
So, to render a 1, only segments c and f would be turned on; the rest would be off. To render a 7, only segments a, c, and f would be turned on.
The problem is that the signals which control the segments have been mixed up on each display. The submarine is still trying to display numbers by producing output on signal wires a through g, but those wires are connected to segments randomly. Worse, the wire/segment connections are mixed up separately for each four-digit display! (All of the digits within a display use the same connections, though.)
So, you might know that only signal wires b and g are turned on, but that doesn't mean segments b and g are turned on: the only digit that uses two segments is 1, so it must mean segments c and f are meant to be on. With just that information, you still can't tell which wire (b/g) goes to which segment (c/f). For that, you'll need to collect more information.
For each display, you watch the changing signals for a while, make a note of all ten unique signal patterns you see, and then write down a single four digit output value (your puzzle input). Using the signal patterns, you should be able to work out which pattern corresponds to which digit.
For example, here is what you might see in a single entry in your notes:
acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab |
cdfeb fcadb cdfeb cdbaf
(The entry is wrapped here to two lines so it fits; in your notes, it will all be on a single line.)
Each entry consists of ten unique signal patterns, a | delimiter, and finally the four digit output value. Within an entry, the same wire/segment connections are used (but you don't know what the connections actually are). The unique signal patterns correspond to the ten different ways the submarine tries to render a digit using the current wire/segment connections. Because 7 is the only digit that uses three segments, dab in the above example means that to render a 7, signal lines d, a, and b are on. Because 4 is the only digit that uses four segments, eafb means that to render a 4, signal lines e, a, f, and b are on.
Using this information, you should be able to work out which combination of signal wires corresponds to each of the ten digits. Then, you can decode the four digit output value. Unfortunately, in the above example, all of the digits in the output value (cdfeb fcadb cdfeb cdbaf) use five segments and are more difficult to deduce.
For now, focus on the easy digits. Consider this larger example:
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb |
fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec |
fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef |
cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega |
efabcd cedba gadfec cb
aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga |
gecf egdcabf bgf bfgea
fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf |
gebdcfa ecba ca fadegcb
dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf |
cefg dcbef fcge gbcadfe
bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd |
ed bcgafe cdgba cbgef
egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg |
gbdfcae bgc cg cgb
gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc |
fgae cfgab fg bagce
Because the digits 1, 4, 7, and 8 each use a unique number of segments, you should be able to tell which combinations of signals correspond to those digits. Counting only digits in the output values (the part after | on each line), in the above example, there are 26 instances of digits that use a unique number of segments (highlighted above).
In the output values, how many times do digits 1, 4, 7, or 8 appear?
+49
View File
@@ -0,0 +1,49 @@
--- Part Two ---
Through a little deduction, you should now be able to determine the remaining digits. Consider again the first example above:
acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab |
cdfeb fcadb cdfeb cdbaf
After some careful analysis, the mapping between signal wires and segments only make sense in the following configuration:
dddd
e a
e a
ffff
g b
g b
cccc
So, the unique signal patterns would correspond to the following digits:
acedgfb: 8
cdfbe: 5
gcdfa: 2
fbcad: 3
dab: 7
cefabd: 9
cdfgeb: 6
eafb: 4
cagedb: 0
ab: 1
Then, the four digits of the output value can be decoded:
cdfeb: 5
fcadb: 3
cdfeb: 5
cdbaf: 3
Therefore, the output value for this entry is 5353.
Following this same process for each entry in the second, larger example above, the output value of each entry can be determined:
fdgacbe cefdb cefbgd gcbe: 8394
fcgedb cgb dgebacf gc: 9781
cg cg fdcagb cbg: 1197
efabcd cedba gadfec cb: 9361
gecf egdcabf bgf bfgea: 4873
gebdcfa ecba ca fadegcb: 8418
cefg dcbef fcge gbcadfe: 4548
ed bcgafe cdgba cbgef: 1625
gbdfcae bgc cg cgb: 8717
fgae cfgab fg bagce: 4315
Adding all of the output values in this larger example produces 61229.
For each entry, determine all of the wire/segment connections and decode the four-digit output values. What do you get if you add up all of the output values?
+1
View File
@@ -0,0 +1 @@
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
+21
View File
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_09</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Creek.HelpfulExtensions" Version="1.3.0" />
</ItemGroup>
<ItemGroup>
<None Update="input.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+235
View File
@@ -0,0 +1,235 @@
using Creek.HelpfulExtensions;
namespace Day09
{
class Program
{
public static int arraySizeX;
public static int arraySizeY;
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("input.txt");
//Part1(lines);
Part2(lines);
}
static void Part1(string[] lines)
{
arraySizeX = lines[0].Length;
arraySizeY = lines.Count();
int[,] array = new int[arraySizeX, arraySizeY];
foreach (var (line, index) in lines.WithIndex())
{
for (int i = 0; i < line.Length; i++)
{
array[i,index] = int.Parse(line[i].ToString());
}
}
List<int> lowPoints = new List<int>();
// Check each number in the array
for (int i = 0; i < arraySizeX; i++)
{
for (int j = 0; j < arraySizeY; j++)
{
if (IsLowPoint(array, i, j))
{
lowPoints.Add(array[i,j]);
}
}
}
// Risk level of a low point is 1 plus height
int totalRiskLevel = lowPoints.Sum() + lowPoints.Count();
Console.WriteLine($"Total Risk Level: {totalRiskLevel}");
}
static void Part2(string[] lines)
{
arraySizeX = lines[0].Length;
arraySizeY = lines.Count();
int[,] array = new int[arraySizeX, arraySizeY];
foreach (var (line, index) in lines.WithIndex())
{
for (int i = 0; i < line.Length; i++)
{
array[i, index] = int.Parse(line[i].ToString());
}
}
List<(int x, int y)> lowPointLocations = new List<(int x, int y)>();
// Check each number in the array
for (int i = 0; i < arraySizeX; i++)
{
for (int j = 0; j < arraySizeY; j++)
{
if (IsLowPoint(array, i, j))
{
lowPointLocations.Add((i, j));
}
}
}
// There is a basin for every low point, bounded by 9s and the edge of the array
// Find these basins, along with the count of how many locations are in each basin
List<int> basinLocationCount = new List<int>();
foreach ((int x, int y) location in lowPointLocations)
{
// For each low point, find all the locations within its basin
Console.WriteLine("Starting new basin");
List<(int x, int y)> locationsInBasin = new List<(int x, int y)>();
FindBasinLocations(array, ref locationsInBasin, location);
basinLocationCount.Add(locationsInBasin.Count());
}
Console.WriteLine("==============");
foreach (var item in basinLocationCount)
{
Console.WriteLine(item);
}
List<int> threeHighest = basinLocationCount.OrderByDescending(x => x).Take(3).ToList();
int mult = threeHighest.Aggregate((x, y) => x * y);
Console.WriteLine($"Total Basin Locations: {basinLocationCount.Count()} Multiplying their sizes together: {mult}");
}
static void FindBasinLocations(int[,] array, ref List<(int x, int y)> locationsInBasin, (int x, int y) location)
{
List<(int x, int y)> relativeLocations = new List<(int x, int y)>()
{
//(location.x - 1, location.y - 1),
//(location.x, location.y - 1),
//(location.x + 1, location.y - 1),
//(location.x - 1, location.y),
//(location.x + 1, location.y),
//(location.x - 1, location.y + 1),
//(location.x, location.y + 1),
//(location.x + 1, location.y + 1),
};
// REMEMBER THIS DOESN'T TAKE INTO ACCOUNT DIAGONALS
try
{
//relativeLocations.Add((location.x - 1, location.y - 1));
relativeLocations.Add((location.x, location.y - 1));
//relativeLocations.Add((location.x + 1, location.y - 1));
relativeLocations.Add((location.x - 1, location.y));
relativeLocations.Add((location.x + 1, location.y));
//relativeLocations.Add((location.x - 1, location.y + 1));
relativeLocations.Add((location.x, location.y + 1));
//relativeLocations.Add((location.x + 1, location.y + 1));
}
catch (Exception ex)
{
Console.WriteLine($"{location.x},{location.y} errored");
}
// For every direction, if there's a 9 or no element stop, otherwise, go again from that location, excluding locations we've already considered
foreach ((int x, int y) relativeLocation in relativeLocations)
{
int newX = relativeLocation.x;
int newY = relativeLocation.y;
bool condition1 = IsNotHighPointOrOutOfArray(array, newX, newY);
bool condition2 = condition1 ? array[newX, newY] < 9 : false;
bool condition3 = condition1 ? !locationsInBasin.Contains((newX, newY)) : false;
//Console.WriteLine($"{condition1} - {condition2} - {condition3}");
if (condition1 && condition2 && condition3)
{
locationsInBasin.Add((newX, newY));
Console.WriteLine($"{newX},{newY} added with value {array[newX, newY]}");
FindBasinLocations(array, ref locationsInBasin, relativeLocation);
}
}
}
static bool IsNotHighPointOrOutOfArray(int[,] array, int x, int y)
{
if (IsInArray(x, y) && array[x, y] < 9)
{
return true;
}
else
{
return false;
}
}
static bool IsLowPoint(int[,] array, int x, int y)
{
// top left x-1, y-1
// top middle x, y-1
// top right x+1, y-1
// left x-1, y
// right x+1, y
// bottom left x-1, y+1
// bottom middle x, y+1
// bottom right x+1, y+1
// Compare all EXISTING positions around the current position and if any of them are lowest than the value in the current position return false
int currentPosition = array[x, y];
if (IsInArray(x-1, y-1) && array[x-1, y-1] < currentPosition)
{
return false;
}
else if (IsInArray(x, y - 1) && array[x, y - 1] < currentPosition)
{
return false;
}
else if (IsInArray(x + 1, y - 1) && array[x + 1, y - 1] < currentPosition)
{
return false;
}
else if (IsInArray(x - 1, y) && array[x - 1, y] < currentPosition)
{
return false;
}
else if (IsInArray(x + 1, y) && array[x + 1, y] < currentPosition)
{
return false;
}
else if (IsInArray(x - 1, y + 1) && array[x - 1, y + 1] < currentPosition)
{
return false;
}
else if (IsInArray(x, y + 1) && array[x, y + 1] < currentPosition)
{
return false;
}
else if (IsInArray(x + 1, y + 1) && array[x + 1, y + 1] < currentPosition)
{
return false;
}
else
{
Console.WriteLine($"{x},{y}: {currentPosition}");
return true;
}
}
static bool IsInArray(int x, int y)
{
if (x >= 0 && x < arraySizeX && y >= 0 && y < arraySizeY)
{
return true;
}
else
{
return false;
}
}
}
}
+21
View File
@@ -0,0 +1,21 @@
--- Day 9: Smoke Basin ---
These caves seem to be lava tubes. Parts are even still volcanically active; small hydrothermal vents release smoke into the caves that slowly settles like rain.
If you can model how the smoke flows through the caves, you might be able to avoid it and be that much safer. The submarine generates a heightmap of the floor of the nearby caves for you (your puzzle input).
Smoke flows to the lowest point of the area it's in. For example, consider the following heightmap:
2199943210
3987894921
9856789892
8767896789
9899965678
Each number corresponds to the height of a particular location, where 9 is the highest and 0 is the lowest a location can be.
Your first goal is to find the low points - the locations that are lower than any of its adjacent locations. Most locations have four adjacent locations (up, down, left, and right); locations on the edge or corner of the map have three or two adjacent locations, respectively. (Diagonal locations do not count as adjacent.)
In the above example, there are four low points, all highlighted: two are in the first row (a 1 and a 0), one is in the third row (a 5), and one is in the bottom row (also a 5). All other locations on the heightmap have some lower adjacent location, and so are not low points.
The risk level of a low point is 1 plus its height. In the above example, the risk levels of the low points are 2, 1, 6, and 6. The sum of the risk levels of all low points in the heightmap is therefore 15.
Find all of the low points on your heightmap. What is the sum of the risk levels of all low points on your heightmap?
+38
View File
@@ -0,0 +1,38 @@
--- Part Two ---
Next, you need to find the largest basins so you know what areas are most important to avoid.
A basin is all locations that eventually flow downward to a single low point. Therefore, every low point has a basin, although some basins are very small. Locations of height 9 do not count as being in any basin, and all other locations will always be part of exactly one basin.
The size of a basin is the number of locations within the basin, including the low point. The example above has four basins.
The top-left basin, size 3:
2199943210
3987894921
9856789892
8767896789
9899965678
The top-right basin, size 9:
2199943210
3987894921
9856789892
8767896789
9899965678
The middle basin, size 14:
2199943210
3987894921
9856789892
8767896789
9899965678
The bottom-right basin, size 9:
2199943210
3987894921
9856789892
8767896789
9899965678
Find the three largest basins and multiply their sizes together. In the above example, this is 9 * 14 * 9 = 1134.
What do you get if you multiply together the sizes of the three largest basins?
+100
View File
@@ -0,0 +1,100 @@
4567894301299921298789654345689439843295436789543298765432345678986789756901239998765634567895986555
3458963212989890989678943234678998764989945678932198764321456799215678949892398999854525658934895434
2348954329876799876567899195789469999767896989949019965432567897434569998789987898743212345695679423
1237895498765698765479998989890359878956789999898929876545678996545698987678976987654563456789798912
3456797987854569954398987678921298766545678998777899987766789987656987676569895498765676567899987893
4567989896543498765987876567892987655434567897656798799897894598767899565458789329876787678999876789
5679878789432579879876743458989876542123456996545987678998923459878998433347678910987898789998865678
8798765678921456989865432365678987678012345989439878569899012398989987321234567899998949898987654568
9987654688932368998765421234567898632125499878998767476789323987399876510126789998769434967896543456
2398543567893458999876510195978976543236989656989654345895439876210965432345678989754323456987432345
1987652356954567899985431989899987654549878949878943234976545985431986583556899679943212569898541234
0198621237899778999996569878789698765698765436567890125987689987642398874567976567894323498789210123
9239432348998989998987698765679549878789876323456789239898992398543498765678965456789434999654321234
8998543459987899987898798754678932989899985434567894398789943987659569898789654329899949898765432345
7987674569876789876789987643767891296929876765678965987656894998998979979898763210169898769896543456
6599795678965699965679876321458942965439987878989879898545899899987898965919874323456789656987654578
5459898789654569874589765432349899876598998989894998765434789789876567894301986545678998734598787689
4345979896543498763459896565456789987987989998763219896545697698765456965212397696989654321239898793
3254567965432987654567987886767891299876767899854323987676789569876345894343498989898975434345999892
0123979879521098975678998997878910198965656789967456798789893498985256799454569978797896545656789991
1239899998632129996789989798989992987654547899996567899893912987654345678965698765686789656767899989
4398789876543234989899976659999989998743234598989699989932102398965457789898789654345898787878999878
6987654997654399878999865545898678999654123987678989876545293459878968898769899983236789898989998767
9876563498969989769899854236789567898763234976567878989676989598989879997656999874345899949899989756
9765432349898876658789743145678978999854569865453569998789878987899989789743298765456789234789876545
9897561298767435345697653234567899989967698774312478999898767856789997678932109876567892125678987634
8999990129854321234589754745678999879878987685101387899997656345678954567893212987678943034599299846
7898889298743210125678965678989998767989999543215456999898743237567893478954563499789956745989398767
6787678987654321367889876989999887656799898654323567898765432123456789589765679599899877659878989878
5674569898765432456789987898998786545698798765434678979878741012367998678978798989924989798767878989
4323498789878543567897698967899654323987679878555789567997652323458998789989987678912398987856567899
3212347678989697689976569458789765219886587989676894456989543456767899893499876567893987996543456789
2101234567898798797895435365698954398775456898789932349879656567878954901298775456789896789612345678
3232345678979899896789423234567965699674345679894321298968987678989543212987654345698765678923458989
4563656789765932945678910123679899986545234569965432987857899799898954329898765257789674567934567897
5674767899854321234789543234598798997632123678996949876546978998767899998789954348998543456895688976
6789898998765430123897654345987687889875012399989899985434569987658998875657895767987432388996789765
7895919987654321234998765499876576778964323989878789876323568998899987764546789879876321276989899876
8954323498765434345699878987655485567895439876567678987212567899999876543534995989865410125678999987
9765434679876595456789989987643213458996545985434569874323456789998765432323894399986423234789998998
7976765789987876567994399876543201246789759886323498765434569899879894321012789459876534345689987989
6989876894598987878973234997875212345678998765434999876545679998767987652345678967987649876798765678
5492987923679598989862125987654345456789329876565899987786789987656399543458789978998956987899654568
6321098912395439799654434598765456567893212987876789699898899876543297654567893989879987898998743489
5499999101987325678969547679976787998999543498989896545999932999632198775878932398767898969997632378
6987893245896534567898956789987898949698956569193987659899891098949019896989991987654329459876541267
9876789356789645678987897996598989434567897692012798998789789987898923987899989998763212345998765459
8765678969898756789256789543459876323456789789125679989678679876767994598999878989854301456789876567
5874789998979867894345678932398765614347899899434599876534598765656789679998767678965212367899987678
4343467897767998965456789321459654301256789998765987988323989854345678999987654589654343479999898789
3212989926456999987567895432396543212367899899899876543219876543236799989876543458965494989698769894
4343499212347894398878989693987665323456789789989987695499965432125678978985432367896989896569654923
5454578901456943219989878989998786734569897679878798986989876743234599769876921456999976789696543219
6567689212567899324599967678999897895878944598765659987976987654345678956989890967898765698987654998
7678998343456898935679756567899998976989432129654745698965498765458789545698789899987654567898769897
8789997654597987899798743456789879987896545098743434899876569896567890124987698768894323458999998786
9897898765989876568987654567898765698989652196542123987987678989698921239876567656789214567899989645
9956789879876543456798765678989854349678943987663039876498789878999632345985454347898996789979878434
9745698998767432345679896789876543234567894598754198765339899867996543459876321238957889895659762123
8634567899654321238789997898987654349978965679865299873210998759889654569985432349546778954349843234
6525898998765432345893298967898795998899876789876789954321989645678965678996543489435568893234956785
5436789129887643458932139456789989876789987895987899977439876434599876789987687678923456789125987996
6545679012998786567891012345899876765898998934598999876567965323689987895398798789212345699934598987
9876789199129987698972357896789995854567899325679999987679873212347898943219999892103479789895679298
3987899988997598789765456789899984323456789212389989898989932101236789992103498943212567998789792149
2198979876789459899896987999939876434598994323459878799999876512345699983212987654323456789678989234
3239567965679345999989898998929987545989987654598765634789965423457999874323498767654567898567878945
4999459854567956789878789987898797659876998765965834323679876567568998765454999878765678997434569896
9878398765699897898765679976545698998965789899894321014567987698989549878969891989889789986545789789
9765129876986789989874798765434569987654891998789543223478998789794323989998710195999897987696897678
8654234989875679876743459983125689998785992989678965354567899895699456799987623234599976798789977567
9766545698764568995432369894012378999876789878567896765678932923988998899876544395989897899898765456
9878656799853656789321298765623567894987898765456989896789671019977789921987895989878789978987632345
9989867987942345693210129898794678923498949987345678987896532198866678930298999876765678954596543456
9896979876543456789521345999898789213999239876239789498986545987755567891979998765874567893987656567
8755699987654567897432567899989892109878998765458991349997679876643456789767987654323456912998767778
5444598798767678996543456789876989298767879986767890145989998965432387893458998765534567899889898989
9323497679989789987894568998765678987656767897878921239876897896521298932347899876765678965678999496
8939986545698993498989979349654349876545856998989432398965986789430989549456910997876889954567894325
7898965434577892109879893298743212965432147899996545987654875678949878998967891298989997892349993214
6587894323456943998765789349892109876543236789987659876543534567898767897898932999292356793498989323
5456789434567899899854578998765412987656745893299767985452123679987656786789999899101236789987879434
4345678946678998789943469549894329898767856794999879876321014989699542345999987678912345699996768965
3235789987889997678912568932985498769878967989899989965432127894598431259899976567893456789865657896
2124899998999876589893467899876987654989879876789999876543236893987640198788893478999567998754346789
4235998989998765498794878945987896543296999765678998987664345992987651987677789567898979899893235678
5345987878999654346689989234598987654345989654567897898785456789298769876545678978957898789762124568
5459876567898953234579890123499998785459876543678965439976567892129898987634389899545987689654335679
6798765456587892145656789294989899896567985432349876521989878921019987896521256789434596578965445799
7999874343456921012345999989876789987679876545678965439997989532198756965432345694323987459878556789
9899983212457892123456789876765695498789987658789997698976596545349867896545696789109876367989769899
9789874343468943234567899985634789219898998969899989987897697655459878987856789895414995499999878998
8676965656578998745678999894323478901987899878999879876789798798767989498979899954323986989899989987
6565698767889109656789698765434567899876789989898765765678999899878995349989998765456899876789899886
5454569878999998767895549898745679978987897696789654344567899945989965210995439876787898965678789765
4323456989769899878934135987656789567898976545698743213456789434597894329874321987898987654565678954
5434567893656789989321014598967993456799895434997654302345678923456789459765210298959996543534567893
6547978932345678995432323459978942367898754329876543212456789014567896598654354349543985432123489932
7656889321256789876543434567899431234789843212987655433469894323478987698765565458932976543234567891
8798995432367899989656657678976532345678932101298766545678965435689998799876676567891098764546678910
+17
View File
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_10</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Update="input.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+193
View File
@@ -0,0 +1,193 @@
using System.Numerics;
using System.Text;
namespace Day10
{
class Program
{
static List<char> openingCharacters = new List<char>() { '(', '[', '{', '<' };
static List<char> closingCharacters = new List<char>() { ')', ']', '}', '>' };
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("input.txt");
//Part1(lines);
Part2(lines);
}
static void Part1(string[] lines)
{
List<string> uncorruptedLines = new List<string>();
int syntaxErrorScore = 0;
foreach (string line in lines)
{
if (!IsLineCorrupted(line, ref syntaxErrorScore))
{
uncorruptedLines.Add(line);
}
}
Console.WriteLine($"Syntax error score: {syntaxErrorScore}");
}
static void Part2(string[] lines)
{
List<string> uncorruptedLines = new List<string>();
int syntaxErrorScore = 0;
foreach (string line in lines)
{
if (!IsLineCorrupted(line, ref syntaxErrorScore))
{
uncorruptedLines.Add(line);
}
}
// Now we just have the incomplete lines, work out how to complete them
List<BigInteger> autoCompleteLineScores = new List<BigInteger>();
foreach (string line in uncorruptedLines)
{
BigInteger totalLineScore = 0;
string characters = GetCharactersToCompleteLine(line);
// Now calculate the score for the line
foreach (char character in characters)
{
totalLineScore = totalLineScore * 5;
switch (character)
{
case ')':
totalLineScore += 1;
break;
case ']':
totalLineScore += 2;
break;
case '}':
totalLineScore += 3;
break;
case '>':
totalLineScore += 4;
break;
default:
break;
}
}
autoCompleteLineScores.Add(totalLineScore);
Console.WriteLine($"{characters} - {totalLineScore} total points.");
}
// the winner is found by sorting all of the scores and then taking the middle score. (There will always be an odd number of scores to consider.)
autoCompleteLineScores.Sort();
BigInteger middleScore = autoCompleteLineScores.Skip(autoCompleteLineScores.Count / 2).Take(1).First();
Console.WriteLine($"Middle score: {middleScore}");
}
static bool IsLineCorrupted(string line, ref int syntaxErrorScore)
{
Stack<char> stackOfExpectedClosingCharacters = new Stack<char>();
for (int i = 0; i < line.Length; i++)
{
if (openingCharacters.Contains(line[i]))
{
// If it's an opening character then add the expected closing character to the stack
stackOfExpectedClosingCharacters.Push(GetExpectedClosingCharacter(line[i]));
}
else if (closingCharacters.Contains(line[i]))
{
// If it's a closing character, then check if it's the one we're expecting
// Make sure there's items in the stack so we don't get an InvalidOperationException
if (stackOfExpectedClosingCharacters.Count > 0)
{
char expectedClosingCharacter = stackOfExpectedClosingCharacters.Pop();
if (line[i] != expectedClosingCharacter)
{
// It's not the one we're expecting so the line is corrupted
Console.WriteLine($"Expected {expectedClosingCharacter}, but found {line[i]} instead.");
// Update the syntax error score
switch (line[i])
{
case ')':
syntaxErrorScore += 3;
break;
case ']':
syntaxErrorScore += 57;
break;
case '}':
syntaxErrorScore += 1197;
break;
case '>':
syntaxErrorScore += 25137;
break;
default:
break;
}
// Report the corrupted line
return true;
}
// If it is the one we're expecting we can safely carry on with the line
}
}
}
// Having reached the end of the line with no wrong closing characters the line cannot be corrupted
return false;
}
static string GetCharactersToCompleteLine(string line)
{
Stack<char> stackOfExpectedClosingCharacters = new Stack<char>();
for (int i = 0; i < line.Length; i++)
{
if (openingCharacters.Contains(line[i]))
{
// If it's an opening character then add the expected closing character to the stack
stackOfExpectedClosingCharacters.Push(GetExpectedClosingCharacter(line[i]));
}
else if (closingCharacters.Contains(line[i]))
{
// If it's a closing character, then it must be the one we're expecting as we've already got rid of the corrupt lines
// Make sure there's items in the stack so we don't get an InvalidOperationException, then pop it off the stack
if (stackOfExpectedClosingCharacters.Count > 0)
{
stackOfExpectedClosingCharacters.Pop();
}
}
}
// The stack should now contain all the closing characters needed, in order, so get them into a string
StringBuilder charactersToCompleteLine = new StringBuilder();
while (stackOfExpectedClosingCharacters.Count > 0)
{
char character = stackOfExpectedClosingCharacters.Pop();
charactersToCompleteLine.Append(character);
}
Console.WriteLine($"Complete by adding {charactersToCompleteLine.ToString()}");
return charactersToCompleteLine.ToString();
}
static char GetExpectedClosingCharacter(char openingCharacter)
{
int index = openingCharacters.FindIndex(x => x == openingCharacter);
return closingCharacters[index];
}
}
}
+50
View File
@@ -0,0 +1,50 @@
--- Day 10: Syntax Scoring ---
You ask the submarine to determine the best route out of the deep-sea cave, but it only replies:
Syntax error in navigation subsystem on line: all of them
All of them?! The damage is worse than you thought. You bring up a copy of the navigation subsystem (your puzzle input).
The navigation subsystem syntax is made of several lines containing chunks. There are one or more chunks on each line, and chunks contain zero or more other chunks. Adjacent chunks are not separated by any delimiter; if one chunk stops, the next chunk (if any) can immediately start. Every chunk must open and close with one of four legal pairs of matching characters:
If a chunk opens with (, it must close with ).
If a chunk opens with [, it must close with ].
If a chunk opens with {, it must close with }.
If a chunk opens with <, it must close with >.
So, () is a legal chunk that contains no other chunks, as is []. More complex but valid chunks include ([]), {()()()}, <([{}])>, [<>({}){}[([])<>]], and even (((((((((()))))))))).
Some lines are incomplete, but others are corrupted. Find and discard the corrupted lines first.
A corrupted line is one where a chunk closes with the wrong character - that is, where the characters it opens and closes with do not form one of the four legal pairs listed above.
Examples of corrupted chunks include (], {()()()>, (((()))}, and <([]){()}[{}]). Such a chunk can appear anywhere within a line, and its presence causes the whole line to be considered corrupted.
For example, consider the following navigation subsystem:
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
Some of the lines aren't corrupted, just incomplete; you can ignore these lines for now. The remaining five lines are corrupted:
{([(<{}[<>[]}>{[]{[(<()> - Expected ], but found } instead.
[[<[([]))<([[{}[[()]]] - Expected ], but found ) instead.
[{[{({}]{}}([{[{{{}}([] - Expected ), but found ] instead.
[<(<(<(<{}))><([]([]() - Expected >, but found ) instead.
<{([([[(<>()){}]>(<<{{ - Expected ], but found > instead.
Stop at the first incorrect closing character on each corrupted line.
Did you know that syntax checkers actually have contests to see who can get the high score for syntax errors in a file? It's true! To calculate the syntax error score for a line, take the first illegal character on the line and look it up in the following table:
): 3 points.
]: 57 points.
}: 1197 points.
>: 25137 points.
In the above example, an illegal ) was found twice (2*3 = 6 points), an illegal ] was found once (57 points), an illegal } was found once (1197 points), and an illegal > was found once (25137 points). So, the total syntax error score for this file is 6+57+1197+25137 = 26397 points!
Find the first illegal character in each corrupted line of the navigation subsystem. What is the total syntax error score for those errors?
+37
View File
@@ -0,0 +1,37 @@
--- Part Two ---
Now, discard the corrupted lines. The remaining lines are incomplete.
Incomplete lines don't have any incorrect characters - instead, they're missing some closing characters at the end of the line. To repair the navigation subsystem, you just need to figure out the sequence of closing characters that complete all open chunks in the line.
You can only use closing characters (), ], }, or >), and you must add them in the correct order so that only legal pairs are formed and all chunks end up closed.
In the example above, there are five incomplete lines:
[({(<(())[]>[[{[]{<()<>> - Complete by adding }}]])})].
[(()[<>])]({[<{<<[]>>( - Complete by adding )}>]}).
(((({<>}<{<{<>}{[]{[]{} - Complete by adding }}>}>)))).
{<[[]]>}<{[{[{[]{()[[[] - Complete by adding ]]}}]}]}>.
<{([{{}}[<[[[<>{}]]]>[]] - Complete by adding ])}>.
Did you know that autocomplete tools also have contests? It's true! The score is determined by considering the completion string character-by-character. Start with a total score of 0. Then, for each character, multiply the total score by 5 and then increase the total score by the point value given for the character in the following table:
): 1 point.
]: 2 points.
}: 3 points.
>: 4 points.
So, the last completion string above - ])}> - would be scored as follows:
Start with a total score of 0.
Multiply the total score by 5 to get 0, then add the value of ] (2) to get a new total score of 2.
Multiply the total score by 5 to get 10, then add the value of ) (1) to get a new total score of 11.
Multiply the total score by 5 to get 55, then add the value of } (3) to get a new total score of 58.
Multiply the total score by 5 to get 290, then add the value of > (4) to get a new total score of 294.
The five lines' completion strings have total scores as follows:
}}]])})] - 288957 total points.
)}>]}) - 5566 total points.
}}>}>)))) - 1480781 total points.
]]}}]}]}> - 995444 total points.
])}> - 294 total points.
Autocomplete tools are an odd bunch: the winner is found by sorting all of the scores and then taking the middle score. (There will always be an odd number of scores to consider.) In this example, the middle score is 288957 because there are the same number of scores smaller and larger than it.
Find the completion string for each incomplete line, score the completion strings, and sort the scores. What is the middle score?
+106
View File
@@ -0,0 +1,106 @@
<{({(([[<<([[([][])]{([]<>)([]<>)}]<[[[]{}]{()[]}]>)(<<[[]()][[]()]><[<>[]]<[]()>>>{<<<><>><<>[]>>[<[]<>><
{<[<((<<({([{{{}[]}<<><>>}]<<{[]<>}([]<>)>>)<{(<[]()>{()()})<(()<>){(){}}>}([(()[])<[]>][[[][]]{{}}])
<{[[{<[[{(<[[({}())[()()]]([<>()](<>()))][(([]<>)([][]))(({}{})[<><>])]><<<[[]<>][{}[]]>([<>{}
<[[<[([({[{<[({}<>)([]<>)](<<>[]>([]()))><[<[]{}>[<><>]]>}>[{[[({}<>)<()<>>][{{}[]}(()())]][[(<>{}){<>{
[((<{((([[<<<[<><>]{{}[]}>>(([<><>]<()[]>)<(()<>)>)>([[[{}{}][[][]>]<{<>()}[<>{}]>])]]<{[<[
([{([[[{(<({<<[]<>>[()()]>{(()[])}})<(<<{}()>(<>>>([(){}]))<[(<>{}){()}]((()[]){()()})>>>)}{
<{{[(<[<<[[{<(()[])>[[{}()]{{}[]}]}[[(<>())[()()]]{<{}{}>}]](<{[<><>]{{}{}}}<({}[])[<><>]>><{[{}<>](<><>)
{({<[<([[(({({<>()}{{}{}})})<<<((){})[[]()]><{{}()}[[][]]>>{(<{}{}>{{}()})}>)<<{<[{}[]][{}{}]>([[][]]{
{[(((((<{[({<{()[]}(()())>{<(){}>{{}()}}}(<[<>()]{[]()}>(<()()>{{}<>})))[<[[{}{}](<>()>]({[]<>
(([((<{<[((<{{<><>}{[]{}}}><<<<>>[{}]>([[]{}]<<>[]>)>)[[{<{}>{()()}}[[{}[]](()()>]](<<<>{}>[[]
{<([[{<{([[<([[]<>]({}{})){{{}()}({}[])}>](<(<()()><()[]>)<<[]<>>([]{})>>)]){[{<<[()[]]<<>{}>><({
<{[[([<<<(<{{(()<>)(()())}([{}<>]((){}))}>)>({({{{()<>}({}<>)}<[[]<>]{<>[]}>})(({<(){}>[<>[]]}<([]{})<[]{}>>)
(<{<{[[({(<[((<>[]){{}})<(<><>)<[]{}>>]((<<>[]><[]()>)<<{}{}>{(){}}>)>(<[[[]<>]]{{<>{}}{[]()}}>(<{
{(({{[[{<[((<<()<>>[{}{}]>((()<>){[]()})){{(<>{})[<>[]]}<<<><>>>}){{({<>{}}([]()))[{<><>}{[]
(([<(([({{<{[{()<>}<{}[]>]}{[[()()][()<>]}[{<>{}}({}{})]}>((<<<>{}>[<>()]>{{[]<>}({}{})}){[<{
[[{{(<<[[[[<<<<>{}>({}())>[([]<>)(()())]>]<<<{<>()}>[<<>[]>[()()]]>[([[]()]<[][]))<[<>{}]{{}<>
{[{(((([<[{([(()()){()()}][<(){}>[{}<>)])[(<{}<>>{<>()})({{}<>}[()[]])]}(<({[]<>}<()[]>)({[]<>
<<([(([{<{<<<[{}[]]((){})>((<>[])(()<>))>{{{<>()}{[]}}{([][])}}>[<{{<>[]}<<>>}({[]<>})>]]({({{<><>
[{((<{<[[<[{[{{}<>}]{[{}][<>[]]}}[<([]())<()[]>>((<>){[]{}})]]<{(<()<>><{}<>]){[[]<>]({}{})}}({<{}[]>{{}
<[<{(<[[<(((<({}[])><(<><>)(<>())]){{{()()}(<>())}<[{}()]>})[([[<>[]]{{}[]}]{{{}()}<{}[]>})[[(()<>){<>
[([{{[<([{[([[()<>]])([[<>][()[]]][[<>[]]<<>[]>])]}{([<<{}()>({})>(<[]()>(<><>))]<<{{}<>}{<>}><(<>
<<[[([([(<(<<[{}[]]<()[]]><{[]{}}[<>()]>>)>[<<({[][]}<<><>>)[<{}{}>{()<>}]><({<>{}}([]))((
<({<{(<[({([[{()}(<><>)](<[][]>[{}{}])](([[]<>]<<>{}>))){({<<>{}>[[]{}]}<([][])>)<<(<><>)<[]<>>}>}}((([[()<
{([<(<[(({[({[(){}]<<>{}>}[[{}{}][{}[]]])]{({[()<>]{()[]}}(<[][]>[()[]])){{{[]{}}(<>[])}[<(){}>(
<[<[<{[{<[{[<<{}<>>(<>)>]{<({}{}){(){}}>((<>{})[{}<>])}}[<[[<><>]{{}<>}]{<()()>}>{<<[]()>(()())>{{{}<
(({[[<<[({[{{<()()>}}{<[<>()]>}][(<{[][]}>{[{}()]{[]<>}})<{{<>{}}(()[])}{{[]()}<<>[]>}>]})
<((<([[({(<{[[(){}]<[][]>]}>({<[()<>](()[])>(([]<>)([]<>))}<{[[]<>]{(){}}}(<()<>>([][]])>))}<{[<[({}
{({{{[[{{[{(<<(){}>[{}{}]>((()<>)[<>{}]))[<<{}[]><[]>>[{{}{}}(<>[])]]}[(<<(){}>({}{}))((<>{})([]<>)))
[[(({[{(<({[{<[]()>{()[]}}<(<>())<()()>>]<(({}[]){{}<>])((()<>){{}[]})>}([[({}{})[<>()]][{<><>}]]{([[
[[{<[([<[((<([[]{}][{}<>])([{}<>])>[([()<>]{{}{}}){{[]()}}])<({{[]()}[[]()]))>)([<<<<>{}><{}()>><(<>
<<({{{<{[<{<{<[]<>>[[]{}]}[<[]()>{[]{}}]>[[[(){}][<><>]]{(<>[]}({}{})}]}><[[({{}[]}{[]()}){(<>())[()<
{{(({[[[{<[<(([]())([]{}))([{}{}](()[])}>]>}([<{[[[]()][(){}]]<{<>[]}>}({<()<>><[]<>>})>((([()
(<(({{(([(({{<{}[]>({}())}([<>[]][{}()])}((<[][]>{()<>}){[[]<>]<{}{}>}))<({{[]<>}([][])}{<[]{}>{<>[]}})
((([<([([{{{<<<>{}><{}[]>>[[<>[]][{}[]]]}}(([<<>{}>[()[]]][{{}{}}])(<[()()][<><>]>{{<>[]}})}}]<{[[<
{{(<[<[<[<<[[(<>[])]({<><>}[()()])]>>]>[{{[[{(<>[])([][])}{[[][]]([]())}]>[[[<{}{}>({}())]<{<>
<[{[[([[{[(<[<{}{}>{(){}}][{[]<>}<()[]]]>(([()<>][[][]]){[<>{}](()[])}))[[<<{}>[<>{}]>[({}{})({}{})]]<([[]{}
({<<<{<({{{{{[()()]({}())}[[[]{}][<><>])}({<()()><[]()>}({<>()}))}{(((<>()){()()}){<(){}><()[]>})(([{}()]
([<({[{({(<<{[{}()]}{{{}[]}((){})}>>)<<{[((){})[()]]}<<{[]<>}<<>()>>([<>()][[]<>])>>{<<[<>[]]<[]<>>)<{<
(<[<<(<[[[[{{({}<>)[{}{}]}<[[]{}]([]<>)>}][<[<<>{}>{[]}][[[]{}](<>())]><<[<>()][(){}]><{[]
(({[[(([<(([{({}[])[<>{}]}{(<>[])({}{})})<<<{}[]>({}())>[({}<>)<{}()>]>)[<<[[][]]((){})><{{}(
{[((<([<[{[{<[<><>][()()]><{<>{}}>}[{<[][]>[()<>]}<(<>())<()<>>>]]<<<(<>())<()[]>>>[{{{}[]}}[[{}()]((){
{{<{({{({[<((({}{}){<>[]}){<{}()>{<>[]}})>(<{<<>{}><[]<>>}>[[{[]<>>{<><>}]{((){})<(){}>}])]}(<{[{{<><>}{[
(({<[[{[(<(((({}{}){()<>}))<{{[]{}}{{}{}}}<[{}<>][(){}]>>)>[{{(<<><>>([]{}))[((){})<{}[]>]}}(([[<>()]{<>()}]
[<([[[<[<{<{<{[]{}}{[]{}}>[([]())<<>[]>]}({{[]{}}<[]()>}<({}())(<>{})>)>}[({[[{}[]][{}<>]]})]>]><[
<{[<<[[<{[[{<<{}[]>[<><>]>}({[[]{}]<{}()>}((()[])))]{[<{()}[[]{}]>]{(({}[])<{}()>)<(<>())[()<>]
[[([[{[[(([{[[<>()]{<>()}]({(){}}({}{}))}[<[<><>]([]())>(<[]()><{}[]>)]]{(<<<><>>[[]{}]>(<[][]>((){}))
{(<<[[{[{{(<<<{}[]>(<>[])>({[]{}}([]{}))>[{<<>()>[[]<>]]([{}[]])])}[[{(<<><>>[()()])<<<><>>>}([<<>
([((<(<[(<{((<{}{}>{<><>})){{(()[])[{}[]]}}}{[[[(){}][<><>]]]({<()<>>{{}[]}}<[()()]{()[]}>)}>[<{(<{}
[(<[([[({({<[{<>()}([]<>)][(<><>)<()[]>]>})[{([(())({}[])][{[]<>}<()<>>])}({<[{}{}](()())><({}())[<>[]
([(<<[<{<{((<(<>[])({}<>)>{{()()}<<>{}>}))<{[[()[]][()[]]][({}[])<{}()>]}{<({})><{[][]}{{}<>}>}>}<<<({(){}}
[(<{(([({<{{(<[]<>>({}()))}}[<[[{}[]][[]]]>[({[]<>}(<>{}))]]>})]<([(<([[()()][[][]]]<((){}
((({([(<<{{<<({}())(())>([<>()]<()()>)>}}<[(<{{}[]}<()<>>><({}{}){(){}}>)][(({()<>}([]()))([()]))({{{}()}
{<(({[<([{[({([][])[[]{}]}<({}<>)<<>()>>)<<{<>()}{[]<>}>{{{}}{[]()}}>]}])<<{<(([[]{}]<<>[]>)){<<[]<>>><<()[
[{<(<<<((<<<{[()<>]{[]<>}}>[[<{}{}>[()[]]]<(<><>)[()[]]>]>{[[[[]()][<>[]]]]({(<>}{[]{}}})}>){({
<<[((<<[{{[(<[<>()]><{{}[]}{<>{}}>){[(()[])([]())][[(){}][{}[]]]}]([<[[][]]{(){}}><<{}{}>{<>{}}>][[
{<<{<<{<({[[([<>{}])[{[]<>}{{}[]}]][[<()<>>[<>{}]]]]<([{[]()}({}{})]({[]()}{<>()})){[({}<>)[[]{}
{<<[{((([<([[<[]()><<><>>][{()<>}<[][]>]]{<[{}[]][()[]]>[{<>{}>{[]}]}){[([[]{}]<()[]>)[[<>()][{}[]]
({{{{<([[((({{{}{}}<()[]>}{<()<>>{{}<>}})(<({}{})>({<>{}}[[]()]))){(<<<><>><()[]>>[{()()}{[]<>}
({<{[[{({{[<[{[][]}<[][]>]{(<><>)}>([[<>{}][<>{}]]({[]{}}<<>[]>))]}{[({[[]]{()[]}}{(<>{})[()()]})(<{(
[{<<<[(<(<{((([]{}))[{<>()}[()[]]]){{<{}{}>}[<[]<>>{<>{}}]}}<(<[<>[]][()()]>)<([{}()]{{}[]})
{{(([[([((<([[<><>]])>({[{()<>}<[]{}>]}<{[()()]<{}>}(<{}<>>({}{}))>))[{{([()()]<{}<>>){(<>{})(
([(<{[[{<{{<{([]())(<>[])}{{[]<>}{()<>}}>{{{()}}[<[]{}><{}<>>]}}<{[{()()}]{{<>[]}[<><>]}}<<{<>(
([[{[{[{<<(<{<{}{}>{[]}}{[{}{}]{()[]}}>[{({}[])}<[()[]]>])>>[(<<({<>{}}{[]{}})>>(<[([]()){()<>}]((()())([]
(({<({<([(({<<<>()>([]())>{<()[]>{[]<>}}}(<{{}<>}[()()]>({{}<>}[{}()]))))]){{<[{[(<>[]){()
([[(<{[[{<[<(<[]()>[{}[]]){[<><>]{<>[]}}>{{([]()){[]{}}}<((){})([]<>)>}]<<<{{}[]}[()]>(<{}><[][]>)>>>}
{{(<[{[([<<<[<{}<>>(<>{})]<({}[])[<>[]]>>({<{}{}><[]{}>}<<[]><(){}>>)>>(((({()()}[[]{}]))<[{[]<>)<[]()>]
(({{<<[{([[({[[]{}]{()<>}}[(<><>)[()()]])[<[<>[]]><([]{})[[][]]>]](<((<><>)<<>()>)[([][])((){})]>[(
((<<([[<{[{({<(){}><[][]>}{(()[])({}[])})({[{}()]({}{})}(<(){}>(<><>)))}{{[{()<>}<{}{}>][{[]{}}(()
<{(((([<[((({{{}<>}[[]<>]}<[{}<>]>)[<({}{})>{{[]()}<{}()>}])<([<<>>(<><>)]((()())(<>{})))>){(({(
<{{<<{{{[({{[<()[]>(()[])]}<<[[]<>][[]]>>}[<[({})<<>[]>][[[]]([][])]>])]}}(<({[[<[(){}]>{<[]{}>}]{(({
[([[(({([{{({{()}[{}<>]}{({}<>){{}()}}]}}{[<<({}())<(){}>>[{()[]}([]{})]>]{<<{{}()}(<>[])>{[(
[{[{[([<<((<<{()<>}<<>()>>[{[]{}}{{}[]}]>[[{[][]}{{}}]])(([((){})(()())]{[(){}]{()}})))}{(<<<<<><>>({}[]
<[{({[({[({{(<[]()>{{}<>}){{{}<>}[(){}]}}(([{}()]<[][]>)[[<>]({}{})])}<<[(<>)({})]<<()[]><
[((([<(({<<({{{}()}({}<>)}({()[]}[{}{}]))>{[{(<>[])}{(<>[])<{}[]>}]{<[<><>][()[]]>}}>({<{<<>()><<><>>}([{}[]]
{({((<<([((<[[()[]]{[][]}]<{(){}}{<>{}}>>({[(){}][<>]})))(<(({<>[]}<(){}>)(<()[]><{}()>))>)]){
<{<[<(<{<[({{{{}<>}<<>{}>}{[[]()][{}{}]}}[({<><>}{<>{}})[[{}()]{[]()}]])({{<[])(<>[])}})](<<[[<><>]](<{}{}>
[([[[{[((<<(<<()()>>)><<{([]()){<>{}}}<{[]{}}<()()>>>[(<<><>>[()[]]){((){})([]{})}]>>({[<[<><>]{<><
<{{({{{[<{[{{{()<>}[<><>]}[(()[]){[]{}}]}(<{{}[]}[<>[]]><{{}{}}<{}[]>>)]{(({(){}}<<>{}>)[<<><>>[{}
[[([[{[({[{[({{}[]}{()[]})[<()()>{{}{}}]][(([]<>)<[][]>)[<{}{}><{}()>]]}][<([([][]){()()}][[{}{}]{()<
{(<<(((<((((<{()<>}<<>[]>)[<[][]>[{}()]]){[[[]<>]<(){}>][<()<>>{{}<>}]})))<[{{[{{}{}}<[]<>>]}}(
{[(<{[<{{({[{[<><>](<>{})}{({}[])(<>{})}]}({<({}[])<[]<>>>(({}[]))}[<<()><<>>}[{()[]}{[][]}]])){[({<<>()>(
<([{[(<(<<([((()())<{}{}>)]<{(<>())(<>()]}{[()<>](<>())}>)<[[<[][]>]{{()}<<><>>}](({()()}[[
<[<[<{{{[{((<(()()){{}<>)><[[]()](()<>)>))({[[<>{}]{{}()}]({()<>}(()[]))})}]}([{((({{}()}[()<
[{([({[<(<{[{[<>[]][<>()]}([[]{}](()()))){{[()()]<(){}>}({()[]}<[]()>)}}<{[(<>[]){()<>}][[()<>]{()[]}]}{<(<>
{((<(<({{([{[([]<>){[]<>}](<[]<>>[[]<>])}{{<[][]><()[]>}({()<>}<<>{}>)}]<[<[<>()]([]{})><{{}<>}<{}<>>>][(
{<<([<(<{[[{{{<>[]}[[]<>]}{[{}[]]]}{<[(){}]>{[{}()]{[]<>}}}](<{[[]<>]{<>[]}}<<()<>>[[]()]>>)]<[{{<{}>[{}]}<(
[[{{{<{[{({<<<[]{}>[()<>]><[[]<>]([]<>)>><{<<>()>[<>{}]}>}((<[{}{}]{[]}]{<[]<>>{<>{}}})[([<>(
[[{<<{{[(([[[{()[]}][[()[]]<[]>]]({{{}}})][({([][])[{}{}]}<[(){}]<()[]>>){<{[]{}}[(){}]><{{}{}}<<>()>]}]))<<
[(({[<<{<({<([<><>])[{<>()>{{}[]}]>((<()<>><{}<>>)[{[][]}([]{})])})<{{([[]<>]<{}<>>)([()[]]{()()}
[([(({(<[<[<((<>{})[[]<>]){[<><>]({}[]>}>]>]>)}[(({(<<[{(){}}[()[]]]>[<(<>{}){{}{}}>[[()<>][()]]]>)
{<{{<({<{((<{({})<<>{}>}((()){()<>})>))}((<{((()[]){{}[]})[<<>>[[]<>]]}(([<>](()<>)))><{{{<>()}((){}}}((
<[<{<((({{[<{{[][]}}<([]<>)(<>{})>>]}[(([{()()}{<>()}])[<[()[]][()[]]>]){<<[<>()](<>{})>{{(){}}(<>
(([{([{[<(<(((()<>))[(())(<>{})])([[{}<>]{{}[]}][{<><>}[{}{}]])>[(([()[]]<[][]>)[{{}[]}(()[])])(([{}{}]
{<(<<{<[{<{<<<<>[]>[[]<>]){[[]()][<><>]}>({(<><>)(()<>)})}>[<([{{}{}}<[]<>>])({{[]<>}({}[])})>]}{<<[(
<{([({{{<{[{(([]())<<><>>)<[()()]((){})>}]}(<{(<(){}>(<>()))}([[()[]][(){}]](<<>{}>[{}()])}>)>([{<(
((([{<<[{{[(<<[]<>>(<>())>{({}{})<{}[]>})[[<()()>[<>[]]][<{}[]>(()())]]]}}]>>)]{{{{[[{[[[([]<>){
({(<{{({[[{<<(()[])[()]>[{<><>}{<>[]}]>{<{<><>}{()[]}>{[{}()]{[][]}}}}{<<{[]<>}(<><>)>{{[]{}}[
(<[{{(([<{{(<[<>()]((){})>{<{}[]>({}())})}}>][<[{{([{}[]])<([]<>)<<>{}>>}}{<({[][]}(()()))(<<>()>{
(<<{{{((<{({<<{}()><{}{}>><<()[]>[<>[]]>>(<[(){}]([]<>)>[({}<>)]))(({{[]<>}<()<>>}[<()[]>(()[])]){<[
<[(((<({([({{[[]()]{[]()}}([{}()]<[]<>>)}[[<()[]>{{}{}}]([<>]<<>()>)]){[((()<>){<>[]}){[{}[]){[
(({[[({{{[{{({(){}}{{}[]})<({}[])([]<>)>}[[(<>{})]<([]()){{}()}>]}[{<{[]<>}<()()>>([{}<>]<{
<[({{[<[{({[({[]<>}{{}[]})[{[][]}{[][]}]][[<{}[]>{[]()}]([()[]]({}<>))]}{<{[{}<>]<[]()>}<<[]()>[<>{}]>><((
[{[{<{{[<<[[<<{}<>>>][{{{}[]}({}())}]]([{<<><>>({}{})}{{[]<>}}]{{{[]()}([]<>)}})><({{<[][]>}}){<{{()><()>}>[<
{{({([<({(<[({{}{}}<[]{}>)]>[(((<>()){<>()]))[<({}[])(<>{})>{<<><>>{[]()}}]]){{[<(()[])<()<>>>(<()<>>)]([<{}
[({[<(<<[{<({<{}()>{{}()}})({({})<()()>}[{[]<>}[{}{}]})><[(({}{}))(((){})[[][]])]>}<{([<[]<>>]<[{}[]]((
[<{{{<<(<[[{<([][]){<>}>}{<[[]]{[]{}}><{<>{}}>}]<<{([]())[<>[]]}><(([]{}){[]<>})[(<>())({}<>}]>>](
+17
View File
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_11</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Update="input.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+175
View File
@@ -0,0 +1,175 @@
namespace Day11
{
class Program
{
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("input.txt");
Part1(lines);
//Part2(lines);
}
static void Part1(string[] lines)
{
int[,] octopusses = new int[10, 10];
// Load initial values
for (int i = 0; i < lines.Length; i++)
{
for (int k = 0; k < lines[i].Length; k++)
{
octopusses[i, k] = int.Parse(lines[i][k].ToString());
}
}
Console.WriteLine("Begin");
int totalFlashes = 0;
// How many total flashes are there after 100 steps?
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"Start {i}");
PerformStep(ref octopusses, ref totalFlashes);
Console.WriteLine($"End {i}");
}
Console.WriteLine($"There were {totalFlashes} total flashes after 100 steps.");
}
static void PerformStep(ref int[,] octopusses, ref int totalFlashes)
{
// First, the energy level of each octopus increases by 1.
for (int i = 0; i < 10; i++)
{
for (int k = 0; k < 10; k++)
{
octopusses[i, k] += 1;
}
}
bool[,] octopussFlashedDuringThisStep = new bool[10, 10];
// Then, any octopus with an energy level greater than 9 flashes.
// This increases the energy level of all adjacent octopuses by 1, including octopuses that
// are diagonally adjacent. If this causes an octopus to have an energy level greater than 9,
// it also flashes.This process continues as long as new octopuses keep having their energy
// level increased beyond 9. (An octopus can only flash at most once per step.)
bool stillFlashing = true;
while (stillFlashing)
{
// Loop through all
for (int i = 0; i < 10; i++)
{
for (int k = 0; k < 10; k++)
{
// mark any with a 9 as having flashed
if (octopusses[i, k] == 9)
{
if (!octopussFlashedDuringThisStep[i, k])
{
octopussFlashedDuringThisStep[i, k] = true;
totalFlashes += 1;
// handle any incrementing of neighbours of those who have flashed
List<(int x, int y)> neighbours = FindAdjacentCellsInclDiagonals((i, k), ref octopusses);
foreach ((int x, int y) neighbour in neighbours)
{
octopusses[neighbour.x, neighbour.y] += 1;
}
}
}
}
}
// if there are no 9s left then stop flashing
if (!ValueIsIn2dArray(9, octopusses))
{
stillFlashing = false;
}
}
// Finally, any octopus that flashed during this step has its energy level set to 0, as it
// used all of its energy to flash.
for (int i = 0; i < 10; i++)
{
for (int k = 0; k < 10; k++)
{
if (octopussFlashedDuringThisStep[i, k] == true)
{
octopusses[i, k] = 0; ;
}
}
}
}
static bool ValueIsIn2dArray(int value, int[,] twoDimensionalArray)
{
for (int x = 0; x < twoDimensionalArray.GetLength(0); x++)
{
for (int y = 0; y < twoDimensionalArray.GetLength(1); y++)
{
if (twoDimensionalArray[x, y] == value)
{
return true;
}
}
}
return false;
}
static List<(int x, int y)> FindAdjacentCellsInclDiagonals((int x, int y) currentCell, ref int[,] twoDimensionalArray)
{
List<(int x, int y)> list = new List<(int x, int y)>();
if (currentCell.x >= 1 && currentCell.y >= 1)
{
list.Add((currentCell.x - 1, currentCell.y - 1));
}
if (currentCell.y >= 1)
{
list.Add((currentCell.x, currentCell.y - 1));
}
if (currentCell.x < twoDimensionalArray.GetLength(0) - 1 && currentCell.y >= 1)
{
list.Add((currentCell.x + 1, currentCell.y - 1));
}
if (currentCell.x >= 1)
{
list.Add((currentCell.x - 1, currentCell.y));
}
if (currentCell.x < twoDimensionalArray.GetLength(0) - 1)
{
list.Add((currentCell.x + 1, currentCell.y));
}
if (currentCell.x >= 1 && currentCell.y < twoDimensionalArray.GetLength(1) - 1)
{
list.Add((currentCell.x - 1, currentCell.y + 1));
}
if (currentCell.y < twoDimensionalArray.GetLength(1) - 1)
{
list.Add((currentCell.x, currentCell.y + 1));
}
if (currentCell.x < twoDimensionalArray.GetLength(0) - 1 && currentCell.y < twoDimensionalArray.GetLength(1) - 1)
{
list.Add((currentCell.x + 1, currentCell.y + 1));
}
return list;
}
}
}
+293
View File
@@ -0,0 +1,293 @@
--- Day 11: Dumbo Octopus ---
You enter a large cavern full of rare bioluminescent dumbo octopuses! They seem to not like the Christmas lights on your submarine, so you turn them off for now.
There are 100 octopuses arranged neatly in a 10 by 10 grid. Each octopus slowly gains energy over time and flashes brightly for a moment when its energy is full. Although your lights are off, maybe you could navigate through the cave without disturbing the octopuses if you could predict when the flashes of light will happen.
Each octopus has an energy level - your submarine can remotely measure the energy level of each octopus (your puzzle input). For example:
5483143223
2745854711
5264556173
6141336146
6357385478
4167524645
2176841721
6882881134
4846848554
5283751526
The energy level of each octopus is a value between 0 and 9. Here, the top-left octopus has an energy level of 5, the bottom-right one has an energy level of 6, and so on.
You can model the energy levels and flashes of light in steps. During a single step, the following occurs:
First, the energy level of each octopus increases by 1.
Then, any octopus with an energy level greater than 9 flashes. This increases the energy level of all adjacent octopuses by 1, including octopuses that are diagonally adjacent. If this causes an octopus to have an energy level greater than 9, it also flashes. This process continues as long as new octopuses keep having their energy level increased beyond 9. (An octopus can only flash at most once per step.)
Finally, any octopus that flashed during this step has its energy level set to 0, as it used all of its energy to flash.
Adjacent flashes can cause an octopus to flash on a step even if it begins that step with very little energy. Consider the middle octopus with 1 energy in this situation:
Before any steps:
11111
19991
19191
19991
11111
After step 1:
34543
40004
50005
40004
34543
After step 2:
45654
51115
61116
51115
45654
An octopus is highlighted when it flashed during the given step.
Here is how the larger example above progresses:
Before any steps:
5483143223
2745854711
5264556173
6141336146
6357385478
4167524645
2176841721
6882881134
4846848554
5283751526
After step 1:
6594254334
3856965822
6375667284
7252447257
7468496589
5278635756
3287952832
7993992245
5957959665
6394862637
After step 2:
8807476555
5089087054
8597889608
8485769600
8700908800
6600088989
6800005943
0000007456
9000000876
8700006848
After step 3:
0050900866
8500800575
9900000039
9700000041
9935080063
7712300000
7911250009
2211130000
0421125000
0021119000
After step 4:
2263031977
0923031697
0032221150
0041111163
0076191174
0053411122
0042361120
5532241122
1532247211
1132230211
After step 5:
4484144000
2044144000
2253333493
1152333274
1187303285
1164633233
1153472231
6643352233
2643358322
2243341322
After step 6:
5595255111
3155255222
3364444605
2263444496
2298414396
2275744344
2264583342
7754463344
3754469433
3354452433
After step 7:
6707366222
4377366333
4475555827
3496655709
3500625609
3509955566
3486694453
8865585555
4865580644
4465574644
After step 8:
7818477333
5488477444
5697666949
4608766830
4734946730
4740097688
6900007564
0000009666
8000004755
6800007755
After step 9:
9060000644
7800000976
6900000080
5840000082
5858000093
6962400000
8021250009
2221130009
9111128097
7911119976
After step 10:
0481112976
0031112009
0041112504
0081111406
0099111306
0093511233
0442361130
5532252350
0532250600
0032240000
After step 10, there have been a total of 204 flashes. Fast forwarding, here is the same configuration every 10 steps:
After step 20:
3936556452
5686556806
4496555690
4448655580
4456865570
5680086577
7000009896
0000000344
6000000364
4600009543
After step 30:
0643334118
4253334611
3374333458
2225333337
2229333338
2276733333
2754574565
5544458511
9444447111
7944446119
After step 40:
6211111981
0421111119
0042111115
0003111115
0003111116
0065611111
0532351111
3322234597
2222222976
2222222762
After step 50:
9655556447
4865556805
4486555690
4458655580
4574865570
5700086566
6000009887
8000000533
6800000633
5680000538
After step 60:
2533334200
2743334640
2264333458
2225333337
2225333338
2287833333
3854573455
1854458611
1175447111
1115446111
After step 70:
8211111164
0421111166
0042111114
0004211115
0000211116
0065611111
0532351111
7322235117
5722223475
4572222754
After step 80:
1755555697
5965555609
4486555680
4458655580
4570865570
5700086566
7000008666
0000000990
0000000800
0000000000
After step 90:
7433333522
2643333522
2264333458
2226433337
2222433338
2287833333
2854573333
4854458333
3387779333
3333333333
After step 100:
0397666866
0749766918
0053976933
0004297822
0004229892
0053222877
0532222966
9322228966
7922286866
6789998766
After 100 steps, there have been a total of 1656 flashes.
Given the starting energy levels of the dumbo octopuses in your cavern, simulate 100 steps. How many total flashes are there after 100 steps?
View File
+10
View File
@@ -0,0 +1,10 @@
5483143223
2745854711
5264556173
6141336146
6357385478
4167524645
2176841721
6882881134
4846848554
5283751526
+24
View File
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_14</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Update="input.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Creek.HelpfulExtensions" Version="1.4.3" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
</ItemGroup>
</Project>

Some files were not shown because too many files have changed in this diff Show More