Execute Brain****/Ruby: Difference between revisions
Content added Content deleted
m (moved RCBF/Ruby to Execute Brain****/Ruby) |
(improvement of the debugging output, each_with_index->with_index) |
||
Line 13:
jumpback_table = {}
jump_to = []
@program.each_char.
case char
when "[" then jump_to.push(idx)
Line 21:
jumpback_table
end
def run
invert_table = @jumpback_table.invert
dc = 0
pc = 0
while pc < @program.length
print [pc, @program[pc]
case @program[pc]
when ?>
dc += 1
print "\t#{dc}" if $DEBUG
when ?<
dc -= 1
print "\t#{dc}" if $DEBUG
when ?+
@d[dc] += 1
print "\t#{dc},#{@d[dc]}" if $DEBUG
when ?-
@d[dc] -= 1
print "\t#{dc},#{@d[dc]}" if $DEBUG
when ?.
print "\t#{dc},#{@d[dc]}\t" if $DEBUG
print @d[dc].chr
when ?,
@d[dc] = $stdin.getc
print "\t#{dc},#{@d[dc]}" if $DEBUG
when ?[
if @d[dc] == 0
pc =
end
when ?]
if @d[dc] != 0
pc = @jumpback_table[pc]
end
end
Line 71 ⟶ 72:
bf = RCBF.new(helloworld)
bf.run
# use nested loop to increment count to 64 and print (should be '@')
# followed by a newline
RCBF.new('>>++++[<++++[<++++>-]>-]<<.[-]++++++++++.').run</lang>
{{out}}
<pre>Hello World!
@</pre>
|
Revision as of 03:55, 11 December 2014
Execute Brain****/Ruby is an implementation of Brainf***.
Other implementations of Brainf***.
Execute Brain****/Ruby is part of RCBF. You may find other members of RCBF at Category:RCBF.
An implementation of a Brainf*** interpreter in Ruby. More effort could be made to read a program from a file or from stdin.
<lang ruby>class RCBF
def initialize(program) @d = [0] * 30_000 @program = program @jumpback_table = read_program end def read_program jumpback_table = {} jump_to = [] @program.each_char.with_index do |char, idx| case char when "[" then jump_to.push(idx) when "]" then jumpback_table[idx] = jump_to.pop end end jumpback_table end def run invert_table = @jumpback_table.invert dc = 0 pc = 0 while pc < @program.length print [pc, @program[pc]] if $DEBUG case @program[pc] when ?> dc += 1 print "\t#{dc}" if $DEBUG when ?< dc -= 1 print "\t#{dc}" if $DEBUG when ?+ @d[dc] += 1 print "\t#{dc},#{@d[dc]}" if $DEBUG when ?- @d[dc] -= 1 print "\t#{dc},#{@d[dc]}" if $DEBUG when ?. print "\t#{dc},#{@d[dc]}\t" if $DEBUG print @d[dc].chr when ?, @d[dc] = $stdin.getc print "\t#{dc},#{@d[dc]}" if $DEBUG when ?[ if @d[dc] == 0 pc = invert_table[pc] print " #{[pc,@program[pc]]}" if $DEBUG end when ?] if @d[dc] != 0 pc = @jumpback_table[pc] print " #{[pc,@program[pc]]}" if $DEBUG end end puts if $DEBUG pc += 1 end end
end
- output 'Hello World!\n'
helloworld = <<PROGRAM ++++++++++[>+++++++>++++++++++>+++>+<<<<-] >++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. PROGRAM bf = RCBF.new(helloworld) bf.run
- use nested loop to increment count to 64 and print (should be '@')
- followed by a newline
RCBF.new('>>++++[<++++[<++++>-]>-]<<.[-]++++++++++.').run</lang>
- Output:
Hello World! @