64 lines
2.1 KiB
C#
64 lines
2.1 KiB
C#
using AdventOfCode.Core.Shared.IO;
|
|
using System;
|
|
using System.Reflection;
|
|
|
|
namespace AdventOfCode.Solutions._2024
|
|
{
|
|
public class Day02 : IChallange
|
|
{
|
|
public int Year => 2024;
|
|
public int Day => 2;
|
|
|
|
private readonly IInputReader _inputReader;
|
|
|
|
public Day02(IInputReader inputReader)
|
|
{
|
|
_inputReader = inputReader;
|
|
_inputReader.SetInput(this);
|
|
}
|
|
|
|
//2
|
|
//230
|
|
public async Task<string> GetSolutionPart1()
|
|
=> (await _inputReader.ReadAsArrayString())
|
|
.Select(ParselineToReports)
|
|
.Where(reports => AreReportsSave(reports, false))
|
|
.Count()
|
|
.ToString();
|
|
|
|
//4
|
|
//301
|
|
public async Task<string> GetSolutionPart2() => (await _inputReader.ReadAsArrayString())
|
|
.Select(ParselineToReports)
|
|
.Where(reports => AreReportsSave(reports, true))
|
|
.Count()
|
|
.ToString();
|
|
|
|
private static bool AreReportsSave(int[] reports, bool tolarance = false)
|
|
{
|
|
bool isIncrease = reports[1] < reports[0];
|
|
for (int index = 1; index < reports.Length; index++)
|
|
{
|
|
int trueDiff = reports[index - 1] - reports[index];
|
|
int diff = Math.Abs(trueDiff);
|
|
if (diff < 1 || diff > 3)
|
|
{
|
|
return tolarance && HasSafeCombo(reports);
|
|
}
|
|
|
|
if ((isIncrease && trueDiff < 0) || (!isIncrease && trueDiff > 0))
|
|
{
|
|
return tolarance && HasSafeCombo(reports);
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
private static bool HasSafeCombo(int[] reports)
|
|
=> reports.Select((_, i) => SkipReport(reports, i)).Any(reports => AreReportsSave(reports));
|
|
|
|
private static int[] SkipReport(int[] reports, int index) => reports.Where((_, i) => i != index).ToArray();
|
|
private static int[] ParselineToReports(string line) => line.Split(' ').Select(int.Parse).ToArray();
|
|
}
|
|
} |