18/11/25 16:52:01.92 1Q36MCdG.net
>>706 Ruby やっつけ
def parse_bra(code)
Hash.new.tap{|h|
while i = (code.index(/\[[^\[\]]*\]/))
h[i] = i + $&.size - 1; h[h[i]] = i; code = code.sub($&, ' ' * $&.size)
end
end
end
def step(stat)
case stat[:code][stat[:pos]]
when ?> then stat[:mar] = stat[:mar] == 9999 ? 0 : stat[:mar] + 1
when ?< then stat[:mar] = stat[:mar] == 0 ? 9999 : stat[:mar] - 1
when ?+ then stat[:mem][stat[:mar]] = stat[:mem][stat[:mar]] == 255 ? 0 : stat[:mem][stat[:mar]] + 1
when ?- then stat[:mem][stat[:mar]] = stat[:mem][stat[:mar]] == 0 ? 255 : stat[:mem][stat[:mar]] - 1
when ?. then putc stat[:mem][stat[:mar]]
when ?, then stat[:mem][stat[:mar]] = $stdin.getc&.ord.to_i
when ?[ then stat[:pos] = stat[:bra][stat[:pos]] if stat[:mem][stat[:mar]] == 0
when ?] then stat[:pos] = stat[:bra][stat[:pos]] if stat[:mem][stat[:mar]] != 0
end
end
def bf(code)
stat = {pos: 0, mar: 0, code: code, mem: Array.new(10000, 0), bra: parse_bra(code)}
(step(stat); stat[:pos] += 1) while stat[:pos] < code.size
end
bf('>+++++++++[<++++++++>-]/ 中略 /++++[<++++>-]<+.[-]++++++++++.')
# => Hello World!
bf('++++++++[>++++++++<-]>+/ 中略 /++++.<----[>++++<-]>--.++++++++.')
# => Brainfuck