Last active
December 2, 2018 09:26
-
-
Save jyarbro/01b1c0f8f1f746c2c2aefdbd242f465a to your computer and use it in GitHub Desktop.
Advent of Code 2018 Day 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Day2_2018 { | |
const string INPUTFILE = @"2018\day2.txt"; | |
public void Part1() { | |
var input = File.ReadAllLines(INPUTFILE); | |
var twos = 0; | |
var threes = 0; | |
foreach (var line in input) { | |
var letters = line.ToCharArray(); | |
var hasTwo = false; | |
var hasThree = false; | |
for (var charCode = 97; charCode <= 122; charCode++) { | |
var charCount = letters.Count(letter => letter == charCode); | |
if (charCount == 2 && !hasTwo) { | |
twos++; | |
hasTwo = true; | |
} | |
if (charCount == 3 && !hasThree) { | |
threes++; | |
hasThree = true; | |
} | |
} | |
} | |
Console.WriteLine($"{twos} x {threes} = {twos * threes}"); | |
} | |
public void Part2() { | |
var input = File.ReadAllLines(INPUTFILE); | |
var sets = new List<char[]>(); | |
foreach (var line in input) { | |
sets.Add(line.ToCharArray()); | |
} | |
var winner = string.Empty; | |
while (winner == string.Empty && sets.Any()) { | |
var nextLine = sets.First(); | |
winner = RecursiveCheckSet(0, nextLine, sets); | |
sets.Remove(nextLine); | |
} | |
Console.WriteLine(winner); | |
} | |
string RecursiveCheckSet(int index, char[] set, List<char[]> sets, int difference = -1) { | |
// we have a winner! | |
if (index == set.Count()) { | |
return StringWithoutDroppedChar(set, difference); | |
} | |
var similarSets = sets.Where(otherSet => otherSet[index] == set[index]).ToList(); | |
// We found a different character | |
if (similarSets.Count() == 1) { | |
// This is the first different character, so give it another chance. | |
if (difference < 0 && sets.Count > 1) { | |
difference = index; | |
similarSets = sets; | |
} | |
else { | |
return string.Empty; | |
} | |
} | |
index++; | |
return RecursiveCheckSet(index, set, similarSets, difference); | |
} | |
string StringWithoutDroppedChar(char[] set, int dropped) { | |
var returnValue = string.Empty; | |
for (var i = 0; i < set.Count(); i++) { | |
if (i != dropped) { | |
returnValue += set[i]; | |
} | |
} | |
return returnValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment