From 184c3ede8bddb620e7da07341a72ac692a8925ab Mon Sep 17 00:00:00 2001 From: Ben Harris Date: Wed, 4 Dec 2019 11:32:43 -0500 Subject: [PATCH] day 4 --- Day4.cs | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++ DayFactory.cs | 3 ++- aoc2019.csproj | 3 +++ input/day4.in | 1 + 4 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 Day4.cs create mode 100644 input/day4.in diff --git a/Day4.cs b/Day4.cs new file mode 100644 index 0000000..8e57b00 --- /dev/null +++ b/Day4.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace aoc2019 +{ + internal class Day4 : Day + { + int start, end; + + public Day4() + { + var range = File.ReadLines("input/day4.in") + .First() + .Split('-') + .Select(i => int.Parse(i)) + .ToList(); + + start = range[0]; end = range[1]; + } + + private bool IsValid(int i) + { + return Math.Floor(Math.Log10(i) + 1) == 6 + && i >= start + && i <= end + && IsIncreasingDigits(i); + } + + private bool IsIncreasingDigits(int i) + { + int prev = 0; + bool hasDup = false; + foreach (var c in i.ToString()) + { + int curr = c - '0'; + if (curr < prev) + return false; + if (curr == prev) + hasDup = true; + prev = curr; + } + return hasDup; + } + + private bool Part2Criterion(int i) + { + var s = i.ToString(); + return s.Select(c => s.Count(j => j == c)).Any(c => c == 2); + } + + public override void Part1() + { + Console.WriteLine(Enumerable.Range(start, end).Count(i => IsValid(i))); + } + + public override void Part2() + { + Console.WriteLine(Enumerable.Range(start,end).Count(i => IsValid(i) && Part2Criterion(i))); + } + } +} diff --git a/DayFactory.cs b/DayFactory.cs index 5938d75..0a05ecb 100644 --- a/DayFactory.cs +++ b/DayFactory.cs @@ -11,8 +11,9 @@ namespace aoc2019 case 1: return new Day1(); case 2: return new Day2(); case 3: return new Day3(); + case 4: return new Day4(); default: return null; } } } -} \ No newline at end of file +} diff --git a/aoc2019.csproj b/aoc2019.csproj index f45d1e6..1533700 100644 --- a/aoc2019.csproj +++ b/aoc2019.csproj @@ -15,6 +15,9 @@ Always + + Always + diff --git a/input/day4.in b/input/day4.in new file mode 100644 index 0000000..6190bcb --- /dev/null +++ b/input/day4.in @@ -0,0 +1 @@ +245318-765747