Mercurial > hg > aoc
comparison 2017/day25.d @ 32:763c88851b91
day 25
author | Jordi Gutiérrez Hermoso <jordigh@octave.org> |
---|---|
date | Tue, 02 Jan 2018 21:41:45 -0500 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
31:6761b3bbaa70 | 32:763c88851b91 |
---|---|
1 import std.stdio; | |
2 import std.format: formattedRead; | |
3 import std.algorithm: sum; | |
4 | |
5 struct Branch { | |
6 bool writeval; | |
7 int movedir; | |
8 char newstate; | |
9 } | |
10 | |
11 struct Instruction { | |
12 Branch if0; | |
13 Branch if1; | |
14 } | |
15 | |
16 auto branchFmt = | |
17 " - Write the value %d. | |
18 - Move one slot to the %s. | |
19 - Continue with state %s. | |
20 "; | |
21 | |
22 auto parseBranch(File f) { | |
23 int writeval; | |
24 string movedir; | |
25 char newstate; | |
26 | |
27 f.readf(branchFmt, &writeval, &movedir, &newstate); | |
28 return Branch(writeval ? true : false, movedir == "left" ? -1 : 1, newstate); | |
29 } | |
30 | |
31 auto parseInstructions(File f) { | |
32 Instruction[char] instructions; | |
33 | |
34 while(!f.eof) { | |
35 char state; | |
36 f.readf("In state %s:\n", &state); | |
37 f.readln; // "If the current value is 0:" | |
38 auto if0 = f.parseBranch; | |
39 f.readln; // "If the current value is 1:" | |
40 auto if1 = f.parseBranch; | |
41 f.readln; // Blank line | |
42 instructions[state] = Instruction(if0, if1); | |
43 } | |
44 return instructions; | |
45 } | |
46 | |
47 auto runProgram(File f) { | |
48 char state; | |
49 f.readf("Begin in state %s.\n", &state); | |
50 | |
51 long steps; | |
52 f.readf("Perform a diagnostic checksum after %d steps.\n\n", &steps); | |
53 | |
54 Instruction[char] instructions = f.parseInstructions; | |
55 long ip = 0; | |
56 bool[long] tape; | |
57 | |
58 foreach(_; 0..steps) { | |
59 auto inst = instructions[state]; | |
60 auto branch = tape.get(ip, false) ? inst.if1 : inst.if0; | |
61 tape[ip] = branch.writeval; | |
62 ip += branch.movedir; | |
63 state = branch.newstate; | |
64 } | |
65 return tape.values.sum; | |
66 } | |
67 | |
68 void main(string[] args){ | |
69 auto checkSum = runProgram(File(args[1])); | |
70 writeln(checkSum); | |
71 } |