2021aoc/Day20.cs

84 lines
2.3 KiB
C#

// #define Day20
#if Day20
using AoC2021;
var lines = File.ReadAllLines("day20/input");
var translate = lines[0].Select(c => c == '#' ? "1" : "0").ToList();
int steps = 50;
int size = lines.Length - 2;
string[,] image = new string[size + 4,size + 4];
lines.Skip(2).ForEachIndex((l, row) =>
l.ForEachIndex((c, col) => image[row + 2, col + 2] = c == '#' ? "1" : "0"));
string infinite = "0";
SetBorder(image, infinite);
// Print(image);
while (steps > 0) {
size = image.GetLength(0);
string[,] nextImage = new string[size + 2,size + 2];
for (int row = 1; row < size-1; row++) {
for (int col = 1; col < size-1; col++) {
nextImage[row + 1, col + 1] = GetNewPoint(row, col, image);
}
}
infinite = NextInfinite(infinite);
SetBorder(nextImage, infinite);
image = nextImage;
// Print(image);
// Console.WriteLine();
steps--;
}
int count = 0;
for (int row = 0; row < image.GetLength(0); row++) {
for (int col = 0; col < image.GetLength(1); col++) {
if (image[row, col] == "1") {
count++;
}
}
}
Console.WriteLine(count);
void Print(string[,] image) {
for (int row = 0; row < image.GetLength(0); row++) {
for (int col = 0; col < image.GetLength(1); col++) {
Console.Write(image[row, col] == "1" ? '#' : '.');
}
Console.WriteLine();
}
}
string GetNewPoint(int row, int col, string[,] imageToRead) {
var binary = imageToRead[row - 1, col - 1] + imageToRead[row - 1, col] + imageToRead[row - 1, col + 1]
+ imageToRead[row, col - 1] + imageToRead[row, col] + imageToRead[row, col + 1]
+ imageToRead[row + 1, col - 1] + imageToRead[row + 1, col] + imageToRead[row + 1, col + 1];
return translate[Convert.ToInt32(binary, 2)];
}
string NextInfinite(string infinite) {
var infinitePos = Convert.ToInt32(String.Join("",Enumerable.Repeat(infinite, 9)), 2);
return translate[infinitePos];
}
void SetBorder(string[,] image, string value) {
int last = image.GetLength(0) - 1;
Enumerable.Range(0, image.GetLength(0)).ForEachAsList(i => {
image[0, i] = value;
image[1, i] = value;
image[i, 0] = value;
image[i, 1] = value;
image[last, i] = value;
image[last-1, i] = value;
image[i, last] = value;
image[i, last-1] = value;
});
}
#endif