読者です 読者をやめる 読者になる 読者になる

SwiftでBrainF*ckインタープリタを作った

一応作ったんだけど標準入力をどうやって取ればいいか分かんなくて","が実装できてない。

BrainF*ckが分かんない人はWikipediaで。

Brainfuck - Wikipedia


ソース

class BrainFuck {
    var mem: Int[] = []
    var code_arr: Character[] = []
    var pointer = 0
    var counter = 0
    var index = 0
    var length = 0
    var characters = [" ","!","\"","#","$","%","&","\'","(",")","*",
                      "+",",","-",".","//","0","1","2","3","4","5",
                      "6","7","8","9",":",";","<","=",">","?","@","A",
                      "B","C","D","E","F","G","H","I","J","K","L","M",
                      "N","O","P","Q","R","S","T","U","V","W","X","Y",
                      "Z","[","\\","]","^","_","`","a","b","c","d","e",
                      "f","g","h","i","j","k","l","m","n","o","p","q",
                      "r","s","t","u","v","w","x","y","z","{","|","}","~"]
    
    init() {
        for index in 1...1024 {
            mem += 0
        }
    }

    func run(code: String) {
        for c in code {
            code_arr += c
            length++
        }
        
        while index < length {
            process(code_arr[index])
            index++
            //sleep()
        }
    }

    func process(c: Character) {
        switch c {
            case ".":
                print(intToChar(mem[pointer]))
            case ">":
                pointer += 1
            case "<":
                pointer -= 1
            case "+":
                mem[pointer]++
            case "-":
                mem[pointer] -= 1
            case ",":
                print()
            case "[":
                if (mem[pointer] == 0) {
                    while code_arr[index] != "]" {
                        index++
                    }
                    index++
                }
            case "]":
                if (mem[pointer] != 0) {
                    while code_arr[index] != "[" {
                        index--
                    }
                    index--
                }
            default:
                print("\0")
        }
    }


    func intToChar(num: Int) -> String {
        var index = num - 32
        if (index < 0 || index >= 95) {
            return "\0"
        }
        return characters[index]
    }
    
    func sleep() {
        for i in 1..100000 {}
    }
}

var bf = BrainFuck()
bf.run("+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.------------.<++++++++.--------.+++.------.--------.>+.")
println()

実行結果

Hello,world!


組み込み関数の一覧どっかにないかな。