Execute Brain****/Ruby: Difference between revisions

m
Fixed syntax highlighting.
m (Categorization now in master page)
m (Fixed syntax highlighting.)
 
(4 intermediate revisions by 4 users not shown)
Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}
===Version 1===
An implementation of a [[Brainf***]] interpreter in [[Ruby]].
More effort could be made to read a program from a file or from stdin.
 
<langsyntaxhighlight lang="ruby">class RCBF
def initialize(program)
@d = [0] * 30_000
Line 12 ⟶ 13:
def read_program
jumpback_table = {}
nest_leveljump_to = 0[]
@program.each_char.each_with_indexwith_index do |char, idx|
start_idx = []
@program.each_char.each_with_index do |char, idx|
case char
when "[" then jump_to.push(idx)
when "]" start_idxthen jumpback_table[nest_levelidx] = idxjump_to.pop
nest_level += 1
when "]"
nest_level -= 1
jumpback_table[idx] = start_idx[nest_level]
end
end
jumpback_table
end
 
def run
invert_table = @jumpback_table.invert
dc = 0
pc = 0
while pc < @program.length
print [pc, @program[pc].chr].inspect 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 ?, then
@d[dc] = $stdin.getc
print "\t#{dc},#{@d[dc]}" if $DEBUG
when ?[ then
if @d[dc] == 0
pc = @jumpback_table.invertinvert_table[pc]
pprint " #{[pc,@program[pc].chr].inspect}" if $DEBUG
end
when ?] then
if @d[dc] != 0
pc = @jumpback_table[pc]
pprint " #{[pc,@program[pc].chr].inspect}" if $DEBUG
end
end
Line 76 ⟶ 73:
bf = RCBF.new(helloworld)
bf.run
# use nested loop to increment count to 64 and print (should be '@')"
# followed by a newline
nestedloop = RCBF.new('>>++++[<++++[<++++>-]>-]<<.[-]++++++++++.').run</syntaxhighlight>
 
{{out}}
# 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!
@</pre>
 
===Version 2===
This variant converts the brainfuck into Ruby code and runs that instead.
Do note that this requires Ruby1.9.1 or later, earlier versions need a somewhat more verbose variant.
 
BF code may be read from a file or taken from STDIN.
 
<syntaxhighlight lang="ruby">eval 'm=Hash.new(p=0);'+ARGF.read.gsub(
when "]" /./,
'>' => 'p+=1;',
'<' => 'p-=1;',
'+' => 'm[p]+=1;',
'-' => 'm[p]-=1;',
'[' => '(;',
']' => ')while((m[p]&=255)!=0);',
'.' => 'putc(m[p]&=255);',
',' => 'm[p]=STDIN.getc.ord if !STDIN.eof;')</syntaxhighlight>
9,476

edits