Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Brainfuck
- def self.run(src)
- b = check_bracket(src)
- pc = 0
- p = 0
- t = Array.new(30000, 0)
- while pc < src.size
- case src[pc]
- when ?> then p += 1
- when ?< then p -= 1
- when ?+ then t[p] = (t[p] + 1) % 256
- when ?- then t[p] = (t[p] - 1) % 256
- when ?. then print t[p].chr
- when ?, then t[p] = $stdin.getc.to_i
- when ?[ then pc = b[pc] if t[p].zero?
- when ?] then pc = b.invert[pc] - 1
- end
- pc += 1
- end
- end
- private
- def self.check_bracket(src)
- s = []
- l = []
- src.each_byte.with_index do |b, i|
- case b.chr
- when '['
- s << i
- when ']'
- l << [s.pop, i]
- end
- end
- return Hash[*l.flatten]
- end
- end
Add Comment
Please, Sign In to add comment