102 lines
No EOL
2.4 KiB
C#
102 lines
No EOL
2.4 KiB
C#
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(',');
|
|
} |