Guest User

Untitled

a guest
Jan 21st, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. class Brainfuck
  2. def self.run(src)
  3. b = check_bracket(src)
  4. pc = 0
  5. p = 0
  6. t = Array.new(30000, 0)
  7. while pc < src.size
  8. case src[pc]
  9. when ?> then p += 1
  10. when ?< then p -= 1
  11. when ?+ then t[p] = (t[p] + 1) % 256
  12. when ?- then t[p] = (t[p] - 1) % 256
  13. when ?. then print t[p].chr
  14. when ?, then t[p] = $stdin.getc.to_i
  15. when ?[ then pc = b[pc] if t[p].zero?
  16. when ?] then pc = b.invert[pc] - 1
  17. end
  18. pc += 1
  19. end
  20. end
  21.  
  22. private
  23. def self.check_bracket(src)
  24. s = []
  25. l = []
  26. src.each_byte.with_index do |b, i|
  27. case b.chr
  28. when '['
  29. s << i
  30. when ']'
  31. l << [s.pop, i]
  32. end
  33. end
  34. return Hash[*l.flatten]
  35. end
  36. end
Add Comment
Please, Sign In to add comment