-
Notifications
You must be signed in to change notification settings - Fork 1
/
a12.dart
124 lines (107 loc) · 2.47 KB
/
a12.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import 'dart:io';
import 'dart:convert';
import 'package:args/args.dart';
class Game {
List<int> state;
Map<int, bool> rules;
Game(this.state, this.rules);
void evolve() {
var newState = List<int>();
int i = 0;
int pos = state[0] - 2;
int locale = 0;
void checkAndShift() {
if (rules[locale]) {
newState.add(pos);
}
pos++;
locale <<= 1;
locale &= 0x1f;
}
while (i < state.length ) {
if (state[i] == pos + 2) {
locale |= 1;
i++;
}
checkAndShift();
}
while (locale > 0) {
checkAndShift();
}
state = newState;
}
int potSum() {
return state.reduce((a,b) => a+b);
}
}
const generationsArg = 'generations';
ArgResults argResults;
void main(List<String> arguments) async {
exitCode = 0; //presume success
final parser = new ArgParser()
..addOption(generationsArg, abbr: 'g', defaultsTo: '20');
argResults = parser.parse(arguments);
int generations = int.parse(argResults[generationsArg]);
List<String> paths = argResults.rest;
var game = await parseIndata(paths[0]);
for (int i = 0; i < generations; i++) {
game.evolve();
}
stdout.writeln(game.potSum());
}
Future<Game> parseIndata(String path) async {
int lineNumber = 1;
Stream lines = new File(path)
.openRead()
.transform(utf8.decoder)
.transform(const LineSplitter());
try {
var state;
var rules = Map<int, bool>();
await for (var line in lines) {
if (lineNumber == 1) {
state = getState(line);
} else if (lineNumber > 2) {
Rule rule = getRule(line);
rules[rule.pattern] = rule.result;
}
lineNumber++;
}
return Game(state, rules);
} catch (_) {
_handleError(path);
}
}
getState(String line) {
var state = <int>[];
var chars = line.replaceFirst('initial state: ', '').split('');
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '#') {
state.add(i);
}
}
return state;
}
class Rule {
int pattern;
bool result;
Rule(this.pattern, this.result);
}
getRule(String line) {
int pattern = 0;
line.substring(0, 5).split('').forEach((c) {
pattern <<= 1;
if (c == '#') {
pattern |= 1;
}
});
bool result = line[line.length - 1] == '#';
return Rule(pattern, result);
}
Future _handleError(String path) async {
if (await FileSystemEntity.isDirectory(path)) {
stderr.writeln('error: $path is a directory');
} else {
exitCode = 2;
}
}