Last active
September 23, 2015 14:48
-
-
Save maliqq/571655 to your computer and use it in GitHub Desktop.
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
# | |
# (c) 2008 you_katan | |
# | |
class Brainfuck | |
SIZE = 100 | |
def initialize(src, data = '') | |
@src = src | |
@table = Array.new(SIZE, 0) | |
@data = data | |
@cur = 0 | |
@ptr = 0 | |
end | |
def parse | |
0.upto @src.length do |i| | |
ch = @src.slice i, 1 | |
case ch | |
when '+' | |
@table[@cur] += 1 | |
when '-' | |
@table[@cur] -= 1 | |
when '.' | |
print @table[@cur].chr | |
when ',' | |
@data.slice(@ptr, 1).each_byte {|ch| | |
@table[@cur] = ch | |
} | |
@ptr += 1 | |
when '>' | |
@cur += 1 | |
@cur = 0 if cur > SIZE | |
when '<' | |
@cur -= 1 | |
@cur = SIZE if cur < 0 | |
when '[' | |
if (@table[@cur] == 0) | |
opened = 0 | |
i.upto @src.length do |k| | |
ch = @src.slice k, 1 | |
if ch == '[' | |
opened += 1 | |
elsif ch == ']' | |
opened -= 1 | |
break if opened == 0 | |
end | |
end | |
end | |
i = k | |
when ']' | |
if (@table[@cur] != 0) | |
closed = 0 | |
i.downto 0 do |k| | |
ch = @src.slice k, 1 | |
if ch == ']' | |
closed += 1 | |
elsif ch == '[' | |
closed -= 1 | |
break if closed == 0 | |
end | |
end | |
i = k | |
end | |
end | |
end | |
end | |
end | |
if $0 == File.basename(__FILE__) | |
bf = Brainfuck.new('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.-------------------------------------------------------------------------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.-------------------------------------------------------------------.-----------------------.') | |
bf.parse | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment