Skip to content

Instantly share code, notes, and snippets.

@kognate
Created November 3, 2015 04:21
Show Gist options
  • Save kognate/fe4466575bee3da1ae42 to your computer and use it in GitHub Desktop.
Save kognate/fe4466575bee3da1ae42 to your computer and use it in GitHub Desktop.
The Accelerate Framework is awesome
//
// main.swift
// conways
//
// Created by Josh Smith on 11/2/15.
// Copyright © 2015 Josh Smith. All rights reserved.
//
import Foundation
import Cocoa
import Accelerate
import GameplayKit
func printPopulation(pop: [Double], col: Int, row: Int) {
system("clear")
let char = Character("-")
let dotted = String(count: 2 + (col * 2), repeatedValue: char)
print(dotted)
for j in 0...(row-1) {
print("|", terminator: "")
for i in pop[(j * col)..<(j * col)+col] {
switch (i) {
case 1.0: print("* ",terminator: "")
default: print(" ",terminator: "")
}
}
print("|")
}
print(dotted)
NSThread.sleepForTimeInterval(0.05)
}
func genPopulation(col: Int, row: Int) -> [Double] {
var res: [Double] = []
let rand = GKGaussianDistribution(randomSource: GKRandomSource(), lowestValue: 1, highestValue: 100)
for _ in 1...col {
for _ in 1...row {
let nInt = rand.nextInt()
switch nInt {
case _ where nInt < 60:
res.append(1.0)
default:
res.append(0.0)
}
}
}
return res
}
let convMatrix = [ 1.0, 1.0, 1.0,
1.0, 0.0, 1.0,
1.0, 1.0, 1.0 ]
func runGeneration(population: [Double], row: Int, col: Int, generations: Int, inout buffer: [Double], complete: ((result:[Double]) -> Void)) {
guard generations > 0 else {
return
}
vDSP_f3x3D(population, vDSP_Length(row), vDSP_Length(col), convMatrix, &buffer)
let nextstep = buffer.enumerate().map { (index, element) -> Double in
switch (element) {
case _ where (element > 1.0 && element <= 2.0):
return population[index]
case _ where (element < 4.0 && element >= 3.0):
return 1.0
default:
return 0.0
}
}
printPopulation(population, col: col, row: row)
var resultSum: Double = 0.0
vDSP_sveD(population, 1, &resultSum, vDSP_Length(col * row))
guard resultSum > 1.0 else {
return
}
complete(result: nextstep)
runGeneration(nextstep, row: row, col: col, generations: generations - 1, buffer: &buffer, complete: complete)
}
func startRandom(col: Int, row: Int, generations: Int) {
let population = genPopulation(col, row: row)
var arg = [Double](count:col*row, repeatedValue: 0.0)
runGeneration(population, row: row, col: col, generations: generations, buffer: &arg) { (newpopulation) in
printPopulation(newpopulation, col: col, row: row)
}
}
startRandom(50, row: 50, generations: 3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment