mirror of
https://github.com/jcreek/advent-of-code.git
synced 2026-07-13 03:03:46 +00:00
chore(*): Move old solutions into a separate folder
This commit is contained in:
@@ -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>
|
||||
@@ -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}");
|
||||
@@ -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?
|
||||
@@ -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
@@ -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>
|
||||
@@ -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}");
|
||||
@@ -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?
|
||||
@@ -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
@@ -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>
|
||||
@@ -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; }
|
||||
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.)
|
||||
@@ -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
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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?
|
||||
@@ -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?
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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?
|
||||
@@ -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?
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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.");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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?
|
||||
@@ -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?
|
||||
@@ -0,0 +1 @@
|
||||
3,4,3,1,2
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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?
|
||||
@@ -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?
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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?
|
||||
@@ -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?
|
||||
@@ -0,0 +1 @@
|
||||
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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?
|
||||
@@ -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?
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -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];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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?
|
||||
@@ -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?
|
||||
@@ -0,0 +1,106 @@
|
||||
<{({(([[<<([[([][])]{([]<>)([]<>)}]<[[[]{}]{()[]}]>)(<<[[]()][[]()]><[<>[]]<[]()>>>{<<<><>><<>[]>>[<[]<>><
|
||||
{<[<((<<({([{{{}[]}<<><>>}]<<{[]<>}([]<>)>>)<{(<[]()>{()()})<(()<>){(){}}>}([(()[])<[]>][[[][]]{{}}])
|
||||
<{[[{<[[{(<[[({}())[()()]]([<>()](<>()))][(([]<>)([][]))(({}{})[<><>])]><<<[[]<>][{}[]]>([<>{}
|
||||
<[[<[([({[{<[({}<>)([]<>)](<<>[]>([]()))><[<[]{}>[<><>]]>}>[{[[({}<>)<()<>>][{{}[]}(()())]][[(<>{}){<>{
|
||||
[((<{((([[<<<[<><>]{{}[]}>>(([<><>]<()[]>)<(()<>)>)>([[[{}{}][[][]>]<{<>()}[<>{}]>])]]<{[<[
|
||||
([{([[[{(<({<<[]<>>[()()]>{(()[])}})<(<<{}()>(<>>>([(){}]))<[(<>{}){()}]((()[]){()()})>>>)}{
|
||||
<{{[(<[<<[[{<(()[])>[[{}()]{{}[]}]}[[(<>())[()()]]{<{}{}>}]](<{[<><>]{{}{}}}<({}[])[<><>]>><{[{}<>](<><>)
|
||||
{({<[<([[(({({<>()}{{}{}})})<<<((){})[[]()]><{{}()}[[][]]>>{(<{}{}>{{}()})}>)<<{<[{}[]][{}{}]>([[][]]{
|
||||
{[(((((<{[({<{()[]}(()())>{<(){}>{{}()}}}(<[<>()]{[]()}>(<()()>{{}<>})))[<[[{}{}](<>()>]({[]<>
|
||||
(([((<{<[((<{{<><>}{[]{}}}><<<<>>[{}]>([[]{}]<<>[]>)>)[[{<{}>{()()}}[[{}[]](()()>]](<<<>{}>[[]
|
||||
{<([[{<{([[<([[]<>]({}{})){{{}()}({}[])}>](<(<()()><()[]>)<<[]<>>([]{})>>)]){[{<<[()[]]<<>{}>><({
|
||||
<{[[([<<<(<{{(()<>)(()())}([{}<>]((){}))}>)>({({{{()<>}({}<>)}<[[]<>]{<>[]}>})(({<(){}>[<>[]]}<([]{})<[]{}>>)
|
||||
(<{<{[[({(<[((<>[]){{}})<(<><>)<[]{}>>]((<<>[]><[]()>)<<{}{}>{(){}}>)>(<[[[]<>]]{{<>{}}{[]()}}>(<{
|
||||
{(({{[[{<[((<<()<>>[{}{}]>((()<>){[]()})){{(<>{})[<>[]]}<<<><>>>}){{({<>{}}([]()))[{<><>}{[]
|
||||
(([<(([({{<{[{()<>}<{}[]>]}{[[()()][()<>]}[{<>{}}({}{})]}>((<<<>{}>[<>()]>{{[]<>}({}{})}){[<{
|
||||
[[{{(<<[[[[<<<<>{}>({}())>[([]<>)(()())]>]<<<{<>()}>[<<>[]>[()()]]>[([[]()]<[][]))<[<>{}]{{}<>
|
||||
{[{(((([<[{([(()()){()()}][<(){}>[{}<>)])[(<{}<>>{<>()})({{}<>}[()[]])]}(<({[]<>}<()[]>)({[]<>
|
||||
<<([(([{<{<<<[{}[]]((){})>((<>[])(()<>))>{{{<>()}{[]}}{([][])}}>[<{{<>[]}<<>>}({[]<>})>]]({({{<><>
|
||||
[{((<{<[[<[{[{{}<>}]{[{}][<>[]]}}[<([]())<()[]>>((<>){[]{}})]]<{(<()<>><{}<>]){[[]<>]({}{})}}({<{}[]>{{}
|
||||
<[<{(<[[<(((<({}[])><(<><>)(<>())]){{{()()}(<>())}<[{}()]>})[([[<>[]]{{}[]}]{{{}()}<{}[]>})[[(()<>){<>
|
||||
[([{{[<([{[([[()<>]])([[<>][()[]]][[<>[]]<<>[]>])]}{([<<{}()>({})>(<[]()>(<><>))]<<{{}<>}{<>}><(<>
|
||||
<<[[([([(<(<<[{}[]]<()[]]><{[]{}}[<>()]>>)>[<<({[][]}<<><>>)[<{}{}>{()<>}]><({<>{}}([]))((
|
||||
<({<{(<[({([[{()}(<><>)](<[][]>[{}{}])](([[]<>]<<>{}>))){({<<>{}>[[]{}]}<([][])>)<<(<><>)<[]<>>}>}}((([[()<
|
||||
{([<(<[(({[({[(){}]<<>{}>}[[{}{}][{}[]]])]{({[()<>]{()[]}}(<[][]>[()[]])){{{[]{}}(<>[])}[<(){}>(
|
||||
<[<[<{[{<[{[<<{}<>>(<>)>]{<({}{}){(){}}>((<>{})[{}<>])}}[<[[<><>]{{}<>}]{<()()>}>{<<[]()>(()())>{{{}<
|
||||
(({[[<<[({[{{<()()>}}{<[<>()]>}][(<{[][]}>{[{}()]{[]<>}})<{{<>{}}(()[])}{{[]()}<<>[]>}>]})
|
||||
<((<([[({(<{[[(){}]<[][]>]}>({<[()<>](()[])>(([]<>)([]<>))}<{[[]<>]{(){}}}(<()<>>([][]])>))}<{[<[({}
|
||||
{({{{[[{{[{(<<(){}>[{}{}]>((()<>)[<>{}]))[<<{}[]><[]>>[{{}{}}(<>[])]]}[(<<(){}>({}{}))((<>{})([]<>)))
|
||||
[[(({[{(<({[{<[]()>{()[]}}<(<>())<()()>>]<(({}[]){{}<>])((()<>){{}[]})>}([[({}{})[<>()]][{<><>}]]{([[
|
||||
[[{<[([<[((<([[]{}][{}<>])([{}<>])>[([()<>]{{}{}}){{[]()}}])<({{[]()}[[]()]))>)([<<<<>{}><{}()>><(<>
|
||||
<<({{{<{[<{<{<[]<>>[[]{}]}[<[]()>{[]{}}]>[[[(){}][<><>]]{(<>[]}({}{})}]}><[[({{}[]}{[]()}){(<>())[()<
|
||||
{{(({[[[{<[<(([]())([]{}))([{}{}](()[])}>]>}([<{[[[]()][(){}]]<{<>[]}>}({<()<>><[]<>>})>((([()
|
||||
(<(({{(([(({{<{}[]>({}())}([<>[]][{}()])}((<[][]>{()<>}){[[]<>]<{}{}>}))<({{[]<>}([][])}{<[]{}>{<>[]}})
|
||||
((([<([([{{{<<<>{}><{}[]>>[[<>[]][{}[]]]}}(([<<>{}>[()[]]][{{}{}}])(<[()()][<><>]>{{<>[]}})}}]<{[[<
|
||||
{{(<[<[<[<<[[(<>[])]({<><>}[()()])]>>]>[{{[[{(<>[])([][])}{[[][]]([]())}]>[[[<{}{}>({}())]<{<>
|
||||
<[{[[([[{[(<[<{}{}>{(){}}][{[]<>}<()[]]]>(([()<>][[][]]){[<>{}](()[])}))[[<<{}>[<>{}]>[({}{})({}{})]]<([[]{}
|
||||
({<<<{<({{{{{[()()]({}())}[[[]{}][<><>])}({<()()><[]()>}({<>()}))}{(((<>()){()()}){<(){}><()[]>})(([{}()]
|
||||
([<({[{({(<<{[{}()]}{{{}[]}((){})}>>)<<{[((){})[()]]}<<{[]<>}<<>()>>([<>()][[]<>])>>{<<[<>[]]<[]<>>)<{<
|
||||
(<[<<(<[[[[{{({}<>)[{}{}]}<[[]{}]([]<>)>}][<[<<>{}>{[]}][[[]{}](<>())]><<[<>()][(){}]><{[]
|
||||
(({[[(([<(([{({}[])[<>{}]}{(<>[])({}{})})<<<{}[]>({}())>[({}<>)<{}()>]>)[<<[[][]]((){})><{{}(
|
||||
{[((<([<[{[{<[<><>][()()]><{<>{}}>}[{<[][]>[()<>]}<(<>())<()<>>>]]<<<(<>())<()[]>>>[{{{}[]}}[[{}()]((){
|
||||
{{<{({{({[<((({}{}){<>[]}){<{}()>{<>[]}})>(<{<<>{}><[]<>>}>[[{[]<>>{<><>}]{((){})<(){}>}])]}(<{[{{<><>}{[
|
||||
(({<[[{[(<(((({}{}){()<>}))<{{[]{}}{{}{}}}<[{}<>][(){}]>>)>[{{(<<><>>([]{}))[((){})<{}[]>]}}(([[<>()]{<>()}]
|
||||
[<([[[<[<{<{<{[]{}}{[]{}}>[([]())<<>[]>]}({{[]{}}<[]()>}<({}())(<>{})>)>}[({[[{}[]][{}<>]]})]>]><[
|
||||
<{[<<[[<{[[{<<{}[]>[<><>]>}({[[]{}]<{}()>}((()[])))]{[<{()}[[]{}]>]{(({}[])<{}()>)<(<>())[()<>]
|
||||
[[([[{[[(([{[[<>()]{<>()}]({(){}}({}{}))}[<[<><>]([]())>(<[]()><{}[]>)]]{(<<<><>>[[]{}]>(<[][]>((){}))
|
||||
{(<<[[{[{{(<<<{}[]>(<>[])>({[]{}}([]{}))>[{<<>()>[[]<>]]([{}[]])])}[[{(<<><>>[()()])<<<><>>>}([<<>
|
||||
([((<(<[(<{((<{}{}>{<><>})){{(()[])[{}[]]}}}{[[[(){}][<><>]]]({<()<>>{{}[]}}<[()()]{()[]}>)}>[<{(<{}
|
||||
[(<[([[({({<[{<>()}([]<>)][(<><>)<()[]>]>})[{([(())({}[])][{[]<>}<()<>>])}({<[{}{}](()())><({}())[<>[]
|
||||
([(<<[<{<{((<(<>[])({}<>)>{{()()}<<>{}>}))<{[[()[]][()[]]][({}[])<{}()>]}{<({})><{[][]}{{}<>}>}>}<<<({(){}}
|
||||
[(<{(([({<{{(<[]<>>({}()))}}[<[[{}[]][[]]]>[({[]<>}(<>{}))]]>})]<([(<([[()()][[][]]]<((){}
|
||||
((({([(<<{{<<({}())(())>([<>()]<()()>)>}}<[(<{{}[]}<()<>>><({}{}){(){}}>)][(({()<>}([]()))([()]))({{{}()}
|
||||
{<(({[<([{[({([][])[[]{}]}<({}<>)<<>()>>)<<{<>()}{[]<>}>{{{}}{[]()}}>]}])<<{<(([[]{}]<<>[]>)){<<[]<>>><<()[
|
||||
[{<(<<<((<<<{[()<>]{[]<>}}>[[<{}{}>[()[]]]<(<><>)[()[]]>]>{[[[[]()][<>[]]]]({(<>}{[]{}}})}>){({
|
||||
<<[((<<[{{[(<[<>()]><{{}[]}{<>{}}>){[(()[])([]())][[(){}][{}[]]]}]([<[[][]]{(){}}><<{}{}>{<>{}}>][[
|
||||
{<<{<<{<({[[([<>{}])[{[]<>}{{}[]}]][[<()<>>[<>{}]]]]<([{[]()}({}{})]({[]()}{<>()})){[({}<>)[[]{}
|
||||
{<<[{((([<([[<[]()><<><>>][{()<>}<[][]>]]{<[{}[]][()[]]>[{<>{}>{[]}]}){[([[]{}]<()[]>)[[<>()][{}[]]
|
||||
({{{{<([[((({{{}{}}<()[]>}{<()<>>{{}<>}})(<({}{})>({<>{}}[[]()]))){(<<<><>><()[]>>[{()()}{[]<>}
|
||||
({<{[[{({{[<[{[][]}<[][]>]{(<><>)}>([[<>{}][<>{}]]({[]{}}<<>[]>))]}{[({[[]]{()[]}}{(<>{})[()()]})(<{(
|
||||
[{<<<[(<(<{((([]{}))[{<>()}[()[]]]){{<{}{}>}[<[]<>>{<>{}}]}}<(<[<>[]][()()]>)<([{}()]{{}[]})
|
||||
{{(([[([((<([[<><>]])>({[{()<>}<[]{}>]}<{[()()]<{}>}(<{}<>>({}{}))>))[{{([()()]<{}<>>){(<>{})(
|
||||
([(<{[[{<{{<{([]())(<>[])}{{[]<>}{()<>}}>{{{()}}[<[]{}><{}<>>]}}<{[{()()}]{{<>[]}[<><>]}}<<{<>(
|
||||
([[{[{[{<<(<{<{}{}>{[]}}{[{}{}]{()[]}}>[{({}[])}<[()[]]>])>>[(<<({<>{}}{[]{}})>>(<[([]()){()<>}]((()())([]
|
||||
(({<({<([(({<<<>()>([]())>{<()[]>{[]<>}}}(<{{}<>}[()()]>({{}<>}[{}()]))))]){{<[{[(<>[]){()
|
||||
([[(<{[[{<[<(<[]()>[{}[]]){[<><>]{<>[]}}>{{([]()){[]{}}}<((){})([]<>)>}]<<<{{}[]}[()]>(<{}><[][]>)>>>}
|
||||
{{(<[{[([<<<[<{}<>>(<>{})]<({}[])[<>[]]>>({<{}{}><[]{}>}<<[]><(){}>>)>>(((({()()}[[]{}]))<[{[]<>)<[]()>]
|
||||
(({{<<[{([[({[[]{}]{()<>}}[(<><>)[()()]])[<[<>[]]><([]{})[[][]]>]](<((<><>)<<>()>)[([][])((){})]>[(
|
||||
((<<([[<{[{({<(){}><[][]>}{(()[])({}[])})({[{}()]({}{})}(<(){}>(<><>)))}{{[{()<>}<{}{}>][{[]{}}(()
|
||||
<{(((([<[((({{{}<>}[[]<>]}<[{}<>]>)[<({}{})>{{[]()}<{}()>}])<([<<>>(<><>)]((()())(<>{})))>){(({(
|
||||
<{{<<{{{[({{[<()[]>(()[])]}<<[[]<>][[]]>>}[<[({})<<>[]>][[[]]([][])]>])]}}(<({[[<[(){}]>{<[]{}>}]{(({
|
||||
[([[(({([{{({{()}[{}<>]}{({}<>){{}()}}]}}{[<<({}())<(){}>>[{()[]}([]{})]>]{<<{{}()}(<>[])>{[(
|
||||
[{[{[([<<((<<{()<>}<<>()>>[{[]{}}{{}[]}]>[[{[][]}{{}}]])(([((){})(()())]{[(){}]{()}})))}{(<<<<<><>>({}[]
|
||||
<[{({[({[({{(<[]()>{{}<>}){{{}<>}[(){}]}}(([{}()]<[][]>)[[<>]({}{})])}<<[(<>)({})]<<()[]><
|
||||
[((([<(({<<({{{}()}({}<>)}({()[]}[{}{}]))>{[{(<>[])}{(<>[])<{}[]>}]{<[<><>][()[]]>}}>({<{<<>()><<><>>}([{}[]]
|
||||
{({((<<([((<[[()[]]{[][]}]<{(){}}{<>{}}>>({[(){}][<>]})))(<(({<>[]}<(){}>)(<()[]><{}()>))>)]){
|
||||
<{<[<(<{<[({{{{}<>}<<>{}>}{[[]()][{}{}]}}[({<><>}{<>{}})[[{}()]{[]()}]])({{<[])(<>[])}})](<<[[<><>]](<{}{}>
|
||||
[([[[{[((<<(<<()()>>)><<{([]()){<>{}}}<{[]{}}<()()>>>[(<<><>>[()[]]){((){})([]{})}]>>({[<[<><>]{<><
|
||||
<{{({{{[<{[{{{()<>}[<><>]}[(()[]){[]{}}]}(<{{}[]}[<>[]]><{{}{}}<{}[]>>)]{(({(){}}<<>{}>)[<<><>>[{}
|
||||
[[([[{[({[{[({{}[]}{()[]})[<()()>{{}{}}]][(([]<>)<[][]>)[<{}{}><{}()>]]}][<([([][]){()()}][[{}{}]{()<
|
||||
{(<<(((<((((<{()<>}<<>[]>)[<[][]>[{}()]]){[[[]<>]<(){}>][<()<>>{{}<>}]})))<[{{[{{}{}}<[]<>>]}}(
|
||||
{[(<{[<{{({[{[<><>](<>{})}{({}[])(<>{})}]}({<({}[])<[]<>>>(({}[]))}[<<()><<>>}[{()[]}{[][]}]])){[({<<>()>(
|
||||
<([{[(<(<<([((()())<{}{}>)]<{(<>())(<>()]}{[()<>](<>())}>)<[[<[][]>]{{()}<<><>>}](({()()}[[
|
||||
<[<[<{{{[{((<(()()){{}<>)><[[]()](()<>)>))({[[<>{}]{{}()}]({()<>}(()[]))})}]}([{((({{}()}[()<
|
||||
[{([({[<(<{[{[<>[]][<>()]}([[]{}](()()))){{[()()]<(){}>}({()[]}<[]()>)}}<{[(<>[]){()<>}][[()<>]{()[]}]}{<(<>
|
||||
{((<(<({{([{[([]<>){[]<>}](<[]<>>[[]<>])}{{<[][]><()[]>}({()<>}<<>{}>)}]<[<[<>()]([]{})><{{}<>}<{}<>>>][(
|
||||
{<<([<(<{[[{{{<>[]}[[]<>]}{[{}[]]]}{<[(){}]>{[{}()]{[]<>}}}](<{[[]<>]{<>[]}}<<()<>>[[]()]>>)]<[{{<{}>[{}]}<(
|
||||
[[{{{<{[{({<<<[]{}>[()<>]><[[]<>]([]<>)>><{<<>()>[<>{}]}>}((<[{}{}]{[]}]{<[]<>>{<>{}}})[([<>(
|
||||
[[{<<{{[(([[[{()[]}][[()[]]<[]>]]({{{}}})][({([][])[{}{}]}<[(){}]<()[]>>){<{[]{}}[(){}]><{{}{}}<<>()>]}]))<<
|
||||
[(({[<<{<({<([<><>])[{<>()>{{}[]}]>((<()<>><{}<>>)[{[][]}([]{})])})<{{([[]<>]<{}<>>)([()[]]{()()}
|
||||
[([(({(<[<[<((<>{})[[]<>]){[<><>]({}[]>}>]>]>)}[(({(<<[{(){}}[()[]]]>[<(<>{}){{}{}}>[[()<>][()]]]>)
|
||||
{<{{<({<{((<{({})<<>{}>}((()){()<>})>))}((<{((()[]){{}[]})[<<>>[[]<>]]}(([<>](()<>)))><{{{<>()}((){}}}((
|
||||
<[<{<((({{[<{{[][]}}<([]<>)(<>{})>>]}[(([{()()}{<>()}])[<[()[]][()[]]>]){<<[<>()](<>{})>{{(){}}(<>
|
||||
(([{([{[<(<(((()<>))[(())(<>{})])([[{}<>]{{}[]}][{<><>}[{}{}]])>[(([()[]]<[][]>)[{{}[]}(()[])])(([{}{}]
|
||||
{<(<<{<[{<{<<<<>[]>[[]<>]){[[]()][<><>]}>({(<><>)(()<>)})}>[<([{{}{}}<[]<>>])({{[]<>}({}[])})>]}{<<[(
|
||||
<{([({{{<{[{(([]())<<><>>)<[()()]((){})>}]}(<{(<(){}>(<>()))}([[()[]][(){}]](<<>{}>[{}()])}>)>([{<(
|
||||
((([{<<[{{[(<<[]<>>(<>())>{({}{})<{}[]>})[[<()()>[<>[]]][<{}[]>(()())]]]}}]>>)]{{{{[[{[[[([]<>){
|
||||
({(<{{({[[{<<(()[])[()]>[{<><>}{<>[]}]>{<{<><>}{()[]}>{[{}()]{[][]}}}}{<<{[]<>}(<><>)>{{[]{}}[
|
||||
(<[{{(([<{{(<[<>()]((){})>{<{}[]>({}())})}}>][<[{{([{}[]])<([]<>)<<>{}>>}}{<({[][]}(()()))(<<>()>{
|
||||
(<<{{{((<{({<<{}()><{}{}>><<()[]>[<>[]]>>(<[(){}]([]<>)>[({}<>)]))(({{[]<>}<()<>>}[<()[]>(()[])]){<[
|
||||
<[(((<({([({{[[]()]{[]()}}([{}()]<[]<>>)}[[<()[]>{{}{}}]([<>]<<>()>)]){[((()<>){<>[]}){[{}[]){[
|
||||
(({[[({{{[{{({(){}}{{}[]})<({}[])([]<>)>}[[(<>{})]<([]()){{}()}>]}[{<{[]<>}<()()>>([{}<>]<{
|
||||
<[({{[<[{({[({[]<>}{{}[]})[{[][]}{[][]}]][[<{}[]>{[]()}]([()[]]({}<>))]}{<{[{}<>]<[]()>}<<[]()>[<>{}]>><((
|
||||
[{[{<{{[<<[[<<{}<>>>][{{{}[]}({}())}]]([{<<><>>({}{})}{{[]<>}}]{{{[]()}([]<>)}})><({{<[][]>}}){<{{()><()>}>[<
|
||||
{{({([<({(<[({{}{}}<[]{}>)]>[(((<>()){<>()]))[<({}[])(<>{})>{<<><>>{[]()}}]]){{[<(()[])<()<>>>(<()<>>)]([<{}
|
||||
[({[<(<<[{<({<{}()>{{}()}})({({})<()()>}[{[]<>}[{}{}]})><[(({}{}))(((){})[[][]])]>}<{([<[]<>>]<[{}[]]((
|
||||
[<{{{<<(<[[{<([][]){<>}>}{<[[]]{[]{}}><{<>{}}>}]<<{([]())[<>[]]}><(([]{}){[]<>})[(<>())({}<>}]>>](
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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?
|
||||
@@ -0,0 +1,10 @@
|
||||
5483143223
|
||||
2745854711
|
||||
5264556173
|
||||
6141336146
|
||||
6357385478
|
||||
4167524645
|
||||
2176841721
|
||||
6882881134
|
||||
4846848554
|
||||
5283751526
|
||||
@@ -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>
|
||||
@@ -0,0 +1,260 @@
|
||||
using Creek.HelpfulExtensions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Day14
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
var sr = new StreamReader("input.txt");
|
||||
var translate = new Dictionary<string, string>();
|
||||
|
||||
string polymer = sr.ReadLine();
|
||||
|
||||
while (!sr.EndOfStream)
|
||||
{
|
||||
string line = sr.ReadLine();
|
||||
if (line.Length > 0)
|
||||
{
|
||||
var p = line.Split(" -> ");
|
||||
translate.Add(p[0], p[1]);
|
||||
}
|
||||
}
|
||||
|
||||
var pairs = new Dictionary<string, ulong>();
|
||||
var elements = new Dictionary<string, ulong>();
|
||||
|
||||
for (int k = 0; k < polymer.Length - 1; k++)
|
||||
{
|
||||
var p = polymer.Substring(k, 2);
|
||||
pairs.TryAdd(p, 0);
|
||||
pairs[p]++;
|
||||
}
|
||||
|
||||
for (int k = 0; k < polymer.Length; k++)
|
||||
{
|
||||
elements.TryAdd(polymer[k].ToString(), 0);
|
||||
elements[polymer[k].ToString()]++;
|
||||
}
|
||||
|
||||
for (int i = 0; i < 40; i++)
|
||||
{
|
||||
var newpairs = new Dictionary<string, ulong>();
|
||||
foreach (var p in pairs.Keys)
|
||||
{
|
||||
var insert = translate[p];
|
||||
var c = pairs[p];
|
||||
newpairs.TryAdd(p[0] + insert, 0);
|
||||
newpairs[p[0] + insert] += c;
|
||||
newpairs.TryAdd(insert + p[1], 0);
|
||||
newpairs[insert + p[1]] += c;
|
||||
elements.TryAdd(insert, 0);
|
||||
elements[insert] += c;
|
||||
}
|
||||
pairs = newpairs;
|
||||
}
|
||||
|
||||
ulong min = ulong.MaxValue;
|
||||
ulong max = ulong.MinValue;
|
||||
ulong sum = 0;
|
||||
|
||||
foreach (var a in elements.Values)
|
||||
{
|
||||
if (a > max) max = a;
|
||||
if (a < min) min = a;
|
||||
sum += a;
|
||||
}
|
||||
|
||||
Console.WriteLine($"Result: {max} - {min} = {max - min}, length = {sum}");
|
||||
}
|
||||
|
||||
//static void Main(string[] args)
|
||||
//{
|
||||
// string[] lines = File.ReadAllLines("input.txt");
|
||||
|
||||
|
||||
// //Part1(lines);
|
||||
// Part2(lines);
|
||||
//}
|
||||
|
||||
static void Part1(string[] lines)
|
||||
{
|
||||
string polymerTemplate = lines[0];
|
||||
|
||||
Console.WriteLine($"Template: {polymerTemplate}");
|
||||
|
||||
// Pair insertion rules are stored from index 2 onwards
|
||||
// A rule like AB -> C means that when elements A and B are immediately adjacent, element C
|
||||
// should be inserted between them.
|
||||
// Also, because all pairs are considered simultaneously, inserted elements are not considered
|
||||
// to be part of a pair until the next step.
|
||||
|
||||
List<Rule> rules = new List<Rule>();
|
||||
// Consider each rule
|
||||
for (int i = 2; i < lines.Length; i++)
|
||||
{
|
||||
// e.g. AB -> C
|
||||
string pairToMatch = lines[i].Substring(0, 2);
|
||||
string characterToInsert = lines[i].Substring(6, 1);
|
||||
|
||||
rules.Add(new Rule()
|
||||
{
|
||||
First = pairToMatch[0],
|
||||
Second = pairToMatch[1],
|
||||
Insert = characterToInsert[0],
|
||||
});
|
||||
}
|
||||
|
||||
// Set the number of steps to run
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
CompleteStep(ref polymerTemplate, ref lines, rules);
|
||||
//Console.WriteLine($"After step {i+1}: {polymerTemplate}");
|
||||
}
|
||||
|
||||
// Count occurrences of each character
|
||||
char[] chars = polymerTemplate.ToCharArray();
|
||||
List<char> uniqueCharacters = chars.Select(x => x).Distinct().ToList();
|
||||
List<(char character, int count)> countList = new List<(char character, int count)>();
|
||||
|
||||
foreach (char character in uniqueCharacters)
|
||||
{
|
||||
countList.Add((character, polymerTemplate.Count(c => c == character)));
|
||||
}
|
||||
|
||||
(char character, int count) mostCommon = countList.MaxBy(x => x.count);
|
||||
(char character, int count) leastCommon = countList.MinBy(x => x.count);
|
||||
|
||||
Console.WriteLine(mostCommon.count - leastCommon.count);
|
||||
}
|
||||
|
||||
static void Part2(string[] lines)
|
||||
{
|
||||
string polymerTemplate = lines[0];
|
||||
|
||||
Console.WriteLine($"Template: {polymerTemplate}");
|
||||
|
||||
// Pair insertion rules are stored from index 2 onwards
|
||||
// A rule like AB -> C means that when elements A and B are immediately adjacent, element C
|
||||
// should be inserted between them.
|
||||
// Also, because all pairs are considered simultaneously, inserted elements are not considered
|
||||
// to be part of a pair until the next step.
|
||||
|
||||
Dictionary<(char, char), char> rules = new Dictionary<(char, char), char>();
|
||||
// Consider each rule
|
||||
for (int i = 2; i < lines.Length; i++)
|
||||
{
|
||||
// e.g. AB -> C
|
||||
string pairToMatch = lines[i].Substring(0, 2);
|
||||
string characterToInsert = lines[i].Substring(6, 1);
|
||||
|
||||
rules.Add((pairToMatch[0], pairToMatch[1]), characterToInsert[0]);
|
||||
}
|
||||
|
||||
// Set the number of steps to run
|
||||
for (int i = 0; i < 40; i++)
|
||||
{
|
||||
Stopwatch stopWatch = new Stopwatch();
|
||||
stopWatch.Start();
|
||||
|
||||
CompleteStepNew(ref polymerTemplate, rules);
|
||||
|
||||
stopWatch.Stop();
|
||||
TimeSpan ts = stopWatch.Elapsed;
|
||||
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
|
||||
ts.Hours, ts.Minutes, ts.Seconds,
|
||||
ts.Milliseconds / 10);
|
||||
Console.WriteLine($"Step {i + 1} took {elapsedTime}");
|
||||
}
|
||||
|
||||
// Count occurrences of each character
|
||||
char[] chars = polymerTemplate.ToCharArray();
|
||||
List<char> uniqueCharacters = chars.Select(x => x).Distinct().ToList();
|
||||
List<(char character, int count)> countList = new List<(char character, int count)>();
|
||||
|
||||
foreach (char character in uniqueCharacters)
|
||||
{
|
||||
countList.Add((character, polymerTemplate.Count(c => c == character)));
|
||||
}
|
||||
|
||||
(char character, int count) mostCommon = countList.MaxBy(x => x.count);
|
||||
(char character, int count) leastCommon = countList.MinBy(x => x.count);
|
||||
|
||||
Console.WriteLine(mostCommon.count - leastCommon.count);
|
||||
}
|
||||
|
||||
static void CompleteStepNew(ref string polymerTemplate, Dictionary<(char, char), char> rules)
|
||||
{
|
||||
LinkedList<char> temporaryList = new LinkedList<char>();
|
||||
char[] temporaryTemplate = polymerTemplate.ToCharArray();
|
||||
|
||||
for (int i = 0; i < temporaryTemplate.Length; i++)
|
||||
{
|
||||
temporaryList.AddLast(temporaryTemplate[i]);
|
||||
}
|
||||
|
||||
LinkedListNode<char> pointer = temporaryList.Find(temporaryList.First());
|
||||
|
||||
// Insert the new character into the linked list but do not change the temporary template we're checking against
|
||||
for (int i = 0; i < temporaryTemplate.Count() - 1; i++)
|
||||
{
|
||||
char insertValue;
|
||||
|
||||
//using ("First".DisposableStopWatch())
|
||||
//{
|
||||
rules.TryGetValue((temporaryTemplate[i], temporaryTemplate[i + 1]), out insertValue);
|
||||
//}
|
||||
|
||||
temporaryList.AddAfter(pointer, insertValue);
|
||||
|
||||
// Move on an extra position as we have added a node
|
||||
pointer = pointer.Next.Next;
|
||||
}
|
||||
|
||||
polymerTemplate = String.Join("", temporaryList);
|
||||
//polymerTemplate = string.Concat(temporaryList); // this is slower
|
||||
}
|
||||
|
||||
static void CompleteStep(ref string polymerTemplate, ref string[] lines, List<Rule> rules)
|
||||
{
|
||||
LinkedList<char> temporaryList = new LinkedList<char>();
|
||||
List<char> temporaryTemplate = new List<char>();
|
||||
|
||||
foreach (char character in polymerTemplate)
|
||||
{
|
||||
temporaryList.AddLast(character);
|
||||
temporaryTemplate.Add(character);
|
||||
}
|
||||
|
||||
LinkedListNode<char> pointer = temporaryList.Find(temporaryList.First());
|
||||
|
||||
// Insert the new character into the linked list but do not change the temporary template we're checking against
|
||||
for (int i = 0; i < temporaryTemplate.Count() - 1; i++)
|
||||
{
|
||||
Rule matchingRule = rules.FirstOrDefault(r => r.First == temporaryTemplate.ElementAt(i) && r.Second == temporaryTemplate.ElementAt(i + 1));
|
||||
|
||||
if (matchingRule is not null)
|
||||
{
|
||||
temporaryList.AddAfter(pointer, matchingRule.Insert);
|
||||
|
||||
// Move on an extra position as we have added a node
|
||||
pointer = pointer.Next;
|
||||
}
|
||||
|
||||
pointer = pointer.Next;
|
||||
}
|
||||
|
||||
polymerTemplate = String.Join("", temporaryList);
|
||||
}
|
||||
|
||||
|
||||
class Rule
|
||||
{
|
||||
public char First { get; set; }
|
||||
public char Second { get; set; }
|
||||
public char Insert { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
--- Day 14: Extended Polymerization ---
|
||||
The incredible pressures at this depth are starting to put a strain on your submarine. The submarine has polymerization equipment that would produce suitable materials to reinforce the submarine, and the nearby volcanically-active caves should even have the necessary input elements in sufficient quantities.
|
||||
|
||||
The submarine manual contains instructions for finding the optimal polymer formula; specifically, it offers a polymer template and a list of pair insertion rules (your puzzle input). You just need to work out what polymer would result after repeating the pair insertion process a few times.
|
||||
|
||||
For example:
|
||||
|
||||
NNCB
|
||||
|
||||
CH -> B
|
||||
HH -> N
|
||||
CB -> H
|
||||
NH -> C
|
||||
HB -> C
|
||||
HC -> B
|
||||
HN -> C
|
||||
NN -> C
|
||||
BH -> H
|
||||
NC -> B
|
||||
NB -> B
|
||||
BN -> B
|
||||
BB -> N
|
||||
BC -> B
|
||||
CC -> N
|
||||
CN -> C
|
||||
The first line is the polymer template - this is the starting point of the process.
|
||||
|
||||
The following section defines the pair insertion rules. A rule like AB -> C means that when elements A and B are immediately adjacent, element C should be inserted between them. These insertions all happen simultaneously.
|
||||
|
||||
So, starting with the polymer template NNCB, the first step simultaneously considers all three pairs:
|
||||
|
||||
The first pair (NN) matches the rule NN -> C, so element C is inserted between the first N and the second N.
|
||||
The second pair (NC) matches the rule NC -> B, so element B is inserted between the N and the C.
|
||||
The third pair (CB) matches the rule CB -> H, so element H is inserted between the C and the B.
|
||||
Note that these pairs overlap: the second element of one pair is the first element of the next pair. Also, because all pairs are considered simultaneously, inserted elements are not considered to be part of a pair until the next step.
|
||||
|
||||
After the first step of this process, the polymer becomes NCNBCHB.
|
||||
|
||||
Here are the results of a few steps using the above rules:
|
||||
|
||||
Template: NNCB
|
||||
After step 1: NCNBCHB
|
||||
After step 2: NBCCNBBBCBHCB
|
||||
After step 3: NBBBCNCCNBBNBNBBCHBHHBCHB
|
||||
After step 4: NBBNBNBBCCNBCNCCNBBNBBNBBBNBBNBBCBHCBHHNHCBBCBHCB
|
||||
This polymer grows quickly. After step 5, it has length 97; After step 10, it has length 3073. After step 10, B occurs 1749 times, C occurs 298 times, H occurs 161 times, and N occurs 865 times; taking the quantity of the most common element (B, 1749) and subtracting the quantity of the least common element (H, 161) produces 1749 - 161 = 1588.
|
||||
|
||||
Apply 10 steps of pair insertion to the polymer template and find the most and least common elements in the result. What do you get if you take the quantity of the most common element and subtract the quantity of the least common element?
|
||||
@@ -0,0 +1,6 @@
|
||||
--- Part Two ---
|
||||
The resulting polymer isn't nearly strong enough to reinforce the submarine. You'll need to run more steps of the pair insertion process; a total of 40 steps should do it.
|
||||
|
||||
In the above example, the most common element is B (occurring 2192039569602 times) and the least common element is H (occurring 3849876073 times); subtracting these produces 2188189693529.
|
||||
|
||||
Apply 40 steps of pair insertion to the polymer template and find the most and least common elements in the result. What do you get if you take the quantity of the most common element and subtract the quantity of the least common element?
|
||||
@@ -0,0 +1,18 @@
|
||||
NNCB
|
||||
|
||||
CH -> B
|
||||
HH -> N
|
||||
CB -> H
|
||||
NH -> C
|
||||
HB -> C
|
||||
HC -> B
|
||||
HN -> C
|
||||
NN -> C
|
||||
BH -> H
|
||||
NC -> B
|
||||
NB -> B
|
||||
BN -> B
|
||||
BB -> N
|
||||
BC -> B
|
||||
CC -> N
|
||||
CN -> C
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace>_15</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="input.txt">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,101 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Day15
|
||||
{
|
||||
public class Dijkstra
|
||||
{
|
||||
public object PartOne(string input) => Solve(GetRiskLevelMap(input));
|
||||
public object PartTwo(string input) => Solve(ScaleUp(GetRiskLevelMap(input)));
|
||||
|
||||
int Solve(Dictionary<Point, int> riskMap)
|
||||
{
|
||||
// Disjktra algorithm
|
||||
|
||||
var topLeft = new Point(0, 0);
|
||||
var bottomRight = new Point(riskMap.Keys.MaxBy(p => p.x).x, riskMap.Keys.MaxBy(p => p.y).y);
|
||||
|
||||
// Visit points in order of cumulted risk
|
||||
// ⭐ .Net 6 finally has a PriorityQueue collection :)
|
||||
var q = new PriorityQueue<Point, int>();
|
||||
var totalRiskMap = new Dictionary<Point, int>();
|
||||
|
||||
totalRiskMap[topLeft] = 0;
|
||||
q.Enqueue(topLeft, 0);
|
||||
|
||||
// It would be enough to go until we find the bottom right corner, but computing all
|
||||
// risk levels is not much more work
|
||||
while (q.Count > 0)
|
||||
{
|
||||
var p = q.Dequeue();
|
||||
|
||||
foreach (var n in Neighbours(p))
|
||||
{
|
||||
if (riskMap.ContainsKey(n) && !totalRiskMap.ContainsKey(n))
|
||||
{
|
||||
var totalRisk = totalRiskMap[p] + riskMap[n];
|
||||
totalRiskMap[n] = totalRisk;
|
||||
if (n == bottomRight)
|
||||
{
|
||||
break;
|
||||
}
|
||||
var h = 0; //bottomRight.y - n.y + bottomRight.x - n.x;
|
||||
q.Enqueue(n, totalRisk + h);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// return bottom right corner's total risk:
|
||||
return totalRiskMap[bottomRight];
|
||||
}
|
||||
|
||||
// Create an 5x scaled up map, as described in part 2
|
||||
Dictionary<Point, int> ScaleUp(Dictionary<Point, int> map)
|
||||
{
|
||||
var (ccol, crow) = (map.Keys.MaxBy(p => p.x).x + 1, map.Keys.MaxBy(p => p.y).y + 1);
|
||||
|
||||
var res = new Dictionary<Point, int>(
|
||||
from y in Enumerable.Range(0, crow * 5)
|
||||
from x in Enumerable.Range(0, ccol * 5)
|
||||
|
||||
// x, y and risk level in the original map:
|
||||
let tileY = y % crow
|
||||
let tileX = x % ccol
|
||||
let tileRiskLevel = map[new Point(tileX, tileY)]
|
||||
|
||||
// risk level is increased by tile distance from origin:
|
||||
let tileDistance = (y / crow) + (x / ccol)
|
||||
|
||||
// risk level wraps around from 9 to 1:
|
||||
let riskLevel = (tileRiskLevel + tileDistance - 1) % 9 + 1
|
||||
select new KeyValuePair<Point, int>(new Point(x, y), riskLevel)
|
||||
);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
// store the points in a dictionary so that we can iterate over them and
|
||||
// to easily deal with points outside the area
|
||||
Dictionary<Point, int> GetRiskLevelMap(string input)
|
||||
{
|
||||
var map = input.Split("\n");
|
||||
return new Dictionary<Point, int>(
|
||||
from y in Enumerable.Range(0, map[0].Length)
|
||||
from x in Enumerable.Range(0, map.Length)
|
||||
select new KeyValuePair<Point, int>(new Point(x, y), map[y][x] - '0')
|
||||
);
|
||||
}
|
||||
|
||||
IEnumerable<Point> Neighbours(Point point) =>
|
||||
new[] {
|
||||
point with {y = point.y + 1},
|
||||
point with {y = point.y - 1},
|
||||
point with {x = point.x + 1},
|
||||
point with {x = point.x - 1},
|
||||
};
|
||||
}
|
||||
}
|
||||
record Point(int x, int y);
|
||||
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
// A C# program for Dijkstra1's single
|
||||
// source shortest path algorithm.
|
||||
// The program is for adjacency matrix
|
||||
// representation of the graph
|
||||
|
||||
namespace Day15
|
||||
{
|
||||
class Dijkstra1
|
||||
{
|
||||
// A utility function to find the
|
||||
// vertex with minimum distance
|
||||
// value, from the set of vertices
|
||||
// not yet included in shortest
|
||||
// path tree
|
||||
static int V = 9;
|
||||
int minDistance(int[] dist,
|
||||
bool[] sptSet)
|
||||
{
|
||||
// Initialize min value
|
||||
int min = int.MaxValue, min_index = -1;
|
||||
|
||||
for (int v = 0; v < V; v++)
|
||||
if (sptSet[v] == false && dist[v] <= min)
|
||||
{
|
||||
min = dist[v];
|
||||
min_index = v;
|
||||
}
|
||||
|
||||
return min_index;
|
||||
}
|
||||
|
||||
// A utility function to print
|
||||
// the constructed distance array
|
||||
void printSolution(int[] dist, int n)
|
||||
{
|
||||
Console.Write("Vertex Distance "
|
||||
+ "from Source\n");
|
||||
for (int i = 0; i < V; i++)
|
||||
Console.Write(i + " \t\t " + dist[i] + "\n");
|
||||
}
|
||||
|
||||
// Function that implements Dijkstra1's
|
||||
// single source shortest path algorithm
|
||||
// for a graph represented using adjacency
|
||||
// matrix representation
|
||||
public void dijkstra(int[,] graph, int src)
|
||||
{
|
||||
int[] dist = new int[V]; // The output array. dist[i]
|
||||
// will hold the shortest
|
||||
// distance from src to i
|
||||
|
||||
// sptSet[i] will true if vertex
|
||||
// i is included in shortest path
|
||||
// tree or shortest distance from
|
||||
// src to i is finalized
|
||||
bool[] sptSet = new bool[V];
|
||||
|
||||
// Initialize all distances as
|
||||
// INFINITE and stpSet[] as false
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
dist[i] = int.MaxValue;
|
||||
sptSet[i] = false;
|
||||
}
|
||||
|
||||
// Distance of source vertex
|
||||
// from itself is always 0
|
||||
dist[src] = 0;
|
||||
|
||||
// Find shortest path for all vertices
|
||||
for (int count = 0; count < V - 1; count++)
|
||||
{
|
||||
// Pick the minimum distance vertex
|
||||
// from the set of vertices not yet
|
||||
// processed. u is always equal to
|
||||
// src in first iteration.
|
||||
int u = minDistance(dist, sptSet);
|
||||
|
||||
// Mark the picked vertex as processed
|
||||
sptSet[u] = true;
|
||||
|
||||
// Update dist value of the adjacent
|
||||
// vertices of the picked vertex.
|
||||
for (int v = 0; v < V; v++)
|
||||
|
||||
// Update dist[v] only if is not in
|
||||
// sptSet, there is an edge from u
|
||||
// to v, and total weight of path
|
||||
// from src to v through u is smaller
|
||||
// than current value of dist[v]
|
||||
if (!sptSet[v] && graph[u, v] != 0 &&
|
||||
dist[u] != int.MaxValue && dist[u] + graph[u, v] < dist[v])
|
||||
dist[v] = dist[u] + graph[u, v];
|
||||
}
|
||||
|
||||
// print the constructed distance array
|
||||
printSolution(dist, V);
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// public static void Main()
|
||||
// {
|
||||
// /* Let us create the example
|
||||
//graph discussed above */
|
||||
// int[,] graph = new int[,] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
|
||||
// { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
|
||||
// { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
|
||||
// { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
|
||||
// { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
|
||||
// { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
|
||||
// { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
|
||||
// { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
|
||||
// { 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
|
||||
// Dijkstra1 t = new Dijkstra1();
|
||||
// t.dijkstra(graph, 0);
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
namespace Day15
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
string[] lines = File.ReadAllLines("input.txt");
|
||||
|
||||
|
||||
Part1(lines);
|
||||
//Part2(lines);
|
||||
}
|
||||
|
||||
static void Part1(string[] lines)
|
||||
{
|
||||
Dictionary<Position, int> cavernMap = GenerateCavernMap(lines);
|
||||
|
||||
// Disjktra's algorithm
|
||||
|
||||
Position startPosition = new Position(0, 0);
|
||||
Position endPosition = new Position(cavernMap.Keys.MaxBy(p => p.x).x, cavernMap.Keys.MaxBy(p => p.y).y);
|
||||
|
||||
PriorityQueue<Position, int> priorityQueue = new PriorityQueue<Position, int>();
|
||||
Dictionary<Position, int> totalRiskMap = new Dictionary<Position, int>();
|
||||
|
||||
totalRiskMap[startPosition] = 0;
|
||||
priorityQueue.Enqueue(startPosition, 0);
|
||||
|
||||
while (priorityQueue.Count > 0)
|
||||
{
|
||||
Position position = priorityQueue.Dequeue();
|
||||
|
||||
IEnumerable<Position> nearbyPositions = GetNearbyNonDiagonalPositions(position);
|
||||
|
||||
foreach (Position nearbyPosition in nearbyPositions)
|
||||
{
|
||||
// If it's in the cavern but we haven't calculated its risk yet
|
||||
if (cavernMap.ContainsKey(nearbyPosition) && !totalRiskMap.ContainsKey(nearbyPosition))
|
||||
{
|
||||
// The total risk for this nearby position is the total risk for the current position,
|
||||
// plus the value at this nearby position
|
||||
int totalRisk = totalRiskMap[position] + cavernMap[nearbyPosition];
|
||||
totalRiskMap[nearbyPosition] = totalRisk;
|
||||
|
||||
// If we've reached the end position of the cavern, then stop
|
||||
if (nearbyPosition == endPosition)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
// Add the position to the queue
|
||||
priorityQueue.Enqueue(nearbyPosition, totalRisk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What is the lowest total risk of any path from the top left to the bottom right?
|
||||
Console.WriteLine(totalRiskMap[endPosition]);
|
||||
}
|
||||
|
||||
static IEnumerable<Position> GetNearbyNonDiagonalPositions(Position position)
|
||||
{
|
||||
return new[] {
|
||||
position with {y = position.y + 1},
|
||||
position with {y = position.y - 1},
|
||||
position with {x = position.x + 1},
|
||||
position with {x = position.x - 1},
|
||||
};
|
||||
}
|
||||
|
||||
static Dictionary<Position, int> GenerateCavernMap(string[] lines)
|
||||
{
|
||||
Dictionary<Position, int> keyValuePairs = new Dictionary<Position, int>();
|
||||
for (int x = 0; x < lines.Length; x++)
|
||||
{
|
||||
for (int y = 0; y < lines[x].Length; y++)
|
||||
{
|
||||
// TODO - why is this "lines[y][x] - '0'" rather than "lines[x][y]"
|
||||
// as I think it should be?
|
||||
keyValuePairs.Add(new Position(x, y), lines[y][x] - '0');
|
||||
}
|
||||
}
|
||||
|
||||
return keyValuePairs;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
record Position(int x, int y);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
--- Day 15: Chiton ---
|
||||
You've almost reached the exit of the cave, but the walls are getting closer together. Your submarine can barely still fit, though; the main problem is that the walls of the cave are covered in chitons, and it would be best not to bump any of them.
|
||||
|
||||
The cavern is large, but has a very low ceiling, restricting your motion to two dimensions. The shape of the cavern resembles a square; a quick scan of chiton density produces a map of risk level throughout the cave (your puzzle input). For example:
|
||||
|
||||
1163751742
|
||||
1381373672
|
||||
2136511328
|
||||
3694931569
|
||||
7463417111
|
||||
1319128137
|
||||
1359912421
|
||||
3125421639
|
||||
1293138521
|
||||
2311944581
|
||||
You start in the top left position, your destination is the bottom right position, and you cannot move diagonally. The number at each position is its risk level; to determine the total risk of an entire path, add up the risk levels of each position you enter (that is, don't count the risk level of your starting position unless you enter it; leaving it adds no risk to your total).
|
||||
|
||||
Your goal is to find a path with the lowest total risk. In this example, a path with the lowest total risk is highlighted here:
|
||||
|
||||
1163751742
|
||||
1381373672
|
||||
2136511328
|
||||
3694931569
|
||||
7463417111
|
||||
1319128137
|
||||
1359912421
|
||||
3125421639
|
||||
1293138521
|
||||
2311944581
|
||||
The total risk of this path is 40 (the starting position is never entered, so its risk is not counted).
|
||||
|
||||
What is the lowest total risk of any path from the top left to the bottom right?
|
||||
@@ -0,0 +1,10 @@
|
||||
1163751742
|
||||
1381373672
|
||||
2136511328
|
||||
3694931569
|
||||
7463417111
|
||||
1319128137
|
||||
1359912421
|
||||
3125421639
|
||||
1293138521
|
||||
2311944581
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace>_16</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="input.txt">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,148 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Day16
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
string[] lines = File.ReadAllLines("input.txt");
|
||||
|
||||
|
||||
Part1(lines);
|
||||
//Part2(lines);
|
||||
}
|
||||
|
||||
static void Part1(string[] lines)
|
||||
{
|
||||
string hex = lines[0];
|
||||
Queue<int> bitQueue = new Queue<int>();
|
||||
|
||||
for (int i = 0; i < hex.Length; i++)
|
||||
{
|
||||
// Convert each hex character into binary
|
||||
string currentHexCharacter = Convert.ToString(Convert.ToInt32(hex[i].ToString(), 16), 2);
|
||||
|
||||
// Store each bit into the list
|
||||
for (int j = 0; j < currentHexCharacter.Length; j++)
|
||||
{
|
||||
bitQueue.Enqueue(int.Parse(currentHexCharacter[j].ToString()));
|
||||
}
|
||||
}
|
||||
|
||||
List<int> versionNumbers = new List<int>();
|
||||
List<int> outputList = new List<int>();
|
||||
|
||||
HandlePacket(ref versionNumbers, ref outputList, bitQueue);
|
||||
|
||||
foreach (var item in versionNumbers)
|
||||
{
|
||||
Console.WriteLine(item);
|
||||
}
|
||||
|
||||
int total = versionNumbers.Sum(x => x);
|
||||
|
||||
Console.WriteLine($"The sum of version numbers in all packets is: {total}");
|
||||
}
|
||||
|
||||
static void HandlePacket(ref List<int> versionNumbers, ref List<int> outputList, Queue<int> bitQueue)
|
||||
{
|
||||
int packetVersion = Convert.ToInt32($"{bitQueue.Dequeue()}{bitQueue.Dequeue()}{bitQueue.Dequeue()}", 2);
|
||||
versionNumbers.Add(packetVersion);
|
||||
|
||||
int typeId = Convert.ToInt32($"{bitQueue.Dequeue()}{bitQueue.Dequeue()}{bitQueue.Dequeue()}", 2);
|
||||
|
||||
if (typeId == 4)
|
||||
{
|
||||
// Packets represent a literal value
|
||||
/*
|
||||
* Literal value packets encode a single binary number. To do this, the binary number
|
||||
* is padded with leading zeroes until its length is a multiple of four bits, and then
|
||||
* it is broken into groups of four bits. Each group is prefixed by a 1 bit except the last
|
||||
* group, which is prefixed by a 0 bit. These groups of five bits immediately follow the packet header.
|
||||
*/
|
||||
StringBuilder binaryLiteral = new StringBuilder();
|
||||
bool isEndOfPacket = false;
|
||||
|
||||
while (!isEndOfPacket)
|
||||
{
|
||||
int endOfPacketIdentifier = bitQueue.Dequeue();
|
||||
|
||||
binaryLiteral.Append($"{bitQueue.Dequeue()}{bitQueue.Dequeue()}{bitQueue.Dequeue()}{bitQueue.Dequeue()}");
|
||||
|
||||
if (endOfPacketIdentifier == 0)
|
||||
{
|
||||
// last group, end of packet
|
||||
isEndOfPacket = true;
|
||||
}
|
||||
}
|
||||
|
||||
string binaryLiteralString = binaryLiteral.ToString();
|
||||
int output = Convert.ToInt32(binaryLiteralString, 2);
|
||||
|
||||
outputList.Add(output);
|
||||
|
||||
// if the unprocessed binary doesn't just contain zeros process it again
|
||||
if (bitQueue.Count >= 11 && bitQueue.Any(b => (b != 0)))
|
||||
{
|
||||
HandlePacket(ref versionNumbers, ref outputList, bitQueue);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Packets represent an operator
|
||||
int lengthTypeId = bitQueue.Dequeue();
|
||||
|
||||
if (lengthTypeId == 0)
|
||||
{
|
||||
// the next _15_ bits are a number that represents the _total length in bits_ of the
|
||||
// sub-packets contained by this packet.
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for (int i = 0; i < 15 && bitQueue.Count > 0; i++)
|
||||
{
|
||||
sb.Append(bitQueue.Dequeue());
|
||||
}
|
||||
|
||||
int totalLengthInBitsOfSubPacketsContainedByThisPacket = Convert.ToInt32(sb.ToString(), 2);
|
||||
|
||||
|
||||
Queue<int> newBitQueue = new Queue<int>();
|
||||
|
||||
for (int i = 0; i < totalLengthInBitsOfSubPacketsContainedByThisPacket && bitQueue.Count > 0; i++)
|
||||
{
|
||||
newBitQueue.Enqueue(bitQueue.Dequeue());
|
||||
}
|
||||
|
||||
if (bitQueue.Count >= 11)
|
||||
{
|
||||
HandlePacket(ref versionNumbers, ref outputList, newBitQueue);
|
||||
}
|
||||
}
|
||||
else if (lengthTypeId == 1)
|
||||
{
|
||||
// the next _11_ bits are a number that represents the _number of sub-packets
|
||||
// immediately contained_ by this packet.
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for (int i = 0; i < 11 && bitQueue.Count > 0; i++)
|
||||
{
|
||||
sb.Append(bitQueue.Dequeue());
|
||||
}
|
||||
|
||||
int numberOfSubPacketsImmediatelyContainedByThisPacket = Convert.ToInt32(sb.ToString(), 2);
|
||||
|
||||
// TODO - I can't see how I can even use this information
|
||||
|
||||
if (bitQueue.Count >= 11)
|
||||
{
|
||||
HandlePacket(ref versionNumbers, ref outputList, bitQueue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
--- Day 16: Packet Decoder ---
|
||||
As you leave the cave and reach open waters, you receive a transmission from the Elves back on the ship.
|
||||
|
||||
The transmission was sent using the Buoyancy Interchange Transmission System (BITS), a method of packing numeric expressions into a binary sequence. Your submarine's computer has saved the transmission in hexadecimal (your puzzle input).
|
||||
|
||||
The first step of decoding the message is to convert the hexadecimal representation into binary. Each character of hexadecimal corresponds to four bits of binary data:
|
||||
|
||||
0 = 0000
|
||||
1 = 0001
|
||||
2 = 0010
|
||||
3 = 0011
|
||||
4 = 0100
|
||||
5 = 0101
|
||||
6 = 0110
|
||||
7 = 0111
|
||||
8 = 1000
|
||||
9 = 1001
|
||||
A = 1010
|
||||
B = 1011
|
||||
C = 1100
|
||||
D = 1101
|
||||
E = 1110
|
||||
F = 1111
|
||||
The BITS transmission contains a single packet at its outermost layer which itself contains many other packets. The hexadecimal representation of this packet might encode a few extra 0 bits at the end; these are not part of the transmission and should be ignored.
|
||||
|
||||
Every packet begins with a standard header: the first three bits encode the packet version, and the next three bits encode the packet type ID. These two values are numbers; all numbers encoded in any packet are represented as binary with the most significant bit first. For example, a version encoded as the binary sequence 100 represents the number 4.
|
||||
|
||||
Packets with type ID 4 represent a literal value. Literal value packets encode a single binary number. To do this, the binary number is padded with leading zeroes until its length is a multiple of four bits, and then it is broken into groups of four bits. Each group is prefixed by a 1 bit except the last group, which is prefixed by a 0 bit. These groups of five bits immediately follow the packet header. For example, the hexadecimal string D2FE28 becomes:
|
||||
|
||||
110100101111111000101000
|
||||
VVVTTTAAAAABBBBBCCCCC
|
||||
Below each bit is a label indicating its purpose:
|
||||
|
||||
The three bits labeled V (110) are the packet version, 6.
|
||||
The three bits labeled T (100) are the packet type ID, 4, which means the packet is a literal value.
|
||||
The five bits labeled A (10111) start with a 1 (not the last group, keep reading) and contain the first four bits of the number, 0111.
|
||||
The five bits labeled B (11110) start with a 1 (not the last group, keep reading) and contain four more bits of the number, 1110.
|
||||
The five bits labeled C (00101) start with a 0 (last group, end of packet) and contain the last four bits of the number, 0101.
|
||||
The three unlabeled 0 bits at the end are extra due to the hexadecimal representation and should be ignored.
|
||||
So, this packet represents a literal value with binary representation 011111100101, which is 2021 in decimal.
|
||||
|
||||
Every other type of packet (any packet with a type ID other than 4) represent an operator that performs some calculation on one or more sub-packets contained within. Right now, the specific operations aren't important; focus on parsing the hierarchy of sub-packets.
|
||||
|
||||
An operator packet contains one or more packets. To indicate which subsequent binary data represents its sub-packets, an operator packet can use one of two modes indicated by the bit immediately after the packet header; this is called the length type ID:
|
||||
|
||||
If the length type ID is 0, then the next 15 bits are a number that represents the total length in bits of the sub-packets contained by this packet.
|
||||
If the length type ID is 1, then the next 11 bits are a number that represents the number of sub-packets immediately contained by this packet.
|
||||
Finally, after the length type ID bit and the 15-bit or 11-bit field, the sub-packets appear.
|
||||
|
||||
For example, here is an operator packet (hexadecimal string 38006F45291200) with length type ID 0 that contains two sub-packets:
|
||||
|
||||
00111000000000000110111101000101001010010001001000000000
|
||||
VVVTTTILLLLLLLLLLLLLLLAAAAAAAAAAABBBBBBBBBBBBBBBB
|
||||
The three bits labeled V (001) are the packet version, 1.
|
||||
The three bits labeled T (110) are the packet type ID, 6, which means the packet is an operator.
|
||||
The bit labeled I (0) is the length type ID, which indicates that the length is a 15-bit number representing the number of bits in the sub-packets.
|
||||
The 15 bits labeled L (000000000011011) contain the length of the sub-packets in bits, 27.
|
||||
The 11 bits labeled A contain the first sub-packet, a literal value representing the number 10.
|
||||
The 16 bits labeled B contain the second sub-packet, a literal value representing the number 20.
|
||||
After reading 11 and 16 bits of sub-packet data, the total length indicated in L (27) is reached, and so parsing of this packet stops.
|
||||
|
||||
As another example, here is an operator packet (hexadecimal string EE00D40C823060) with length type ID 1 that contains three sub-packets:
|
||||
|
||||
11101110000000001101010000001100100000100011000001100000
|
||||
VVVTTTILLLLLLLLLLLAAAAAAAAAAABBBBBBBBBBBCCCCCCCCCCC
|
||||
The three bits labeled V (111) are the packet version, 7.
|
||||
The three bits labeled T (011) are the packet type ID, 3, which means the packet is an operator.
|
||||
The bit labeled I (1) is the length type ID, which indicates that the length is a 11-bit number representing the number of sub-packets.
|
||||
The 11 bits labeled L (00000000011) contain the number of sub-packets, 3.
|
||||
The 11 bits labeled A contain the first sub-packet, a literal value representing the number 1.
|
||||
The 11 bits labeled B contain the second sub-packet, a literal value representing the number 2.
|
||||
The 11 bits labeled C contain the third sub-packet, a literal value representing the number 3.
|
||||
After reading 3 complete sub-packets, the number of sub-packets indicated in L (3) is reached, and so parsing of this packet stops.
|
||||
|
||||
For now, parse the hierarchy of the packets throughout the transmission and add up all of the version numbers.
|
||||
|
||||
Here are a few more examples of hexadecimal-encoded transmissions:
|
||||
|
||||
8A004A801A8002F478 represents an operator packet (version 4) which contains an operator packet (version 1) which contains an operator packet (version 5) which contains a literal value (version 6); this packet has a version sum of 16.
|
||||
620080001611562C8802118E34 represents an operator packet (version 3) which contains two sub-packets; each sub-packet is an operator packet that contains two literal values. This packet has a version sum of 12.
|
||||
C0015000016115A2E0802F182340 has the same structure as the previous example, but the outermost packet uses a different length type ID. This packet has a version sum of 23.
|
||||
A0016C880162017C3686B18A3D4780 is an operator packet that contains an operator packet that contains an operator packet that contains five literal values; it has a version sum of 31.
|
||||
Decode the structure of your hexadecimal-encoded BITS transmission; what do you get if you add up the version numbers in all packets?
|
||||
@@ -0,0 +1 @@
|
||||
EE00D40C823060
|
||||
@@ -0,0 +1,103 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.31912.275
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "09", "09\09.csproj", "{3434EEFA-329E-4398-82CE-61E87D4268AA}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "08", "08\08.csproj", "{0C10174A-B7DA-4EC1-B07C-3478C5946982}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "07", "07\07.csproj", "{81818D41-936E-419A-A536-5D6466C2F1FA}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "06", "06\06.csproj", "{4A7D4D49-874F-4259-90A5-52287F5FD040}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "05", "05\05.csproj", "{F1A149E1-D97A-4843-8673-AB01E5378438}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "04", "04\04.csproj", "{219CC077-10DE-4ABE-B6AB-E09178A8D1DF}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "03", "03\03.csproj", "{5CC48EA7-CCFA-4E6E-BE4E-51D6DD1C4060}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "02", "02\02.csproj", "{D38BFDE7-01EF-4248-AF6C-A4587EF72726}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "01", "01\01.csproj", "{58C837E5-8A6F-4794-80DC-D056B8665586}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "10", "10\10.csproj", "{C9300285-27F4-4BC9-98D3-158BD66E7859}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "11", "11\11.csproj", "{6F13298E-B8CA-4A67-B1E7-320B5637CE6A}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "14", "14\14.csproj", "{9F9653A8-5A92-40C3-A855-7D0F0EAEC422}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "15", "15\15.csproj", "{55BCEE74-A9E1-4506-B068-B25E7B9EA6ED}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "16", "16\16.csproj", "{692919B1-7363-4E0C-83C7-8367F819FA4F}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{3434EEFA-329E-4398-82CE-61E87D4268AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{3434EEFA-329E-4398-82CE-61E87D4268AA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{3434EEFA-329E-4398-82CE-61E87D4268AA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{3434EEFA-329E-4398-82CE-61E87D4268AA}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{0C10174A-B7DA-4EC1-B07C-3478C5946982}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0C10174A-B7DA-4EC1-B07C-3478C5946982}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0C10174A-B7DA-4EC1-B07C-3478C5946982}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0C10174A-B7DA-4EC1-B07C-3478C5946982}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{81818D41-936E-419A-A536-5D6466C2F1FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{81818D41-936E-419A-A536-5D6466C2F1FA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{81818D41-936E-419A-A536-5D6466C2F1FA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{81818D41-936E-419A-A536-5D6466C2F1FA}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{4A7D4D49-874F-4259-90A5-52287F5FD040}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{4A7D4D49-874F-4259-90A5-52287F5FD040}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{4A7D4D49-874F-4259-90A5-52287F5FD040}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{4A7D4D49-874F-4259-90A5-52287F5FD040}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F1A149E1-D97A-4843-8673-AB01E5378438}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F1A149E1-D97A-4843-8673-AB01E5378438}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F1A149E1-D97A-4843-8673-AB01E5378438}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F1A149E1-D97A-4843-8673-AB01E5378438}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{219CC077-10DE-4ABE-B6AB-E09178A8D1DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{219CC077-10DE-4ABE-B6AB-E09178A8D1DF}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{219CC077-10DE-4ABE-B6AB-E09178A8D1DF}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{219CC077-10DE-4ABE-B6AB-E09178A8D1DF}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5CC48EA7-CCFA-4E6E-BE4E-51D6DD1C4060}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5CC48EA7-CCFA-4E6E-BE4E-51D6DD1C4060}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5CC48EA7-CCFA-4E6E-BE4E-51D6DD1C4060}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5CC48EA7-CCFA-4E6E-BE4E-51D6DD1C4060}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D38BFDE7-01EF-4248-AF6C-A4587EF72726}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D38BFDE7-01EF-4248-AF6C-A4587EF72726}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D38BFDE7-01EF-4248-AF6C-A4587EF72726}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D38BFDE7-01EF-4248-AF6C-A4587EF72726}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{58C837E5-8A6F-4794-80DC-D056B8665586}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{58C837E5-8A6F-4794-80DC-D056B8665586}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{58C837E5-8A6F-4794-80DC-D056B8665586}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{58C837E5-8A6F-4794-80DC-D056B8665586}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C9300285-27F4-4BC9-98D3-158BD66E7859}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C9300285-27F4-4BC9-98D3-158BD66E7859}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C9300285-27F4-4BC9-98D3-158BD66E7859}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C9300285-27F4-4BC9-98D3-158BD66E7859}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{6F13298E-B8CA-4A67-B1E7-320B5637CE6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{6F13298E-B8CA-4A67-B1E7-320B5637CE6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{6F13298E-B8CA-4A67-B1E7-320B5637CE6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{6F13298E-B8CA-4A67-B1E7-320B5637CE6A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9F9653A8-5A92-40C3-A855-7D0F0EAEC422}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9F9653A8-5A92-40C3-A855-7D0F0EAEC422}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9F9653A8-5A92-40C3-A855-7D0F0EAEC422}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9F9653A8-5A92-40C3-A855-7D0F0EAEC422}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{55BCEE74-A9E1-4506-B068-B25E7B9EA6ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{55BCEE74-A9E1-4506-B068-B25E7B9EA6ED}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{55BCEE74-A9E1-4506-B068-B25E7B9EA6ED}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{55BCEE74-A9E1-4506-B068-B25E7B9EA6ED}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{692919B1-7363-4E0C-83C7-8367F819FA4F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{692919B1-7363-4E0C-83C7-8367F819FA4F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{692919B1-7363-4E0C-83C7-8367F819FA4F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{692919B1-7363-4E0C-83C7-8367F819FA4F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {B04ADD1F-ADDF-4D40-91EE-8D7DFCC99E33}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
Reference in New Issue
Block a user