Skip to content

Instantly share code, notes, and snippets.

@heyLu
Created November 8, 2012 16:10
Show Gist options
  • Select an option

  • Save heyLu/4039769 to your computer and use it in GitHub Desktop.

Select an option

Save heyLu/4039769 to your computer and use it in GitHub Desktop.
A few thoughts about brainfuck.

A simple C program:

int x = 10;
int y = 10;

if (x == y) {
  x += 3;
else {
  x -= 3;
}

printf("%d\n", x);

A translation of that as a brainfuck program.

++++++++++             |x| store x
>                      |x|0|
++++++++++             |x|y| store y

duplicate x
<[->>+>+<<<]           |_0_|y|x|x| duplicate x
>>>[-<<<+>>>]          |x|y|x|_0_| restore x in the original position

duplicate y
<<[->>+>+<<<]          |x|_0_|x|y|y|
>>>[-<<<+>>>]          |x|y|x|y|_0_|

compare x and y
<<[>>+<<-]             |x|y|_0_|y|x|
>[>-<-]>               |x|y|0|0|_x minus y_|

<+>                    |x|y|0|1|_x minus y_|

[ else
	<-
	<<<---
	>>>>
	[+]
]

<

[ if x == y
	<<<+++
	>>>-
]

<<<.
#

Multiplication is fun!

++++++++++
>+++

<[->>>+>+<<<<]
>>>>[<<<<+>>>>-]    |10|3|0|10|_0_|

<[
  -
  <<[->>>+>+<<<<]
  >>>>[<<<<+>>>>-]  |10|3|0|10|3|_0_|

  <[-<<+>>]         |10|3|3|9|_0_|

  <
]
#!/usr/bin/env ruby
class Brainfuck
attr_accessor :program
def initialize(program = "")
@cells = Array.new(30000) { |x| 0 }
@instruction_pointer = 0
@data_pointer = 0
@program = program
end
def step
print @program[@instruction_pointer] if ENV['VERBOSE']
case @program[@instruction_pointer]
when '+'
@cells[@data_pointer] += 1
when '-'
@cells[@data_pointer] -= 1
when '>'
@data_pointer += 1
when '<'
@data_pointer -= 1
when '.'
printf "%c", @cells[@data_pointer]
when ','
throw NotImplementedException.new "whoops, not implemented!"
when '['
if @cells[@data_pointer] == 0
while @program[@instruction_pointer] != ']' do @instruction_pointer += 1 end
return
end
when ']'
if @cells[@data_pointer] != 0
while @program[@instruction_pointer] != '[' do @instruction_pointer -= 1 end
return
end
when '#'
printf " |_%d_|%d|%d|%d|%d| ", *@cells[@data_pointer, 5] if ENV['DEBUG']
end
raise Exception.new "data pointer out of range: #@data_pointer" if @data_pointer < 0 or @data_pointer >= @cells.length
@instruction_pointer += 1
end
def run
while @instruction_pointer < @program.length do
step()
end
end
end
if ARGV[0]
Brainfuck.new(ARGV[0]).run()
else
program = ""
STDIN.each do |line|
program += line
end
Brainfuck.new(program).run()
end
@rdebath
Copy link

rdebath commented Aug 10, 2014

Your loops are broken ...

>++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>
->+++++++.<+[>[+>]>]<<<+++++++++++++++.>>.+++.------.--------.>>+.>++++.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment