-
Notifications
You must be signed in to change notification settings - Fork 0
/
day01.dart
101 lines (87 loc) · 2.12 KB
/
day01.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import 'package:adventofcode2023/day.dart';
import 'package:adventofcode2023/helper/string_extensions.dart';
import 'package:collection/collection.dart';
class Day1 implements Day {
@override
int get dayNumber => 1;
@override
String solveFirstPuzzle(String puzzleInput) {
var calibrationValues = puzzleInput.splitPerLine().map((e) {
var firstAndLastDigit = e.split('').where((element) => element.isNumeric()).toList();
return int.parse(firstAndLastDigit.first + firstAndLastDigit.last);
}).toList();
var result = calibrationValues.sum;
return result.toString();
}
@override
String solveSecondPuzzle(String puzzleInput) {
var calibrationValues = puzzleInput.splitPerLine().map((e) {
return getCalibrationValueFromLine(e);
}).toList();
var result = calibrationValues.sum;
return result.toString();
}
int getCalibrationValueFromLine(String line) {
List<(int, String)> indicesAndValues = [];
for (var element in numbersAsString) {
var firstIndex = line.indexOf(element);
if (firstIndex != -1) {
indicesAndValues.add((firstIndex, replaceSpelledOutDigitByDigit(element)));
}
var lastIndex = line.lastIndexOf(element);
if (lastIndex != -1) {
indicesAndValues.add((lastIndex, replaceSpelledOutDigitByDigit(element)));
}
}
indicesAndValues.sortBy<num>((element) => element.$1);
return int.parse(indicesAndValues.first.$2 + indicesAndValues.last.$2);
}
}
String replaceSpelledOutDigitByDigit(String digit) {
switch (digit) {
case 'zero':
return '0';
case 'one':
return '1';
case 'two':
return '2';
case 'three':
return '3';
case 'four':
return '4';
case 'five':
return '5';
case 'six':
return '6';
case 'seven':
return '7';
case 'eight':
return '8';
case 'nine':
return '9';
default:
return digit;
}
}
const List<String> numbersAsString = [
'zero',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'0',
];