Files
adventofcode2025/lib/day2/command.dart
2025-12-04 14:53:54 -06:00

77 lines
2.2 KiB
Dart

import "dart:io";
import "package:args/command_runner.dart";
class Day2Command extends Command {
// The [name] and [description] properties must be defined by every
// subclass.
@override
final name = "day2";
@override
final description = "Run Advent of Code 2025 Day 2";
Day2Command() {
// we can add command specific arguments here.
// [argParser] is automatically created by the parent class.
}
// [run] may also return a Future.
@override
Future<void> run() async {
// [argResults] is set before [run()] is called and contains the flags/options
// passed to this command.
if (argResults!.rest.length != 1) {
print(
"Expected 1 positional arguments, found ${argResults!.rest.length}",
);
}
var filePath = argResults!.rest[0];
print("Parsing file: $filePath");
var inputFile = File(filePath);
var openFile = await inputFile.readAsString();
RegExp exp = RegExp(r'^([0-9]+)\1+$');
var ids = openFile
.trim()
.split(',')
.expand((range) {
var extents = range.split('-');
if (extents.length != 2) {
throw Exception(
"Expected range with 2 parts, but got ${extents.length} parts: {range}",
);
}
var numRange = [int.parse(extents[0]), int.parse(extents[1])];
List<int> createRange(int from, int to) =>
List.generate(to - from + 1, (i) => i + from);
return createRange(numRange[0], numRange[1]);
})
.map((id) => id.toString());
var part1Answer = ids
.where((id) => id.length.isEven)
.where((id) {
var firstHalf = id.substring(0, (id.length / 2).floor());
var secondHalf = id.substring((id.length / 2).floor(), id.length);
return firstHalf == secondHalf;
})
.map((id) => int.parse(id))
.reduce((id1, id2) => id1 + id2);
print("Part 1 Answer: $part1Answer");
var part2Answer = ids
.where((id) => exp.hasMatch(id))
.map((id) {
//print(id);
return int.parse(id);
})
.reduce((id1, id2) => id1 + id2);
print("Part 2 Answer: $part2Answer");
}
}