1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-22 16:43:46 +01:00
CodeWars/5kyu/esolang_interpreters_ii/solution.swift

62 lines
1.4 KiB
Swift
Raw Normal View History

func interpreter(_ code: String, _ tape: String) -> String {
func fromTape(stringTape: String) -> [Int] {
return stringTape.map({ c in (c == "0") ? 0 : 1 })
}
func toTape(intTape: [Int]) -> String {
return intTape.reduce("", { x, b in x + (b == 0 ? "0" : "1") })
}
func findComplement(direction: Int, startIndex: Int, l: Character, r: Character) -> Int {
var depth = 0
var i = startIndex
repeat {
let c = code[code.index(code.startIndex, offsetBy: i)]
if c == l {
depth += 1
} else if c == r {
depth -= 1
}
i += direction
} while depth != 0
return i
}
var bits = fromTape(stringTape: tape)
var i = 0
var codeIndex = 0
while codeIndex >= 0 && codeIndex < code.count {
switch code[code.index(code.startIndex, offsetBy: codeIndex)] {
case ">":
i += 1
case "<":
i -= 1
case "*":
bits[i] = (bits[i] + 1) % 2
case "[":
if bits[i] == 0 {
codeIndex = findComplement(direction: 1, startIndex: codeIndex, l: "[", r: "]") - 1
}
case "]":
if bits[i] != 0 {
codeIndex = findComplement(direction: -1, startIndex: codeIndex, l: "]", r: "[")
}
default:
break
}
codeIndex += 1
if i < 0 || i >= bits.count {
break
}
}
return toTape(intTape: bits)
}