141 lines
3.6 KiB
C#
141 lines
3.6 KiB
C#
Day02Parsed exParsed = new Day02Parsed("example-input.txt");
|
|
|
|
Console.WriteLine("Example Part01: {0}", exParsed.GetSafeReportCount01());
|
|
Console.WriteLine("Example Part02: {0}", exParsed.GetSafeReportCount02());
|
|
|
|
Day02Parsed pzParsed = new Day02Parsed("puzzle-input.txt");
|
|
|
|
Console.WriteLine("Puzzle Part01: {0}", pzParsed.GetSafeReportCount01());
|
|
Console.WriteLine("Puzzle Part02: {0}", pzParsed.GetSafeReportCount02());
|
|
|
|
class Day02Parsed : AdventCommon.ParsedInput
|
|
{
|
|
List<List<int>> Reports = new List<List<int>>();
|
|
|
|
public Day02Parsed(string fileName) : base(fileName)
|
|
{
|
|
|
|
}
|
|
|
|
public int GetSafeReportCount01()
|
|
{
|
|
int count = 0;
|
|
|
|
for (int i = 0; i < Reports.Count; i++)
|
|
{
|
|
if (IsSafe(Reports[i]))
|
|
{
|
|
count++;
|
|
}
|
|
}
|
|
|
|
return count;
|
|
}
|
|
|
|
public int GetSafeReportCount02()
|
|
{
|
|
int count = 0;
|
|
|
|
for (int i = 0; i < Reports.Count; i++)
|
|
{
|
|
// First see if its safe outright
|
|
if (IsSafe(Reports[i]))
|
|
{
|
|
count++;
|
|
}
|
|
else
|
|
{
|
|
// Remove one start to end and check again
|
|
for (int j = 0; j < Reports[i].Count; j++)
|
|
{
|
|
List<int> newReport = new List<int>(Reports[i]);
|
|
newReport.RemoveAt(j);
|
|
if (IsSafe(newReport))
|
|
{
|
|
count++;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return count;
|
|
}
|
|
|
|
public bool IsSafe(List<int> report)
|
|
{
|
|
bool isAscending = false;
|
|
|
|
if ( report[0] < report[1] )
|
|
{
|
|
isAscending = true;
|
|
}
|
|
|
|
{
|
|
int rightDiff = report[1] - report[0];
|
|
|
|
if (Math.Abs(rightDiff) < 1 || Math.Abs(rightDiff) > 3)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
for (int i = 1; i < report.Count - 1; i++)
|
|
{
|
|
int leftDiff = report[i] - report[i - 1];
|
|
int rightDiff = report[i + 1] - report[i];
|
|
|
|
// if ascending and either difference is negative, not safe
|
|
if (isAscending && (leftDiff < 0 || rightDiff < 0))
|
|
{
|
|
return false;
|
|
}
|
|
// if descending and either difference is positive, not safe
|
|
else if (!isAscending && (rightDiff > 0 || leftDiff > 0))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (Math.Abs(leftDiff) < 1 || Math.Abs(leftDiff) > 3)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (Math.Abs(rightDiff) < 1 || Math.Abs(rightDiff) > 3)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
{
|
|
int leftDiff = report[report.Count - 1] - report[report.Count - 2];
|
|
if (isAscending && leftDiff < 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (Math.Abs(leftDiff) < 1 || Math.Abs(leftDiff) > 3)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
|
|
public override bool ParseLine(string line, object? context = null)
|
|
{
|
|
List<int> levels = new List<int>();
|
|
var split = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
foreach (var level in split)
|
|
{
|
|
levels.Add(Int32.Parse(level));
|
|
}
|
|
|
|
Reports.Add(levels);
|
|
|
|
return true;
|
|
}
|
|
} |