Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- enum BrainfuckError: Error {
- case NotImplementedInstruction(Character)
- case InvalidInstruction(Character)
- }
- class Brainfuck
- {
- var buffer: Array<Int>
- var dataPointer = 0
- init(buffer: Int) {
- self.buffer = Array(repeating: 0, count: buffer)
- }
- func run(program: String) throws -> String {
- var result = ""
- var instructionPointer = program.characters.startIndex
- while (instructionPointer < program.characters.endIndex) {
- let c = program[instructionPointer]
- switch c {
- case "+":
- buffer[dataPointer] += 1
- case "-":
- buffer[dataPointer] -= 1
- case ">":
- dataPointer += 1
- case "<":
- dataPointer -= 1
- case ".":
- result += String(charcterByAscii(code: buffer[dataPointer]))
- case ",":
- throw BrainfuckError.NotImplementedInstruction(c)
- case "[":
- if buffer[dataPointer] == 0 {
- while (program[instructionPointer] != "]") {
- instructionPointer = program.characters.index(after: instructionPointer)
- }
- instructionPointer = program.characters.index(after: instructionPointer)
- }
- case "]":
- if buffer[dataPointer] != 0 {
- while (program[instructionPointer] != "[") {
- instructionPointer = program.characters.index(before: instructionPointer)
- }
- instructionPointer = program.characters.index(before: instructionPointer)
- }
- default:
- throw BrainfuckError.InvalidInstruction(c)
- }
- instructionPointer = program.characters.index(after: instructionPointer)
- }
- return result
- }
- func debugBuffer() {
- for i in 0..<buffer.count {
- if i == dataPointer {
- print("#\(buffer[i])#", terminator:", ")
- } else {
- print(buffer[i], terminator:", ")
- }
- }
- }
- func charcterByAscii(code: Int) -> Character {
- return Character(UnicodeScalar(code)!)
- }
- }
- let brainfuck = Brainfuck(buffer: 100)
- let program = "+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.------------.<++++++++.--------.+++.------.--------.>+."
- do {
- let result = try brainfuck.run(program: program)
- print(result) // "Hello, world!"
- brainfuck.debugBuffer()
- } catch BrainfuckError.NotImplementedInstruction(let c) {
- print("\(c) is not implemented yet.")
- } catch BrainfuckError.InvalidInstruction(let c) {
- print("\(c) is invalid instruction.")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement