Skip to content

Commit

Permalink
Add AoC 2024 day 02 solver
Browse files Browse the repository at this point in the history
  • Loading branch information
h3x4d3c1m4l committed Dec 2, 2024
1 parent 2381571 commit 5d0f214
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
6 changes: 6 additions & 0 deletions assets/advent_of_code/2024_02_sample.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9
1 change: 1 addition & 0 deletions lib/solvers/advent_of_code/2024/_all_solvers.dart
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export 'day_01_solver.dart';
export 'day_02_solver.dart';
52 changes: 52 additions & 0 deletions lib/solvers/advent_of_code/2024/day_02_solver.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import 'package:h3x_devtools/solvers/advent_of_code/2024/aoc_2024_solver.dart';

class Day02Solver extends AdventOfCode2024Solver {

@override
final int dayNumber = 2;

@override
String getSolution(String input) {
List<List<int>> leveledReports = input.splitLines().map((line) => line.split(' ').parsedAsInts.toList()).toList();

// Part 1
int safeReports = _getSaveReports(leveledReports, false);

// Part 2
int safeReportsWith = _getSaveReports(leveledReports, true);

return 'Safe reports: $safeReports, Safe reports when allowing one error: $safeReportsWith';
}

int _getSaveReports(List<List<int>> leveledReports, bool allowInvalidLevel) {
return leveledReports.where((report) {
bool result = _getReportSafe(report);
int i = 0;
while (!result && allowInvalidLevel && i < report.length) {
result = _getReportSafe(report.toList()..removeAt(i));
i++;
}
return result;
}).length;
}

bool _getReportSafe(List<int> report) {
int maxInc = 0, maxDec = 0;

for (int i = 0; i < report.length - 1; i++) {
var currentLevel = report[i];
var nextLevel = report[i + 1];

int inc = nextLevel - currentLevel;
maxInc = inc > 0 ? max(maxInc, inc) : maxInc;
maxDec = inc < 0 ? max(maxDec, inc.abs()) : maxDec;

if (inc == 0 || !((maxInc == 0 && maxDec >= 1 && maxDec <= 3) || (maxInc >= 1 && maxInc <= 3 && maxDec == 0))) {
return false;
}
}

return true;
}

}

0 comments on commit 5d0f214

Please sign in to comment.