Skip to content

Commit

Permalink
Day02: Solved
Browse files Browse the repository at this point in the history
  • Loading branch information
julemand101 committed Dec 2, 2024
1 parent e6783b3 commit 4679924
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 1 deletion.
54 changes: 54 additions & 0 deletions lib/day02.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// --- Day 2: Red-Nosed Reports ---
// https://adventofcode.com/2024/day/2

int solveA(Iterable<String> input) =>
input.map((line) => line.split(' ').map(int.parse)).where(isValid).length;

int solveB(Iterable<String> input) =>
input.map((line) => line.split(' ').map(int.parse)).where((report) {
if (isValid(report)) {
return true;
}

for (var i = 0; i < report.length; i++) {
if (isValid(report, skipLevel: i)) {
return true;
}
}

return false;
}).length;

bool isValid(Iterable<int> levels, {int skipLevel = -1}) {
int? lastValue;
bool? increasing;

for (final (index, value) in levels.indexed) {
if (index == skipLevel) {
continue;
}

if (lastValue == null) {
lastValue = value;
continue;
}

if ((value - lastValue).abs() > 3 || value == lastValue) {
return false;
}

if (increasing == null) {
increasing = value > lastValue;
lastValue = value;
continue;
}

if (increasing && value < lastValue || !increasing && value > lastValue) {
return false;
}

lastValue = value;
}

return true;
}
2 changes: 1 addition & 1 deletion test/data
Submodule data updated from c7941e to 5a327b
48 changes: 48 additions & 0 deletions test/day02_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// --- Day 2: Red-Nosed Reports ---
// https://adventofcode.com/2024/day/2

import 'dart:io';
import 'package:advent_of_code_2024/day02.dart';
import 'package:advent_of_code_2024/util.dart';
import 'package:test/test.dart';

final input = File('test/data/day02.txt').readAsLinesSync();

void main() {
group('Part One', () {
test('Example 1', () {
expect(
solveA(r'''
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
'''
.asLines),
equals(2));
});
test('Solution', () {
expect(solveA(input), equals(421));
});
});
group('Part Two', () {
test('Example 1', () {
expect(
solveB(r'''
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
'''
.asLines),
equals(4));
});
test('Solution', () {
expect(solveB(input), equals(476));
});
});
}

0 comments on commit 4679924

Please sign in to comment.