feat: Add day 2
This commit is contained in:
parent
d0f5e65015
commit
6e5b0fcf60
3 changed files with 104 additions and 0 deletions
102
AdventOfCode2026/Day2.cs
Normal file
102
AdventOfCode2026/Day2.cs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
namespace AdventOfCode2026;
|
||||
|
||||
public class Day2 : Solution
|
||||
{
|
||||
public override string SolvePart1()
|
||||
{
|
||||
return InputReader
|
||||
.ReadLines(2)
|
||||
.SelectMany(ToRanges)
|
||||
.Select(ToLimit)
|
||||
.SelectMany(GetIds)
|
||||
.Where(id => IsTwiceSequence(id.ToString()))
|
||||
.Sum()
|
||||
.ToString();
|
||||
}
|
||||
|
||||
public override string SolvePart2()
|
||||
{
|
||||
return InputReader
|
||||
.ReadLines(2)
|
||||
.SelectMany(ToRanges)
|
||||
.Select(ToLimit)
|
||||
.SelectMany(GetIds)
|
||||
.Where(id => IsTwiceOrMoreSequence(id.ToString()))
|
||||
.Sum()
|
||||
.ToString();
|
||||
}
|
||||
|
||||
private static IEnumerable<long> GetIds((string from, string to) limit) => GetIds(limit.from, limit.to);
|
||||
|
||||
private static IEnumerable<long> GetIds(string from, string to)
|
||||
{
|
||||
var current = long.Parse(from);
|
||||
var end = long.Parse(to);
|
||||
while (current <= end)
|
||||
{
|
||||
yield return current;
|
||||
current++;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsTwiceOrMoreSequence(string input)
|
||||
{
|
||||
if (input.Length < 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var subLength = 1; subLength <= input.Length / 2; subLength++)
|
||||
{
|
||||
if (input.Length % subLength != 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var testBlock = input[..subLength];
|
||||
var theoreticalString = string.Concat(Enumerable.Repeat(testBlock, input.Length / subLength));
|
||||
if (theoreticalString == input)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsTwiceSequence(string input)
|
||||
{
|
||||
if (input.Length < 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (input.Length % 2 != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var firstHalfIndex = 0;
|
||||
var secondHalfIndex = input.Length / 2;
|
||||
while (secondHalfIndex < input.Length)
|
||||
{
|
||||
if (input[firstHalfIndex] != input[secondHalfIndex])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
firstHalfIndex++;
|
||||
secondHalfIndex++;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static (string from, string to) ToLimit(string range)
|
||||
{
|
||||
var parts = range.Split('-');
|
||||
return (parts[0], parts[1]);
|
||||
}
|
||||
|
||||
private static IEnumerable<string> ToRanges(string line) => line.Split(',');
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue