93 lines
2.6 KiB
C#
93 lines
2.6 KiB
C#
|
namespace AdventOfCode2022.Handlers
|
||
|
{
|
||
|
public class Day03
|
||
|
{
|
||
|
string[] letters = new string[] {};
|
||
|
string[] rucksack = new string[] {};
|
||
|
public Day03()
|
||
|
{
|
||
|
rucksack = File.ReadAllText(@"./days/03/input").Trim().Split("\n");
|
||
|
|
||
|
// a-z
|
||
|
for (var i = 97; i <= 122; i++)
|
||
|
{
|
||
|
letters = letters.Append(((char)i).ToString()).ToArray();
|
||
|
}
|
||
|
|
||
|
// A-Z
|
||
|
for (var i = 65; i <= 90; i++)
|
||
|
{
|
||
|
letters = letters.Append(((char)i).ToString()).ToArray();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public int GetLetterPriority(string letter)
|
||
|
{
|
||
|
return Array.IndexOf(letters, letter) + 1;
|
||
|
}
|
||
|
|
||
|
public void PartA()
|
||
|
{
|
||
|
var sum = 0;
|
||
|
foreach (var line in rucksack)
|
||
|
{
|
||
|
var lineLength = line.Length;
|
||
|
var halfPoint = lineLength / 2;
|
||
|
var partOne = line.Substring(0, halfPoint);
|
||
|
var partTwo = line.Substring(halfPoint);
|
||
|
|
||
|
var firstParts = partOne.ToArray();
|
||
|
var secondParts = partTwo.ToArray();
|
||
|
var diffLetter = "";
|
||
|
|
||
|
foreach (var letter in firstParts)
|
||
|
{
|
||
|
if (secondParts.Contains(letter))
|
||
|
{
|
||
|
diffLetter = letter.ToString();
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (diffLetter == "")
|
||
|
{
|
||
|
Console.WriteLine("No diff letter found");
|
||
|
}
|
||
|
|
||
|
sum += GetLetterPriority(diffLetter);
|
||
|
}
|
||
|
|
||
|
Console.WriteLine($"Part A: {sum}");
|
||
|
}
|
||
|
|
||
|
public void PartB()
|
||
|
{
|
||
|
var groups = rucksack.Chunk(3);
|
||
|
var sum = 0;
|
||
|
foreach (var group in groups)
|
||
|
{
|
||
|
var firstSackLetters = group[0];
|
||
|
var commonLetter = "";
|
||
|
foreach (var ch in firstSackLetters)
|
||
|
{
|
||
|
var letter = Convert.ToString(ch);
|
||
|
var exists = group.All(x => x.Contains(letter));
|
||
|
if (exists)
|
||
|
{
|
||
|
commonLetter = letter;
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (commonLetter == "")
|
||
|
{
|
||
|
Console.WriteLine("No common letter found");
|
||
|
}
|
||
|
|
||
|
sum += GetLetterPriority(commonLetter);
|
||
|
}
|
||
|
|
||
|
Console.WriteLine($"Part B: {sum}");
|
||
|
}
|
||
|
}
|
||
|
}
|