## 0 Replies - 1635 Views - Last Post: 12 January 2010 - 01:39 PM

### #1 erik.price Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

# Brainf*ck Interpreter

Posted 12 January 2010 - 01:39 PM

Description: Input is a string containing valid BF code.Evaluates a brainf*ck program
```def parseBF(bf)

ptrIndex = 0
i = 0
x = -1
ptr = Array.new(bf.length, 0)
#create an array that would work in the case that every element of the BF string is '>', and fill it up with 0s
#the classic distrobutuion has an array of 30,000 spaces, but this gives in essence unlimited room

while i < bf.length
case bf[i].chr

when '+': ptr[ptrIndex] += 1

when '-': ptr[ptrIndex] -= 1

when '>': ptrIndex += 1

when '<': ptrIndex -= 1

when '.': print(ptr[ptrIndex].chr)

when ',': ptr[ptrIndex] = STDIN.getc #get a single character

when '[':  if ptr[ptrIndex] == 0

i += 1
x = 0
while  x > 0  or bf[i].chr != ']' do

if bf[i].chr == '['
x += 1

elsif bf[i].chr == ']'
x -= 1
end #end if

i += 1
end #end while

end #end if

when ']':  x = 0
i -= 1
while x > 0 or bf[i].chr != '['
if bf[i].chr == ']'
x += 1
elsif bf[i].chr == '['
x -= 1
end #end if
i -= 1
end #end while
i -= 1

else #nothing , we ignore all extra characters

end #end case
i += 1
end   #end while
end #end method
```

Is This A Good Question/Topic? 0

## Replies To: Brainf*ck Interpreter

### #2 erik.price Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

## Re: Brainf*ck Interpreter

Posted 12 January 2010 - 01:39 PM

Description: Input is a string containing valid BF code. Works in 1.8/1.9, but runs much faster in Ruby 1.9Evaluates a brainf*ck program
```def parseBF(bf)

ptrIndex = 0
i = 0
x = -1
ptr = Array.new(bf.length, 0)
#create an array that would work in the case that every element of the BF string is '>', and fill it up with 0s
#the classic distrobutuion has an array of 30,000 spaces, but this gives in essence unlimited room

while i < bf.length
case bf[i].chr

when '+'then ptr[ptrIndex] += 1

when '-'then ptr[ptrIndex] -= 1

when '>'then ptrIndex += 1

when '<'then ptrIndex -= 1

when '.'then print(ptr[ptrIndex].chr)

when ','then ptr[ptrIndex] = STDIN.getc #get a single character

when '['then  if ptr[ptrIndex] == 0

i += 1
x = 0
while  x > 0  or bf[i].chr != ']' do

if bf[i].chr == '['
x += 1

elsif bf[i].chr == ']'
x -= 1
end #end if

i += 1
end #end while

end #end if

when ']'then  x = 0
i -= 1
while x > 0 or bf[i].chr != '['
if bf[i].chr == ']'
x += 1
elsif bf[i].chr == '['
x -= 1
end #end if
i -= 1
end #end while
i -= 1

else #nothing , we ignore all extra characters

end #end case
i += 1
end   #end while
end #end method
```

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }