Code cleanup

This commit is contained in:
2023-12-02 18:27:00 +01:00
parent 4d8bfbb377
commit 4b3d0fd0b6
78 changed files with 6814 additions and 6950 deletions

View File

@@ -1,8 +1,8 @@
using System;
namespace AdventOfCode2020
{
/*
namespace AdventOfCode2020;
/*
--- Day 1: Report Repair ---
After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island. Surely, Christmas will go on without you.
@@ -41,49 +41,48 @@ In your expense report, what is the product of the three entries that sum to 202
*/
public class Day01 : IDay
*/
public class Day01 : IDay
{
public string ResolvePart1(string[] inputs)
{
public string ResolvePart1(string[] inputs)
int result = -1;
for (int i = 0; i < (inputs.Length - 1) && result < 0; i++)
{
int result = -1;
for (int i = 0; i < (inputs.Length - 1) && result < 0; i++)
for (int j = i + 1; j < inputs.Length && result < 0; j++)
{
for (int j = i + 1; j < inputs.Length && result < 0; j++)
if (string.IsNullOrEmpty(inputs[i]) || string.IsNullOrEmpty(inputs[j])) { continue; }
int numI = Convert.ToInt32(inputs[i]);
int numJ = Convert.ToInt32(inputs[j]);
if ((numI + numJ) == 2020)
{
if (string.IsNullOrEmpty(inputs[i]) || string.IsNullOrEmpty(inputs[j])) { continue; }
int numI = Convert.ToInt32(inputs[i]);
int numJ = Convert.ToInt32(inputs[j]);
if ((numI + numJ) == 2020)
{
result = numI * numJ;
}
result = numI * numJ;
}
}
return result.ToString();
}
public string ResolvePart2(string[] inputs)
{
long result = -1;
for (int i = 0; i < (inputs.Length - 2) && result < 0; i++)
{
for (int j = i + 1; j < (inputs.Length - 1) && result < 0; j++)
{
for (int k = j + 1; k < inputs.Length && result < 0; k++)
{
if (string.IsNullOrEmpty(inputs[i]) || string.IsNullOrEmpty(inputs[j]) || string.IsNullOrEmpty(inputs[k])) { continue; }
long numI = Convert.ToInt64(inputs[i]);
long numJ = Convert.ToInt64(inputs[j]);
long numK = Convert.ToInt64(inputs[k]);
if ((numI + numJ + numK) == 2020)
{
result = numI * numJ * numK;
}
}
}
}
return result.ToString();
}
return result.ToString();
}
}
public string ResolvePart2(string[] inputs)
{
long result = -1;
for (int i = 0; i < (inputs.Length - 2) && result < 0; i++)
{
for (int j = i + 1; j < (inputs.Length - 1) && result < 0; j++)
{
for (int k = j + 1; k < inputs.Length && result < 0; k++)
{
if (string.IsNullOrEmpty(inputs[i]) || string.IsNullOrEmpty(inputs[j]) || string.IsNullOrEmpty(inputs[k])) { continue; }
long numI = Convert.ToInt64(inputs[i]);
long numJ = Convert.ToInt64(inputs[j]);
long numK = Convert.ToInt64(inputs[k]);
if ((numI + numJ + numK) == 2020)
{
result = numI * numJ * numK;
}
}
}
}
return result.ToString();
}
}

View File

@@ -1,9 +1,8 @@
using System;
using System.Linq;
namespace AdventOfCode2020
{
/*
namespace AdventOfCode2020;
/*
--- Day 2: Password Philosophy ---
Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan.
@@ -36,57 +35,56 @@ Each policy actually describes two positions in the password, where 1 means the
Given the same example list from above:
1-3 a: abcde is valid: position 1 contains a and position 3 does not.
1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.
2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.
1-3 a: abcde is valid: position 1 contains a and position 3 does not.
1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.
2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.
How many passwords are valid according to the new interpretation of the policies?
*/
*/
public class Day02 : IDay
public class Day02 : IDay
{
public string ResolvePart1(string[] inputs)
{
public string ResolvePart1(string[] inputs)
int cntValid = 0;
foreach (string input in inputs)
{
int cntValid = 0;
foreach (string input in inputs)
{
if (string.IsNullOrEmpty(input)) { continue; }
string[] parts = input.Split('-', ' ', ':');
int min = Convert.ToInt32(parts[0]);
int max = Convert.ToInt32(parts[1]);
string character = parts[2];
string password = parts[4];
int cnt = password.Count(c => c == character[0]);
if (cnt <= max && cnt >= min) { cntValid++; }
}
return cntValid.ToString();
if (string.IsNullOrEmpty(input)) { continue; }
string[] parts = input.Split('-', ' ', ':');
int min = Convert.ToInt32(parts[0]);
int max = Convert.ToInt32(parts[1]);
string character = parts[2];
string password = parts[4];
int cnt = password.Count(c => c == character[0]);
if (cnt <= max && cnt >= min) { cntValid++; }
}
public string ResolvePart2(string[] inputs)
{
int cntValid = 0;
foreach (string input in inputs)
{
if (string.IsNullOrEmpty(input)) { continue; }
string[] parts = input.Split('-', ' ', ':');
int index0 = Convert.ToInt32(parts[0]);
int index1 = Convert.ToInt32(parts[1]);
string character = parts[2];
string password = parts[4];
if (password.Length < index0 || password.Length < index1) { continue; }
bool hasIndex0 = (password[index0 - 1] == character[0]);
bool hasIndex1 = (password[index1 - 1] == character[0]);
if ((hasIndex0 && hasIndex1) || (hasIndex0 == false && hasIndex1 == false)) { continue; }
if (hasIndex0 || hasIndex1) { cntValid++; }
}
return cntValid.ToString();
}
return cntValid.ToString();
}
}
public string ResolvePart2(string[] inputs)
{
int cntValid = 0;
foreach (string input in inputs)
{
if (string.IsNullOrEmpty(input)) { continue; }
string[] parts = input.Split('-', ' ', ':');
int index0 = Convert.ToInt32(parts[0]);
int index1 = Convert.ToInt32(parts[1]);
string character = parts[2];
string password = parts[4];
if (password.Length < index0 || password.Length < index1) { continue; }
bool hasIndex0 = (password[index0 - 1] == character[0]);
bool hasIndex1 = (password[index1 - 1] == character[0]);
if ((hasIndex0 && hasIndex1) || (hasIndex0 == false && hasIndex1 == false)) { continue; }
if (hasIndex0 || hasIndex1) { cntValid++; }
}
return cntValid.ToString();
}
}

View File

@@ -74,44 +74,43 @@ What do you get if you multiply together the number of trees encountered on each
*/
namespace AdventOfCode2020
namespace AdventOfCode2020;
public class Day03 : IDay
{
public class Day03 : IDay
public string ResolvePart1(string[] inputs)
{
public string ResolvePart1(string[] inputs)
{
int treeCnt = FollowSlope(inputs, 3, 1);
return treeCnt.ToString();
}
int treeCnt = FollowSlope(inputs, 3, 1);
return treeCnt.ToString();
}
public string ResolvePart2(string[] inputs)
{
int treeCnt1 = FollowSlope(inputs, 1, 1);
int treeCnt2 = FollowSlope(inputs, 3, 1);
int treeCnt3 = FollowSlope(inputs, 5, 1);
int treeCnt4 = FollowSlope(inputs, 7, 1);
int treeCnt5 = FollowSlope(inputs, 1, 2);
long treeMult = treeCnt1 * treeCnt2 * treeCnt3 * treeCnt4 * treeCnt5;
return treeMult.ToString();
}
public string ResolvePart2(string[] inputs)
{
int treeCnt1 = FollowSlope(inputs, 1, 1);
int treeCnt2 = FollowSlope(inputs, 3, 1);
int treeCnt3 = FollowSlope(inputs, 5, 1);
int treeCnt4 = FollowSlope(inputs, 7, 1);
int treeCnt5 = FollowSlope(inputs, 1, 2);
long treeMult = treeCnt1 * treeCnt2 * treeCnt3 * treeCnt4 * treeCnt5;
return treeMult.ToString();
}
private static int FollowSlope(string[] inputs, int dx, int dy)
private static int FollowSlope(string[] inputs, int dx, int dy)
{
int x = 0;
int y = 0;
int treeCnt = 0;
x += dx;
y += dy;
while (y < inputs.Length)
{
int x = 0;
int y = 0;
int treeCnt = 0;
string input = inputs[y];
char c = input[x % input.Length];
if (c == '#') { treeCnt++; }
x += dx;
y += dy;
while (y < inputs.Length)
{
string input = inputs[y];
char c = input[x % input.Length];
if (c == '#') { treeCnt++; }
x += dx;
y += dy;
}
return treeCnt;
}
return treeCnt;
}
}
}

View File

@@ -124,145 +124,143 @@ Count the number of valid passports - those that have all required fields and va
*/
namespace AdventOfCode2020
namespace AdventOfCode2020;
public class Day04 : IDay
{
public class Day04 : IDay
public string ResolvePart1(string[] inputs)
{
public string ResolvePart1(string[] inputs)
{
List<Dictionary<string, string>> passports = Passports_Parse(inputs);
int cnt = 0;
List<string> neededFields = new List<string>
{
"byr", // Birth Year
"iyr", // Issue Year
"eyr", // Expiration Year
"hgt", // Height
"hcl", // Hair Color
"ecl", // Eye Color
"pid", // Passport ID
};
List<Dictionary<string, string>> passports = Passports_Parse(inputs);
int cnt = 0;
List<string> neededFields = new() {
"byr", // Birth Year
"iyr", // Issue Year
"eyr", // Expiration Year
"hgt", // Height
"hcl", // Hair Color
"ecl", // Eye Color
"pid", // Passport ID
};
foreach (Dictionary<string, string> passport in passports)
{
bool valid = true;
foreach (string field in neededFields)
{
if (passport.ContainsKey(field) == false)
{
valid = false;
break;
}
}
if (valid) { cnt++; }
}
return cnt.ToString();
}
public string ResolvePart2(string[] inputs)
foreach (Dictionary<string, string> passport in passports)
{
List<Dictionary<string, string>> passports = Passports_Parse(inputs);
int cnt = 0;
foreach (Dictionary<string, string> passport in passports)
bool valid = true;
foreach (string field in neededFields)
{
if (Passport_Validate(passport) == false) { continue; }
cnt++;
}
return cnt.ToString();
}
private List<Dictionary<string, string>> Passports_Parse(string[] inputs)
{
List<Dictionary<string, string>> passports = new List<Dictionary<string, string>>();
Dictionary<string, string> passport = new Dictionary<string, string>();
foreach (string input in inputs)
{
if (string.IsNullOrEmpty(input))
if (passport.ContainsKey(field) == false)
{
if (passport.Count > 0)
{
passports.Add(passport);
passport = new Dictionary<string, string>();
}
continue;
}
string[] pairs = input.Split(' ');
foreach (string pair in pairs)
{
string[] data = pair.Split(':');
if (passport.ContainsKey(data[0]))
{
passport[data[0]] = data[1];
}
else
{
passport.Add(data[0], data[1]);
}
valid = false;
break;
}
}
if (passport.Count > 0)
{
passports.Add(passport);
}
return passports;
if (valid) { cnt++; }
}
private bool Passport_Validate(Dictionary<string, string> passport)
{
if (passport.ContainsKey("byr") == false) { return false; }
int? birthYear = Year_Parse(passport["byr"]);
if (birthYear == null || birthYear < 1920 || birthYear > 2002) { return false; }
if (passport.ContainsKey("iyr") == false) { return false; }
int? issueYear = Year_Parse(passport["iyr"]);
if (issueYear == null || issueYear < 2010 || issueYear > 2020) { return false; }
if (passport.ContainsKey("eyr") == false) { return false; }
int? expirationYear = Year_Parse(passport["eyr"]);
if (expirationYear == null || expirationYear < 2020 || expirationYear > 2030) { return false; }
if (passport.ContainsKey("hgt") == false) { return false; }
string strHeight = passport["hgt"];
if (strHeight.EndsWith("cm"))
{
string strHeightCm = strHeight.Substring(0, strHeight.Length - 2);
if (strHeightCm.All(char.IsNumber) == false) { return false; }
int heightCm = Convert.ToInt32(strHeightCm);
if (heightCm < 150 || heightCm > 193) { return false; }
}
else if (strHeight.EndsWith("in"))
{
string strHeightIn = strHeight.Substring(0, strHeight.Length - 2);
if (strHeightIn.All(char.IsNumber) == false) { return false; }
int heightIn = Convert.ToInt32(strHeightIn);
if (heightIn < 59 || heightIn > 76) { return false; }
}
else { return false; }
if (passport.ContainsKey("hcl") == false) { return false; }
string strHairColor = passport["hcl"];
if (strHairColor.StartsWith("#") == false) { return false; }
string strHairColorHex = strHairColor.Substring(1);
if (strHairColorHex.All(c => char.IsNumber(c) || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) == false) { return false; }
if (passport.ContainsKey("ecl") == false) { return false; }
string strEyeColor = passport["ecl"];
if (strEyeColor != "amb" && strEyeColor != "blu" && strEyeColor != "brn" && strEyeColor != "gry" && strEyeColor != "grn" && strEyeColor != "hzl" && strEyeColor != "oth") { return false; }
if (passport.ContainsKey("pid") == false) { return false; }
string strPassportID = passport["pid"];
if (strPassportID.Length != 9) { return false; }
if (strPassportID.All(char.IsNumber) == false) { return false; }
return true;
}
private int? Year_Parse(string input)
{
if (input.Length != 4) { return null; }
if (input.All(char.IsNumber) == false) { return null; }
return Convert.ToInt32(input);
}
return cnt.ToString();
}
}
public string ResolvePart2(string[] inputs)
{
List<Dictionary<string, string>> passports = Passports_Parse(inputs);
int cnt = 0;
foreach (Dictionary<string, string> passport in passports)
{
if (Passport_Validate(passport) == false) { continue; }
cnt++;
}
return cnt.ToString();
}
private List<Dictionary<string, string>> Passports_Parse(string[] inputs)
{
List<Dictionary<string, string>> passports = new();
Dictionary<string, string> passport = new();
foreach (string input in inputs)
{
if (string.IsNullOrEmpty(input))
{
if (passport.Count > 0)
{
passports.Add(passport);
passport = new Dictionary<string, string>();
}
continue;
}
string[] pairs = input.Split(' ');
foreach (string pair in pairs)
{
string[] data = pair.Split(':');
if (passport.ContainsKey(data[0]))
{
passport[data[0]] = data[1];
}
else
{
passport.Add(data[0], data[1]);
}
}
}
if (passport.Count > 0)
{
passports.Add(passport);
}
return passports;
}
private bool Passport_Validate(Dictionary<string, string> passport)
{
if (passport.ContainsKey("byr") == false) { return false; }
int? birthYear = Year_Parse(passport["byr"]);
if (birthYear == null || birthYear < 1920 || birthYear > 2002) { return false; }
if (passport.ContainsKey("iyr") == false) { return false; }
int? issueYear = Year_Parse(passport["iyr"]);
if (issueYear == null || issueYear < 2010 || issueYear > 2020) { return false; }
if (passport.ContainsKey("eyr") == false) { return false; }
int? expirationYear = Year_Parse(passport["eyr"]);
if (expirationYear == null || expirationYear < 2020 || expirationYear > 2030) { return false; }
if (passport.ContainsKey("hgt") == false) { return false; }
string strHeight = passport["hgt"];
if (strHeight.EndsWith("cm"))
{
string strHeightCm = strHeight.Substring(0, strHeight.Length - 2);
if (strHeightCm.All(char.IsNumber) == false) { return false; }
int heightCm = Convert.ToInt32(strHeightCm);
if (heightCm < 150 || heightCm > 193) { return false; }
}
else if (strHeight.EndsWith("in"))
{
string strHeightIn = strHeight.Substring(0, strHeight.Length - 2);
if (strHeightIn.All(char.IsNumber) == false) { return false; }
int heightIn = Convert.ToInt32(strHeightIn);
if (heightIn < 59 || heightIn > 76) { return false; }
}
else { return false; }
if (passport.ContainsKey("hcl") == false) { return false; }
string strHairColor = passport["hcl"];
if (strHairColor.StartsWith("#") == false) { return false; }
string strHairColorHex = strHairColor.Substring(1);
if (strHairColorHex.All(c => char.IsNumber(c) || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) == false) { return false; }
if (passport.ContainsKey("ecl") == false) { return false; }
string strEyeColor = passport["ecl"];
if (strEyeColor != "amb" && strEyeColor != "blu" && strEyeColor != "brn" && strEyeColor != "gry" && strEyeColor != "grn" && strEyeColor != "hzl" && strEyeColor != "oth") { return false; }
if (passport.ContainsKey("pid") == false) { return false; }
string strPassportID = passport["pid"];
if (strPassportID.Length != 9) { return false; }
if (strPassportID.All(char.IsNumber) == false) { return false; }
return true;
}
private int? Year_Parse(string input)
{
if (input.Length != 4) { return null; }
if (input.All(char.IsNumber) == false) { return null; }
return Convert.ToInt32(input);
}
}

View File

@@ -59,156 +59,155 @@ What is the ID of your seat?
using System;
using System.Linq;
namespace AdventOfCode2020
namespace AdventOfCode2020;
public class Day05 : IDay
{
public class Day05 : IDay
public string ResolvePart1(string[] inputs)
{
public string ResolvePart1(string[] inputs)
int maxSerialNumber = 0;
foreach (string input in inputs)
{
int maxSerialNumber = 0;
foreach (string input in inputs)
{
Seat seat = Seat_Parse(input);
if (seat == null) { continue; }
int newSerialNumber = seat.GetSerialNumber();
if (newSerialNumber > maxSerialNumber) { maxSerialNumber = newSerialNumber; }
}
return maxSerialNumber.ToString();
Seat seat = Seat_Parse(input);
if (seat == null) { continue; }
int newSerialNumber = seat.GetSerialNumber();
if (newSerialNumber > maxSerialNumber) { maxSerialNumber = newSerialNumber; }
}
return maxSerialNumber.ToString();
}
public string ResolvePart2(string[] inputs)
{
// Fill the seats
char[][] seats = new char[8][];
for (int i = 0; i < 8; i++)
{
seats[i] = new char[128];
for (int j = 0; j < 128; j++) { seats[i][j] = '.'; }
}
foreach (string input in inputs)
{
Seat seat = Seat_Parse(input);
if (seat == null) { continue; }
seats[seat.Column][seat.Row] = 'X';
}
public string ResolvePart2(string[] inputs)
// Show seats
for (int i = 0; i < 8; i++)
{
// Fill the seats
char[][] seats = new char[8][];
for (int i = 0; i < 8; i++)
for (int j = 0; j < 128; j++)
{
seats[i] = new char[128];
for (int j = 0; j < 128; j++) { seats[i][j] = '.'; }
Console.Write(seats[i][j]);
}
foreach (string input in inputs)
{
Seat seat = Seat_Parse(input);
if (seat == null) { continue; }
Console.WriteLine();
}
seats[seat.Column][seat.Row] = 'X';
}
// Show seats
for (int i = 0; i < 8; i++)
// Find my seat
int mySeatSerialNumber = -1;
for (int i = 0; i < 8 && mySeatSerialNumber < 0; i++)
{
for (int j = 0; j < 128 && mySeatSerialNumber < 0; j++)
{
for (int j = 0; j < 128; j++)
if (seats[i][j] == '.')
{
Console.Write(seats[i][j]);
}
Console.WriteLine();
}
// Find my seat
int mySeatSerialNumber = -1;
for (int i = 0; i < 8 && mySeatSerialNumber < 0; i++)
{
for (int j = 0; j < 128 && mySeatSerialNumber < 0; j++)
{
if (seats[i][j] == '.')
int neighbourCount = 0;
for (int k = -1; k < 2; k++)
{
int neighbourCount = 0;
for (int k = -1; k < 2; k++)
for (int l = -1; l < 2; l++)
{
for (int l = -1; l < 2; l++)
int col = (i + k);
if (col < 0) { col += 8; }
if (col >= 8) { col -= 8; }
int row = (j + l);
if (row < 0) { row += 128; }
if (row >= 128) { row -= 128; }
if (seats[col][row] == 'X')
{
int col = (i + k);
if (col < 0) { col += 8; }
if (col >= 8) { col -= 8; }
int row = (j + l);
if (row < 0) { row += 128; }
if (row >= 128) { row -= 128; }
if (seats[col][row] == 'X')
{
neighbourCount++;
}
neighbourCount++;
}
}
if (neighbourCount == 8)
{
Seat mySeat = new Seat { Row = j, Column = i, };
mySeatSerialNumber = mySeat.GetSerialNumber();
}
}
if (neighbourCount == 8)
{
Seat mySeat = new() { Row = j, Column = i, };
mySeatSerialNumber = mySeat.GetSerialNumber();
}
}
}
return mySeatSerialNumber.ToString();
}
return mySeatSerialNumber.ToString();
}
private class Range
{
public int Start { get; set; }
public int End { get; set; }
public void SplitLeft()
{
int len = End - Start;
int half = (len + 1) / 2;
End -= half;
}
private class Range
public void SplitRight()
{
public int Start { get; set; }
public int End { get; set; }
public void SplitLeft()
{
int len = End - Start;
int half = (len + 1) / 2;
End -= half;
}
public void SplitRight()
{
int len = End - Start;
int half = (len + 1) / 2;
Start += half;
}
}
private class Seat
{
public int Row { get; set; }
public int Column { get; set; }
public int GetSerialNumber()
{
return (Row * 8) + Column;
}
}
private Seat Seat_Parse(string input)
{
if (input.Length != 10 ||
input.All(c => c == 'F' || c == 'B' || c == 'L' || c == 'R') == false ||
false)
{
return null;
}
Seat seat = new Seat();
Range row = new Range { Start = 0, End = 127, };
for (int i = 0; i < 7; i++)
{
if (input[i] == 'F')
{
row.SplitLeft();
}
if (input[i] == 'B')
{
row.SplitRight();
}
}
seat.Row = row.Start;
Range column = new Range { Start = 0, End = 7, };
for (int i = 7; i < 10; i++)
{
if (input[i] == 'L')
{
column.SplitLeft();
}
if (input[i] == 'R')
{
column.SplitRight();
}
}
seat.Column = column.Start;
return seat;
int len = End - Start;
int half = (len + 1) / 2;
Start += half;
}
}
}
private class Seat
{
public int Row { get; set; }
public int Column { get; set; }
public int GetSerialNumber()
{
return (Row * 8) + Column;
}
}
private Seat Seat_Parse(string input)
{
if (input.Length != 10 ||
input.All(c => c == 'F' || c == 'B' || c == 'L' || c == 'R') == false ||
false)
{
return null;
}
Seat seat = new();
Range row = new() { Start = 0, End = 127, };
for (int i = 0; i < 7; i++)
{
if (input[i] == 'F')
{
row.SplitLeft();
}
if (input[i] == 'B')
{
row.SplitRight();
}
}
seat.Row = row.Start;
Range column = new() { Start = 0, End = 7, };
for (int i = 7; i < 10; i++)
{
if (input[i] == 'L')
{
column.SplitLeft();
}
if (input[i] == 'R')
{
column.SplitRight();
}
}
seat.Column = column.Start;
return seat;
}
}

View File

@@ -52,79 +52,78 @@ For each group, count the number of questions to which anyone answered "yes". Wh
*/
namespace AdventOfCode2020
{
public class Day06 : IDay
{
public string ResolvePart1(string[] inputs)
{
Dictionary<char, bool> groupMap = new Dictionary<char, bool>();
List<Dictionary<char, bool>> groupMaps = new List<Dictionary<char, bool>>();
foreach (string input in inputs)
{
if (string.IsNullOrEmpty(input) && groupMap.Count > 0)
{
groupMaps.Add(groupMap);
groupMap = new Dictionary<char, bool>();
continue;
}
namespace AdventOfCode2020;
foreach (char c in input)
{
if (groupMap.ContainsKey(c) == false)
{
groupMap.Add(c, true);
}
}
}
if (groupMap.Count > 0)
public class Day06 : IDay
{
public string ResolvePart1(string[] inputs)
{
Dictionary<char, bool> groupMap = new();
List<Dictionary<char, bool>> groupMaps = new();
foreach (string input in inputs)
{
if (string.IsNullOrEmpty(input) && groupMap.Count > 0)
{
groupMaps.Add(groupMap);
groupMap = new Dictionary<char, bool>();
continue;
}
int total = groupMaps.Sum(groupMap => groupMap.Count);
return total.ToString();
foreach (char c in input)
{
if (groupMap.ContainsKey(c) == false)
{
groupMap.Add(c, true);
}
}
}
if (groupMap.Count > 0)
{
groupMaps.Add(groupMap);
}
public string ResolvePart2(string[] inputs)
{
int groupCount = 0;
Dictionary<char, int> groupMap = new Dictionary<char, int>();
List<Tuple<int, Dictionary<char, int>>> groupMaps = new List<Tuple<int, Dictionary<char, int>>>();
foreach (string input in inputs)
{
if (string.IsNullOrEmpty(input) && groupCount > 0)
{
groupMaps.Add(new Tuple<int, Dictionary<char, int>>(groupCount, groupMap));
groupCount = 0;
groupMap = new Dictionary<char, int>();
continue;
}
int total = groupMaps.Sum(groupMap => groupMap.Count);
return total.ToString();
groupCount++;
foreach (char c in input)
{
if (groupMap.ContainsKey(c) == false)
{
groupMap.Add(c, 1);
}
else
{
groupMap[c] = groupMap[c] + 1;
}
}
}
if (groupCount > 0)
}
public string ResolvePart2(string[] inputs)
{
int groupCount = 0;
Dictionary<char, int> groupMap = new();
List<Tuple<int, Dictionary<char, int>>> groupMaps = new();
foreach (string input in inputs)
{
if (string.IsNullOrEmpty(input) && groupCount > 0)
{
groupMaps.Add(new Tuple<int, Dictionary<char, int>>(groupCount, groupMap));
groupCount = 0;
groupMap = new Dictionary<char, int>();
continue;
}
int total = groupMaps.Sum(group =>
groupCount++;
foreach (char c in input)
{
return group.Item2.Count(p => p.Value == group.Item1);
});
return total.ToString();
if (groupMap.ContainsKey(c) == false)
{
groupMap.Add(c, 1);
}
else
{
groupMap[c] = groupMap[c] + 1;
}
}
}
if (groupCount > 0)
{
groupMaps.Add(new Tuple<int, Dictionary<char, int>>(groupCount, groupMap));
}
int total = groupMaps.Sum(group =>
{
return group.Item2.Count(p => p.Value == group.Item1);
});
return total.ToString();
}
}
}

View File

@@ -68,140 +68,139 @@ How many individual bags are required inside your single shiny gold bag?
*/
namespace AdventOfCode2020
namespace AdventOfCode2020;
public class Day07 : IDay
{
public class Day07 : IDay
public string ResolvePart1(string[] inputs)
{
public string ResolvePart1(string[] inputs)
string myBagColor = "shiny gold";
List<BaggageRule> rules = new();
foreach (string input in inputs)
{
string myBagColor = "shiny gold";
BaggageRule rule = BaggageRule_Parse(input);
rules.Add(rule);
}
List<BaggageRule> rules = new List<BaggageRule>();
foreach (string input in inputs)
List<string> bagColorsToCheck = new() { myBagColor };
List<string> bagColorsChecked = new() { myBagColor };
int cntBagColors = 0;
while (bagColorsToCheck.Count > 0)
{
string currentColor = bagColorsToCheck[0];
bagColorsToCheck.RemoveAt(0);
foreach (BaggageRule rule in rules)
{
BaggageRule rule = BaggageRule_Parse(input);
rules.Add(rule);
}
List<string> bagColorsToCheck = new List<string> { myBagColor };
List<string> bagColorsChecked = new List<string> { myBagColor };
int cntBagColors = 0;
while (bagColorsToCheck.Count > 0)
{
string currentColor = bagColorsToCheck[0];
bagColorsToCheck.RemoveAt(0);
foreach (BaggageRule rule in rules)
if (rule.Contain.Any(r => r.BagColor == currentColor))
{
if (rule.Contain.Any(r => r.BagColor == currentColor))
if (bagColorsChecked.Contains(rule.BagColor) == false)
{
if (bagColorsChecked.Contains(rule.BagColor) == false)
{
bagColorsToCheck.Add(rule.BagColor);
bagColorsChecked.Add(rule.BagColor);
cntBagColors++;
}
bagColorsToCheck.Add(rule.BagColor);
bagColorsChecked.Add(rule.BagColor);
cntBagColors++;
}
}
}
return cntBagColors.ToString();
}
public string ResolvePart2(string[] inputs)
{
string myBagColor = "shiny gold";
List<BaggageRule> rules = new List<BaggageRule>();
foreach (string input in inputs)
{
BaggageRule rule = BaggageRule_Parse(input);
rules.Add(rule);
}
Dictionary<string, BaggageRule> dictRules = rules.ToDictionary(x => x.BagColor);
int cnt = BaggageRule_CountChilds(myBagColor, dictRules);
return cnt.ToString();
}
public class BaggageContainRule
{
public string BagColor { get; set; }
public int Count { get; set; }
}
public class BaggageRule
{
public string BagColor { get; set; }
public List<BaggageContainRule> Contain { get; set; }
}
public BaggageRule BaggageRule_Parse(string input)
{
string[] words = input.Split(' ');
string status = "Parse Color 1";
BaggageRule rule = new BaggageRule();
rule.Contain = new List<BaggageContainRule>();
BaggageContainRule containRule = null;
string color1 = string.Empty;
foreach (string word in words)
{
switch (status)
{
case "Parse Color 1":
color1 = word;
status = "Parse Color 2";
break;
case "Parse Color 2":
rule.BagColor = string.Concat(color1, " ", word);
status = "Expect bags";
break;
case "Expect bags":
if (word != "bags") { throw new Exception("Expecting bags"); }
status = "Expect contain";
break;
case "Expect contain":
if (word != "contain") { throw new Exception("Expecting contain"); }
status = "Parse Contain count";
break;
case "Parse Contain count":
if (word == "no") { status = "End"; break; }
containRule = new BaggageContainRule();
containRule.Count = Convert.ToInt32(word);
status = "Parse Contain color 1";
break;
case "Parse Contain color 1":
color1 = word;
status = "Parse Contain color 2";
break;
case "Parse Contain color 2":
containRule.BagColor = string.Concat(color1, " ", word);
rule.Contain.Add(containRule);
status = "Parse Contain continue";
break;
case "Parse Contain continue":
if (word == "bag," || word == "bags,") { status = "Parse Contain count"; break; }
status = "End";
break;
case "End":
break;
}
}
return rule;
}
public int BaggageRule_CountChilds(string color, Dictionary<string, BaggageRule> dictRules)
{
int cnt = 0;
BaggageRule rule = dictRules[color];
foreach (BaggageContainRule containRule in rule.Contain)
{
cnt += (BaggageRule_CountChilds(containRule.BagColor, dictRules) + 1) * containRule.Count;
}
return cnt;
}
return cntBagColors.ToString();
}
}
public string ResolvePart2(string[] inputs)
{
string myBagColor = "shiny gold";
List<BaggageRule> rules = new();
foreach (string input in inputs)
{
BaggageRule rule = BaggageRule_Parse(input);
rules.Add(rule);
}
Dictionary<string, BaggageRule> dictRules = rules.ToDictionary(x => x.BagColor);
int cnt = BaggageRule_CountChilds(myBagColor, dictRules);
return cnt.ToString();
}
public class BaggageContainRule
{
public string BagColor { get; set; }
public int Count { get; set; }
}
public class BaggageRule
{
public string BagColor { get; set; }
public List<BaggageContainRule> Contain { get; set; }
}
public BaggageRule BaggageRule_Parse(string input)
{
string[] words = input.Split(' ');
string status = "Parse Color 1";
BaggageRule rule = new();
rule.Contain = new List<BaggageContainRule>();
BaggageContainRule containRule = null;
string color1 = string.Empty;
foreach (string word in words)
{
switch (status)
{
case "Parse Color 1":
color1 = word;
status = "Parse Color 2";
break;
case "Parse Color 2":
rule.BagColor = string.Concat(color1, " ", word);
status = "Expect bags";
break;
case "Expect bags":
if (word != "bags") { throw new Exception("Expecting bags"); }
status = "Expect contain";
break;
case "Expect contain":
if (word != "contain") { throw new Exception("Expecting contain"); }
status = "Parse Contain count";
break;
case "Parse Contain count":
if (word == "no") { status = "End"; break; }
containRule = new BaggageContainRule();
containRule.Count = Convert.ToInt32(word);
status = "Parse Contain color 1";
break;
case "Parse Contain color 1":
color1 = word;
status = "Parse Contain color 2";
break;
case "Parse Contain color 2":
containRule.BagColor = string.Concat(color1, " ", word);
rule.Contain.Add(containRule);
status = "Parse Contain continue";
break;
case "Parse Contain continue":
if (word == "bag," || word == "bags,") { status = "Parse Contain count"; break; }
status = "End";
break;
case "End":
break;
}
}
return rule;
}
public int BaggageRule_CountChilds(string color, Dictionary<string, BaggageRule> dictRules)
{
int cnt = 0;
BaggageRule rule = dictRules[color];
foreach (BaggageContainRule containRule in rule.Contain)
{
cnt += (BaggageRule_CountChilds(containRule.BagColor, dictRules) + 1) * containRule.Count;
}
return cnt;
}
}

View File

@@ -93,137 +93,136 @@ Fix the program so that it terminates normally by changing exactly one jmp (to n
*/
namespace AdventOfCode2020
namespace AdventOfCode2020;
public class Day08 : IDay
{
public class Day08 : IDay
public string ResolvePart1(string[] inputs)
{
public string ResolvePart1(string[] inputs)
{
VM vm = new VM(inputs);
vm.Run();
return vm.Accumulator.ToString();
}
VM vm = new(inputs);
vm.Run();
return vm.Accumulator.ToString();
}
public string ResolvePart2(string[] inputs)
public string ResolvePart2(string[] inputs)
{
VM vm = new(inputs);
foreach (Instruction instruction in vm.Instructions)
{
VM vm = new VM(inputs);
foreach (Instruction instruction in vm.Instructions)
if (instruction.OpCode == OpCode.Acc) { continue; }
if (instruction.OpCode == OpCode.Nop)
{
if (instruction.OpCode == OpCode.Acc) { continue; }
if (instruction.OpCode == OpCode.Nop)
{
instruction.OpCode = OpCode.Jmp;
vm.Run();
if (vm.Ended) { break; }
instruction.OpCode = OpCode.Nop;
}
if (instruction.OpCode == OpCode.Jmp)
{
instruction.OpCode = OpCode.Nop;
vm.Run();
if (vm.Ended) { break; }
instruction.OpCode = OpCode.Jmp;
}
instruction.OpCode = OpCode.Jmp;
vm.Run();
if (vm.Ended) { break; }
instruction.OpCode = OpCode.Nop;
}
return vm.Accumulator.ToString();
}
public enum OpCode
{
Acc,
Jmp,
Nop,
};
public class Instruction
{
public OpCode OpCode { get; set; }
public int Value { get; set; }
public bool Executed { get; set; }
public Instruction(string input)
if (instruction.OpCode == OpCode.Jmp)
{
string[] parts = input.Split(' ');
if (parts[0] == "acc")
{
OpCode = OpCode.Acc;
}
if (parts[0] == "jmp")
{
OpCode = OpCode.Jmp;
}
if (parts[0] == "nop")
{
OpCode = OpCode.Nop;
}
if (parts[1].StartsWith("+"))
{
Value = Convert.ToInt32(parts[1].Substring(1));
}
else
{
Value = Convert.ToInt32(parts[1]);
}
Executed = false;
instruction.OpCode = OpCode.Nop;
vm.Run();
if (vm.Ended) { break; }
instruction.OpCode = OpCode.Jmp;
}
}
return vm.Accumulator.ToString();
}
public class VM
public enum OpCode
{
Acc,
Jmp,
Nop,
}
public class Instruction
{
public OpCode OpCode { get; set; }
public int Value { get; set; }
public bool Executed { get; set; }
public Instruction(string input)
{
public List<Instruction> Instructions { get; set; }
string[] parts = input.Split(' ');
public int Accumulator { get; set; }
public bool Ended { get; set; }
public VM(string[] inputs)
if (parts[0] == "acc")
{
Instructions = new List<Instruction>();
foreach (string input in inputs)
{
Instructions.Add(new Instruction(input));
}
Accumulator = 0;
Ended = false;
OpCode = OpCode.Acc;
}
if (parts[0] == "jmp")
{
OpCode = OpCode.Jmp;
}
if (parts[0] == "nop")
{
OpCode = OpCode.Nop;
}
public void Run()
if (parts[1].StartsWith("+"))
{
foreach (Instruction instruction in Instructions)
Value = Convert.ToInt32(parts[1].Substring(1));
}
else
{
Value = Convert.ToInt32(parts[1]);
}
Executed = false;
}
}
private class VM
{
public List<Instruction> Instructions { get; set; }
public int Accumulator { get; set; }
public bool Ended { get; set; }
public VM(string[] inputs)
{
Instructions = new List<Instruction>();
foreach (string input in inputs)
{
Instructions.Add(new Instruction(input));
}
Accumulator = 0;
Ended = false;
}
public void Run()
{
foreach (Instruction instruction in Instructions)
{
instruction.Executed = false;
}
Ended = false;
Accumulator = 0;
int idx = 0;
while (Instructions[idx].Executed == false)
{
Instruction currentInstruction = Instructions[idx];
if (currentInstruction.OpCode == OpCode.Acc)
{
instruction.Executed = false;
Accumulator += currentInstruction.Value;
currentInstruction.Executed = true;
idx++;
}
Ended = false;
Accumulator = 0;
int idx = 0;
while (Instructions[idx].Executed == false)
if (currentInstruction.OpCode == OpCode.Jmp)
{
Instruction currentInstruction = Instructions[idx];
if (currentInstruction.OpCode == OpCode.Acc)
{
Accumulator += currentInstruction.Value;
currentInstruction.Executed = true;
idx++;
}
if (currentInstruction.OpCode == OpCode.Jmp)
{
currentInstruction.Executed = true;
idx += currentInstruction.Value;
}
if (currentInstruction.OpCode == OpCode.Nop)
{
currentInstruction.Executed = true;
idx++;
}
if (idx >= Instructions.Count)
{
Ended = true;
break;
}
currentInstruction.Executed = true;
idx += currentInstruction.Value;
}
if (currentInstruction.OpCode == OpCode.Nop)
{
currentInstruction.Executed = true;
idx++;
}
if (idx >= Instructions.Count)
{
Ended = true;
break;
}
}
}
}
}
}

View File

@@ -91,83 +91,82 @@ What is the encryption weakness in your XMAS-encrypted list of numbers?
*/
namespace AdventOfCode2020
namespace AdventOfCode2020;
public class Day09 : IDay
{
public class Day09 : IDay
public string ResolvePart1(string[] inputs)
{
public string ResolvePart1(string[] inputs)
int preamble = 25;
if (inputs.Length < preamble) { preamble = 5; }
List<long> numbers = inputs.Select(x => Convert.ToInt64(x)).ToList();
int firstInvalid = XMAS_FindFirstInvalid(preamble, numbers);
return numbers[firstInvalid].ToString();
}
public string ResolvePart2(string[] inputs)
{
int preamble = 25;
if (inputs.Length < preamble) { preamble = 5; }
List<long> numbers = inputs.Select(x => Convert.ToInt64(x)).ToList();
int firstInvalid = XMAS_FindFirstInvalid(preamble, numbers);
long numberInvalid = numbers[firstInvalid];
long numberChecksum = -1;
bool found = false;
for (int i = firstInvalid - 1; i > 0 && found == false; i--)
{
int preamble = 25;
if (inputs.Length < preamble) { preamble = 5; }
List<long> numbers = inputs.Select(x => Convert.ToInt64(x)).ToList();
int firstInvalid = XMAS_FindFirstInvalid(preamble, numbers);
return numbers[firstInvalid].ToString();
}
public string ResolvePart2(string[] inputs)
{
int preamble = 25;
if (inputs.Length < preamble) { preamble = 5; }
List<long> numbers = inputs.Select(x => Convert.ToInt64(x)).ToList();
int firstInvalid = XMAS_FindFirstInvalid(preamble, numbers);
long numberInvalid = numbers[firstInvalid];
long numberChecksum = -1;
bool found = false;
for (int i = firstInvalid - 1; i > 0 && found == false; i--)
long sum = numbers[i];
long max = numbers[i];
long min = numbers[i];
for (int j = (i - 1); j >= 0 && found == false; j--)
{
long sum = numbers[i];
long max = numbers[i];
long min = numbers[i];
for (int j = (i - 1); j >= 0 && found == false; j--)
sum += numbers[j];
if (numbers[j] > max) { max = numbers[j]; }
if (numbers[j] < min) { min = numbers[j]; }
if (sum == numberInvalid)
{
sum += numbers[j];
if (numbers[j] > max) { max = numbers[j]; }
if (numbers[j] < min) { min = numbers[j]; }
if (sum == numberInvalid)
{
found = true;
numberChecksum = max + min;
}
if (sum > numberInvalid)
{
break;
}
found = true;
numberChecksum = max + min;
}
}
return numberChecksum.ToString();
}
private static int XMAS_FindFirstInvalid(int preamble, List<long> numbers)
{
int firstInvalid = -1;
for (int i = preamble; i < numbers.Count; i++)
{
bool valid = false;
long number = numbers[i];
for (int j = (i - preamble); j < (i - 1) && valid == false; j++)
if (sum > numberInvalid)
{
for (int k = (j + 1); k < i && valid == false; k++)
{
long sum = numbers[j] + numbers[k];
if (sum == number)
{
valid = true;
}
}
}
if (valid == false)
{
firstInvalid = i;
break;
}
}
return firstInvalid;
}
return numberChecksum.ToString();
}
}
private static int XMAS_FindFirstInvalid(int preamble, List<long> numbers)
{
int firstInvalid = -1;
for (int i = preamble; i < numbers.Count; i++)
{
bool valid = false;
long number = numbers[i];
for (int j = (i - preamble); j < (i - 1) && valid == false; j++)
{
for (int k = (j + 1); k < i && valid == false; k++)
{
long sum = numbers[j] + numbers[k];
if (sum == number)
{
valid = true;
}
}
}
if (valid == false)
{
firstInvalid = i;
break;
}
}
return firstInvalid;
}
}

View File

@@ -91,18 +91,17 @@ Find a chain that uses all of your adapters to connect the charging outlet to yo
*/
namespace AdventOfCode2020
{
public class Day10 : IDay
{
public string ResolvePart1(string[] inputs)
{
throw new NotImplementedException();
}
namespace AdventOfCode2020;
public string ResolvePart2(string[] inputs)
{
throw new NotImplementedException();
}
public class Day10 : IDay
{
public string ResolvePart1(string[] inputs)
{
throw new NotImplementedException();
}
}
public string ResolvePart2(string[] inputs)
{
throw new NotImplementedException();
}
}

View File

@@ -7,18 +7,17 @@
*/
namespace AdventOfCode2020
{
public class Day11 : IDay
{
public string ResolvePart1(string[] inputs)
{
throw new NotImplementedException();
}
namespace AdventOfCode2020;
public string ResolvePart2(string[] inputs)
{
throw new NotImplementedException();
}
public class Day11 : IDay
{
public string ResolvePart1(string[] inputs)
{
throw new NotImplementedException();
}
}
public string ResolvePart2(string[] inputs)
{
throw new NotImplementedException();
}
}

View File

@@ -1,8 +1,7 @@
namespace AdventOfCode2020
namespace AdventOfCode2020;
public interface IDay
{
public interface IDay
{
string ResolvePart1(string[] inputs);
string ResolvePart2(string[] inputs);
}
}
string ResolvePart1(string[] inputs);
string ResolvePart2(string[] inputs);
}

View File

@@ -1,66 +1,65 @@
using System;
using System.IO;
namespace AdventOfCode2020
namespace AdventOfCode2020;
class Program
{
class Program
static void Main()
{
static void Main(string[] args)
int currentDayNumber = 0;
DateTime date = DateTime.UtcNow.AddHours(-5);
if (date.Month == 12 && currentDayNumber == 0)
{
int currentDayNumber = 0;
DateTime date = DateTime.UtcNow.AddHours(-5);
if (date.Month == 12 && currentDayNumber == 0)
{
currentDayNumber = date.Day;
}
RunDay(currentDayNumber);
Console.Read();
currentDayNumber = date.Day;
}
public static void RunDay(int currentDayNumber)
RunDay(currentDayNumber);
Console.Read();
}
public static void RunDay(int currentDayNumber)
{
Console.WriteLine($"Day {currentDayNumber:00}");
Console.WriteLine("------");
Console.WriteLine();
IDay currentDay = null;
Type dayType = Type.GetType($"AdventOfCode2020.Day{currentDayNumber:00}");
if (dayType != null)
{
Console.WriteLine(string.Format("Day {0:00}", currentDayNumber));
Console.WriteLine("------");
Console.WriteLine();
currentDay = Activator.CreateInstance(dayType) as IDay;
}
if (currentDay == null)
{
Console.WriteLine("!!!!!!!");
Console.WriteLine("Day implementation not found.");
return;
}
IDay currentDay = null;
Type dayType = Type.GetType(string.Format("AdventOfCode2020.Day{0:00}", currentDayNumber));
if (dayType != null)
{
currentDay = Activator.CreateInstance(dayType) as IDay;
}
if (currentDay == null)
{
Console.WriteLine("!!!!!!!");
Console.WriteLine("Day implementation not found.");
return;
}
string[] linesDay = File.ReadAllLines(string.Format("inputs/Day{0:00}.txt", currentDayNumber));
try
{
string resultPart1 = currentDay.ResolvePart1(linesDay);
Console.WriteLine("Day{1:00} Result Part1: {0}", resultPart1, currentDayNumber);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
try
{
string resultPart2 = currentDay.ResolvePart2(linesDay);
Console.WriteLine("Day{1:00} Result Part2: {0}", resultPart2, currentDayNumber);
}
catch (Exception ex)
{
Console.WriteLine("!!!!!!!");
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
string[] linesDay = File.ReadAllLines($"inputs/Day{currentDayNumber:00}.txt");
try
{
string resultPart1 = currentDay.ResolvePart1(linesDay);
Console.WriteLine("Day{1:00} Result Part1: {0}", resultPart1, currentDayNumber);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
try
{
string resultPart2 = currentDay.ResolvePart2(linesDay);
Console.WriteLine("Day{1:00} Result Part2: {0}", resultPart2, currentDayNumber);
}
catch (Exception ex)
{
Console.WriteLine("!!!!!!!");
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
}
}