Skip to content

Instantly share code, notes, and snippets.

@halogenandtoast
Last active October 6, 2016 05:01
Show Gist options
  • Select an option

  • Save halogenandtoast/839036 to your computer and use it in GitHub Desktop.

Select an option

Save halogenandtoast/839036 to your computer and use it in GitHub Desktop.
Just for fun
class BrainfuckInterpreter
def initialize(program)
@memory = Array.new(255) { 0 } # 255 memory cells
@m_ptr = 0 # memory pointer: which cell
@i_ptr_stack = Array.new # instruction pointer stack: used for loops and nested loops
@i_ptr = 0 # instruction pointer: which instruction
@program = program
end
def run
while @program[@i_ptr]
op = @program[@i_ptr]
@i_ptr += 1
case op
when ">" then @m_ptr += 1
when "<" then @m_ptr -= 1
when "+" then @memory[@m_ptr] += 1
when "-" then @memory[@m_ptr] -= 1
when "." then print @memory[@m_ptr].chr
when "," then @memory[@m_ptr] = STDIN.getc.ord
when "[" then @i_ptr_stack << @i_ptr
when "]" then
if @memory[@m_ptr] == 0
@i_ptr_stack.pop
else
@i_ptr = @i_ptr_stack.last
end
end
end
end
end
# program = ",>,>++++++++[<------<------>>-]<<[>[>+>+<<-]>>[<<+>>-]<<<-]>>>++++++[<++++++++>-],<.>." # multiplication: give it two numbers whose multiplied value is less than 10. Input would be "23<Enter>"
# program = ",>++++++[<-------->-],[<+>-]<." # addition: give it two numbers whose added value is less than 10. Input would be "23<Enter>"
program ="++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." # Hello world!
BrainfuckInterpreter.new(program).run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment