jweinst1
10/22/2016 - 11:50 PM

cellular automatan virtual machine in swift

cellular automatan virtual machine in swift

//: Playground - noun: a place where people can play

import Cocoa

//virtual machine for cellular automatan


struct Rule {
    let req:Int
    let other:Int
    let ofs:Int
    let new:Int
    
}

struct Grid {
    var table = Array(repeating:Array(repeating:0, count:10), count:10)
    
    subscript(x:Int, y:Int) -> Int {
        get {
            assert(x >= 10 && y >= 10, "Index out of range")
            return table[x][y]
        }
        
        set {
            table[x][y] = newValue
        }
    }
}

struct Machine {
    var mat:Grid
    var rules:[Rule]
    var generations:Int
    var ready:Bool
    
    init(time:Int){
        assert(time > 0, "Generations must be at least 1.")
        self.generations = time
        self.mat = Grid()
        self.rules = [Rule]()
        self.ready = false
    }
    
    mutating func createRule(req:Int, other:Int, ofs:Int, new:Int) -> Void {
        self.rules.append(Rule(req:req, other:other, ofs:ofs, new:new))
    }
    
    mutating func setMat(numbers:inout [Int]) -> Void {
        assert(numbers.count == 100, "Must set the machine with 100 ints.")
        while let next = numbers.popLast() {
            for i in 0..<10 {
                for j in 0..<10 {
                    self.mat[i, j] = next
                }
            }
        }
        self.ready = true
    }
    
    mutating func transform() -> Void {
        while self.generations > 0 {
            for rule in self.rules {
                for i in 0..<10 {
                    for j in 0..<10 {
                        if self.mat[i, j] == rule.req && self.mat[i, j+rule.ofs] == rule.other {
                            self.mat[i, j] = rule.other
                        }
                    }
                }
            }
            self.generations -= 1
        }
    }
    
    func repr() -> String {
        return String(describing: self.mat.table)
    }
}

struct Parser {
    
}