Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. enum BrainfuckError: Error {
  2. case NotImplementedInstruction(Character)
  3. case InvalidInstruction(Character)
  4. }
  5.  
  6. class Brainfuck
  7. {
  8. var buffer: Array<Int>
  9. var dataPointer = 0
  10.  
  11. init(buffer: Int) {
  12. self.buffer = Array(repeating: 0, count: buffer)
  13. }
  14.  
  15. func run(program: String) throws -> String {
  16. var result = ""
  17.  
  18. var instructionPointer = program.characters.startIndex
  19. while (instructionPointer < program.characters.endIndex) {
  20. let c = program[instructionPointer]
  21. switch c {
  22. case "+":
  23. buffer[dataPointer] += 1
  24. case "-":
  25. buffer[dataPointer] -= 1
  26. case ">":
  27. dataPointer += 1
  28. case "<":
  29. dataPointer -= 1
  30. case ".":
  31. result += String(charcterByAscii(code: buffer[dataPointer]))
  32. case ",":
  33. throw BrainfuckError.NotImplementedInstruction(c)
  34. case "[":
  35. if buffer[dataPointer] == 0 {
  36. while (program[instructionPointer] != "]") {
  37. instructionPointer = program.characters.index(after: instructionPointer)
  38. }
  39. instructionPointer = program.characters.index(after: instructionPointer)
  40. }
  41. case "]":
  42. if buffer[dataPointer] != 0 {
  43. while (program[instructionPointer] != "[") {
  44. instructionPointer = program.characters.index(before: instructionPointer)
  45. }
  46. instructionPointer = program.characters.index(before: instructionPointer)
  47. }
  48. default:
  49. throw BrainfuckError.InvalidInstruction(c)
  50. }
  51.  
  52. instructionPointer = program.characters.index(after: instructionPointer)
  53. }
  54. return result
  55. }
  56.  
  57. func debugBuffer() {
  58.  
  59. for i in 0..<buffer.count {
  60. if i == dataPointer {
  61. print("#\(buffer[i])#", terminator:", ")
  62. } else {
  63. print(buffer[i], terminator:", ")
  64. }
  65. }
  66. }
  67.  
  68. func charcterByAscii(code: Int) -> Character {
  69. return Character(UnicodeScalar(code)!)
  70. }
  71. }
  72.  
  73.  
  74. let brainfuck = Brainfuck(buffer: 100)
  75. let program = "+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.------------.<++++++++.--------.+++.------.--------.>+."
  76. do {
  77. let result = try brainfuck.run(program: program)
  78. print(result) // "Hello, world!"
  79. brainfuck.debugBuffer()
  80. } catch BrainfuckError.NotImplementedInstruction(let c) {
  81. print("\(c) is not implemented yet.")
  82. } catch BrainfuckError.InvalidInstruction(let c) {
  83. print("\(c) is invalid instruction.")
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement