blob: 65eed44c20537fb2e16a8c4df32481769a1a4709 (
plain)
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
|
#!/usr/bin/env ruby
INFINITY = 10001
class State
def self.from_input(input)
this = input.shift.split[2][0]
input.shift
zero = [
input.shift.split[4][0].to_i,
input.shift.split[6][0] == 'r' ? 1 : -1,
input.shift.split[4][0]
]
input.shift
one = [
input.shift.split[4][0].to_i,
input.shift.split[6][0] == 'r' ? 1 : -1,
input.shift.split[4][0]
]
return [this, State.new(zero, one)]
end
attr_reader :zero, :one
def initialize(zero, one)
@zero = zero
@one = one
end
end
class Machine
def initialize(start, states)
@state = start
@states = states
@tape = [0] * INFINITY
@cursor = (INFINITY - 1) / 2
end
def step!
st = @states[@state]
pro = @tape[@cursor].zero? ? st.zero : st.one
@tape[@cursor] = pro[0]
@cursor += pro[1]
@state = pro[2]
end
def checksum
return @tape.count(1)
end
end
input = $stdin.readlines.map(&:strip) - [""]
bgn = input.shift.split[3][0]
dnc = input.shift.split[5].to_i
states = []
(0...input.length).step(9) do |i|
states << State.from_input(input[i...i+9])
end
states = states.to_h
m = Machine.new(bgn, states)
dnc.times do
m.step!
end
puts m.checksum
|