Created
March 28, 2010 07:22
-
-
Save ananthakumaran/346624 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* @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