Die Programmiersprache Ruby

Blog| Forum| Wiki  

Diese Seite zeigt Implementierungen von Brainfuck

Interpreter Implementierung von stephensykes.com:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Bf
def initialize
  @a=[0]*30000
  @b=[]
  @p=0
  @x=0
end

def r
  @p+=1 if !@j
end

def l
  @p-=1 if !@j
end

def i
  @a[@p]+=1 if !@j
end

def d
  @a[@p]-=1 if !@j
end

def o
  print @a[@p].chr if !@j
end

def n
  @a[@p] = $stdin.getc if !@j
end

def j
  @x+=1
  if @a[@p]==0
    @j=true
  else
    @b[@x]=$i-1
  end
end

def e
  if @j
    @j=false
  else
    $i=@b[@x]
  end
  @x-=1
end

def b
  10.times {|a| print @a[a].chr}
end
end

b=Bf.new
$i=0
p=$<.readlines.join.tr('^><+\-.,[]#','').tr('><+\-.,[]#', 'rlidonjeb')
while $i<p.size
  b.send(p[$i].chr)
  $i+=1
end


Implementierung von cypher:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/ruby -w 
# Brainfuck interpreter in Ruby written by cypher 

cells = Array.new(300_000) { Integer(0) } 
idx = 0 
cmd_idx = 0 
brace_stack = [] 

commands = IO.read(ARGV[0]) 

while cmd_idx < commands.length 
    case commands[cmd_idx] 
    when ?> 
        idx += 1 
    when ?< 
        idx -= 1 
    when ?+ 
        cells[idx] += 1 
    when ?- 
        cells[idx] -= 1 
    when ?. 
        $stdout << cells[idx].chr 
        $stdout.flush 
    when ?, 
        cells[idx] = $stdin.read( 1 ) 
    when ?[ 
        brace_stack.push cmd_idx 
        # Jump to next ']' 
        cmd_idx += 1 while commands[cmd_idx] != ?] if cells[idx] == 0 
    when ?] 
        if cells[idx] != 0 
            cmd_idx = brace_stack.last 
        else 
            brace_stack.pop 
        end 
    end 
    cmd_idx += 1 
end


Interpreter Implementierung von Gekko:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/ruby -w 
# Brainfuck interpreter in Ruby written by cypher, raise added by Gekko 

cells = Array.new(300_000) { Integer(0) } 
idx = 0 
cmd_idx = 0 
brace_stack = [] 
fuck = "Fuck!" 

commands = IO.read(ARGV[0]) 

while cmd_idx < commands.length 
    case commands[cmd_idx] 
    when ?> 
        idx += 1 
    when ?< 
        idx -= 1 
    when ?+ 
        raise fuck if cells[idx] + 1 >  255 
        cells[idx] += 1 
    when ?- 
        raise fuck if cells[idx] - 1 < 0 
        cells[idx] -= 1 
    when ?. 
        $stdout << cells[idx].chr 
        $stdout.flush 
    when ?, 
        cells[idx] = $stdin.read( 1 ) 
    when ?[ 
        brace_stack.push cmd_idx 
        cmd_idx += 1 while commands[cmd_idx] != ?] if cells[idx] == 0 
    when ?] 
        if cells[idx] != 0 
            cmd_idx = brace_stack.last 
        else 
            brace_stack.pop 
        end 
    end 
    cmd_idx += 1 
end