Last active
October 6, 2016 05:01
-
-
Save halogenandtoast/839036 to your computer and use it in GitHub Desktop.
Just for fun
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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