Skip to content

Instantly share code, notes, and snippets.

@ananthakumaran
Created March 28, 2010 07:22
Show Gist options
  • Save ananthakumaran/346624 to your computer and use it in GitHub Desktop.
Save ananthakumaran/346624 to your computer and use it in GitHub Desktop.
/*
* @author ananthakuaran
*/
object BrainFuck {
val MAX_SIZE = 30000
var pointer = 0
val memory = new Array[Byte](MAX_SIZE)
def main(args:Array[String]) = {
execute("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.")
}
def execute(code:String):Unit = {
var x = 0
while(x < code.length) {
code(x) match {
case '>' => pointer += 1
case '<' => pointer -= 1
case '+' => memory(pointer) = (memory(pointer) + 1).toByte
case '-' => memory(pointer) = (memory(pointer) - 1).toByte
case '.' => print(memory(pointer).toChar)
case ',' => memory(pointer) = readByte()
case '[' => {
var brackets = 1
val block = code.substring(x+1).takeWhile(ch => {
if(ch == '[')
brackets += 1
if(ch == ']')
brackets -= 1
!(brackets == 0)
})
while(memory(pointer) != 0)
{
execute(block)
}
x += block.length + 1
}
case ' ' =>
case _ => { println(code(x) + " WTF is this")}
}
x += 1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment