-
Notifications
You must be signed in to change notification settings - Fork 0
/
day10.dart
96 lines (79 loc) · 2.09 KB
/
day10.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
import 'package:adventofcode2022/day.dart';
import 'package:adventofcode2022/helper/string_extensions.dart';
import 'package:collection/collection.dart';
class Day10 implements Day {
@override
int get dayNumber => 10;
@override
String solveFirstPuzzle(String puzzleInput) {
final instructions = puzzleInput.splitPerLine().map((e) => Instruction(e)).toList();
final cpu = CPU();
for (var instruction in instructions) {
cpu.processInstruction(instruction);
}
var result = cpu.signalStrengths.sum;
return result.toString();
}
@override
String solveSecondPuzzle(String puzzleInput) {
final instructions = puzzleInput.splitPerLine().map((e) => Instruction(e)).toList();
final cpu = CPU();
for (var instruction in instructions) {
cpu.processInstruction(instruction);
}
var pixels = cpu.flatPixels.slices(40);
String result = '';
for (var row in pixels) {
result += '${row.join()}\n';
}
return result.toString();
}
}
enum InstructionType { add, noop }
class Instruction {
late InstructionType type;
late int value;
Instruction(String rawInstruction) {
final parts = rawInstruction.split(' ');
if (parts[0] == 'noop') {
type = InstructionType.noop;
} else {
type = InstructionType.add;
value = int.parse(parts[1]);
}
}
}
class CPU {
int cycles = 0;
int register = 1;
List<int> signalStrengths = [];
final flatPixels = List.filled(240, '.');
void processInstruction(Instruction instruction) {
if (instruction.type == InstructionType.noop) {
tick();
return;
}
if (instruction.type == InstructionType.add) {
tick();
tick();
register += instruction.value;
return;
}
}
void tick() {
cycles++;
checkSignalStrength();
drawPixel();
}
void checkSignalStrength() {
if ((cycles - 20) % 40 == 0) {
signalStrengths.add(cycles * register);
}
}
void drawPixel() {
final column = (cycles - 1) % 40;
if (column >= register - 1 && column <= register + 1) {
flatPixels[cycles - 1] = '#';
}
}
}