Last active
August 29, 2015 14:11
-
-
Save ayato-p/8e0eb12def5f674344eb to your computer and use it in GitHub Desktop.
This file contains 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
fun Int.isZero() = this == 0 | |
fun Int.lt(other: Int) = this < other | |
fun Int.lte(other: Int) = this <= other | |
fun Int.gt(other: Int) = this > other | |
fun Int.gte(other: Int) = this >= other | |
class KotlinF_ck { | |
private var tokens = charArray() | |
private var jumps = hashMapOf<Int, Int>() | |
fun parse(src: String) { | |
tokens = src.toCharArray() | |
var starts = arrayListOf<Int>() | |
tokens.withIndices().forEach { pair -> | |
val (i, c) = pair | |
when(c){ | |
'[' -> starts.add(i) | |
']' -> { | |
val j = starts.last() | |
jumps.put(j, i) | |
jumps.put(i, j) | |
starts.remove(starts.lastIndex) | |
} | |
} | |
} | |
} | |
fun run() { | |
var tape = arrayListOf<Int>() | |
var programCounter = 0 | |
var cursor = 0 | |
while(programCounter < tokens.size) { | |
when(tokens[programCounter]){ | |
'k' -> { | |
if(tape.size lte cursor) { tape.add(0) } | |
tape[cursor]++ | |
} | |
'o' -> { | |
if(tape.size lte cursor) { tape.add(0) } | |
tape[cursor]-- | |
} | |
't' -> print(tape[cursor].toInt().toChar()) | |
'l' -> null | |
'i' -> cursor++ | |
'n' -> cursor-- | |
'[' -> { | |
if(tape[cursor].isZero()){ programCounter = jumps[programCounter] } | |
} | |
']' -> { | |
if(!tape[cursor].isZero()){ programCounter = jumps[programCounter] } | |
} | |
} | |
programCounter++ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment