fork download
  1. module Brainfuck extend self
  2. OPS = {
  3. "[" => :loop_start,
  4. "]" => :loop_end,
  5. ">" => :move_right,
  6. "<" => :move_left,
  7. "+" => :inc_memory,
  8. "-" => :dec_memory,
  9. "." => :put_char,
  10. "," => :get_char
  11. }
  12. MEM_SIZE = 65536
  13.  
  14. def parse(source)
  15. source.chars.map { |ch|
  16. OPS[ch]
  17. }.compact
  18. end
  19.  
  20. def execute(ops)
  21. memory = Array.new(MEM_SIZE){0}
  22. pc = 0
  23. pointer = 0
  24. stack = []
  25.  
  26. jump_table = {}.tap do |table|
  27. table_stack = []
  28. ops.each_with_index do |op, i|
  29. case op
  30. when :loop_start
  31. table_stack.push(i)
  32. when :loop_end
  33. table[table_stack.pop || abort("invalid program")] = i
  34. end
  35. end
  36. abort "invalid program" unless stack.empty?
  37. end
  38.  
  39. while pc < ops.size
  40. case ops[pc]
  41. when :loop_start
  42. if memory[pointer] == 0
  43. pc = jump_table[pc]
  44. else
  45. stack.push(pc)
  46. end
  47. when :loop_end
  48. pc = stack.pop - 1;
  49. when :move_right
  50. pointer += 1
  51. when :move_left
  52. pointer -= 1
  53. when :inc_memory
  54. memory[pointer] += 1
  55. when :dec_memory
  56. memory[pointer] -= 1
  57. when :put_char
  58. print memory[pointer].chr
  59. when :get_char
  60. memory[pointer] = $stdin.getc.ord
  61. else
  62. abort "undefined operation: #{ops[pc].inspect}"
  63. end
  64.  
  65. memory[pointer] %= 256
  66. pc += 1
  67. end
  68. end
  69.  
  70. def run(source)
  71. execute(parse(source))
  72. end
  73. end
  74.  
  75. fizzbuzz = <<BRAINFUCK
  76.  >++++++++++[<++++++++++>-]<[>+>[-]>++++++++++[<++++++++++>-]<+<<[->>->+<<<]>>>
  77.  [-<<<+>>>]<>>+++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<+>]+>[-]>[<<->>[-]]>[-]
  78.  <<<[[-]++++++++++[>++++++++++<-]>++.+++.[-]<[-]+++++++++++[>+++++++++++<-]>+..
  79.  [-]<[-]<<[-]>>]<>>+++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<+>]+>[-]>[<<->>[
  80.  -]]>[-]<<<[[-]+++++++++[>+++++++++++<-]>-.[-]<[-]+++++++++[>+++++++++++++<-]>.
  81.  +++++..[-]<[-]<<[-]>>]<<[[-]>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[
  82.  >++++++++[<++++++>-]<.[-]]<>++++++++[<++++++>-]<.[-]<<<]>[-]++++++++++.[-]<[-]
  83.  <-]
  84. BRAINFUCK
  85.  
  86. Brainfuck.run(ARGV.first ? File.read(ARGV.first) : fizzbuzz)
  87.  
Success #stdin #stdout 0.38s 7688KB
stdin
Standard input is empty
stdout
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz
fizz
22
23
fizz
buzz
26
fizz
28
29
fizzbuzz
31
32
fizz
34
buzz
fizz
37
38
fizz
buzz
41
fizz
43
44
fizzbuzz
46
47
fizz
49
buzz
fizz
52
53
fizz
buzz
56
fizz
58
59
fizzbuzz
61
62
fizz
64
buzz
fizz
67
68
fizz
buzz
71
fizz
73
74
fizzbuzz
76
77
fizz
79
buzz
fizz
82
83
fizz
buzz
86
fizz
88
89
fizzbuzz
91
92
fizz
94
buzz
fizz
97
98
fizz
buzz