Anonymous user
Execute Brain****/Ruby: Difference between revisions
handle nested loops
m (needs attention: nested loops) |
(handle nested loops) |
||
Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}[[Category:Ruby]]
More effort could be made to read a program from a file or from stdin.
Line 7 ⟶ 6:
@d = [0] * 30_000
@program = program
@jumpback_table = read_program
end
def read_program
jumpback_table = {}
nest_level = 0
start_idx = []
@program.each_char.each_with_index do |char, idx|
case char
when "["
start_idx[nest_level] = idx
nest_level += 1
when "]"
nest_level -= 1
jumpback_table[idx] = start_idx[nest_level]
end
end
jumpback_table
end
Line 36 ⟶ 53:
when ?[ then
if @d[dc] == 0
pc
p " #{[pc,@program[pc].chr].inspect}" if $DEBUG
end
when ?] then
if @d[dc] != 0
pc
p " #{[pc,@program[pc].chr].inspect}" if $DEBUG
end
Line 49 ⟶ 66:
end
end
end
# output 'Hello World!\n'▼
<pre>irb(main):048:0> helloworld = '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.'▼
helloworld = <<PROGRAM
++++++++++[>+++++++>++++++++++>+++>+<<<<-]
irb(main):049:0> bf = RCBF.new(helloworld)▼
▲
PROGRAM
bf.run
▲Hello World!
=> nil</pre>▼
# use nested loop to increment count to 64 and print (should be '@')"
# 64 = 4*4*4
nestedloop = '>>++++[<++++[<++++>-]>-]<<.[-]++++++++++.'
bf = RCBF.new(nestedloop)
bf.run</lang>
Output:
<pre>Hello World!
|