Mit Brainfuck-Code für Fibonacci-Zahlen. Oh Jubel.
# brainfuck Interpreter
class Array
def rtrim empty = 0
(self.length-1).downto(0) do |a|
return self[0..a] if self[a] != empty
end
[]
end
end
class Brainfuck
attr_accessor :code, :ascii, :debug
def initialize(code = "", memsize = 30000)
@code = code.gsub(/[^.,+-<>[]]/, "")
@mem = Array.new(memsize, 0)
@ascii = true # In/Output als ASCII oder mit puren Zellwerten arbeiten?
@debug = false
end
def run
p = 0
cp = 0
brackets = []
while cp < @code.length
c = @code[cp].chr
case c
when "+"
@mem[p] += 1
when "-"
@mem[p] -= 1
when ">"
p += 1
when "<"
p -= 1
when "["
brackets.push(cp)
when "]"
if @mem[p] != 0
cp = brackets.pop - 1
else
brackets.pop
end
when "."
if @debug
print "p: #{p} cp: #{cp} "
p @mem.rtrim
end
if @ascii
print @mem[p].chr
else
puts @mem[p]
end
when ","
input = gets
if @ascii
@mem[p] = input[0]
else
@mem[p] = input.to_i
end
end
cp += 1
end
end
end
# Die ersten 10 Fibonacci-Zahlen: +>++>>>++++++++++[<<<<.>[->+>+<<]>>[-<<+>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<<<[-]>>[<<+>>-]>>-]
# Die ersten n Fibonacci-Zahlen: +>++>>>,[<<<<.>[->+>+<<]>>[-<<+>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<<<[-]>>[<<+>>-]>>-]
code = <<END
+>++>>>,[<<<<.>[->+>+<<]>>[-<<+>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<<<[-]>>[<<+>>-]>>-]
END
bf = Brainfuck.new(code)
bf.ascii = false
bf.debug = false
bf.run