Created
November 14, 2015 17:16
-
-
Save siejkowski/c102176f6f6461055d53 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func ==(lhs: Cell, rhs: Cell) -> Bool { | |
return lhs.hashValue == rhs.hashValue | |
} | |
struct Cell: Hashable { | |
let a: Int | |
let b: Int | |
init(_ newA: Int, _ newB: Int) { | |
a = newA | |
b = newB | |
} | |
var hashValue: Int { get { | |
return "(\(a),\(b))".hashValue | |
} } | |
} | |
typealias Board = Set<Cell> | |
func neighbours(cell: Cell) -> Set<Cell> { | |
return [ | |
Cell(cell.a-1, cell.b-1), | |
Cell(cell.a-1, cell.b), | |
Cell(cell.a-1, cell.b+1), | |
Cell(cell.a, cell.b-1), | |
Cell(cell.a, cell.b+1), | |
Cell(cell.a+1, cell.b-1), | |
Cell(cell.a+1, cell.b), | |
Cell(cell.a+1, cell.b+1) | |
]; | |
} | |
func step(board: Board) -> Board { | |
let living = Set(board.filter { cell -> Bool in | |
let count = board.intersect(neighbours(cell)).count | |
return count == 2 || count == 3 | |
}) | |
let newCells = Set(board.map { cell -> Set<Cell> in | |
neighbours(cell) | |
} | |
.reduce(Dictionary<Cell, Int>()) { (dict, cells) -> Dictionary<Cell, Int> in | |
var newDict = dict | |
cells.forEach { cell in | |
newDict.updateValue((newDict[cell] ?? 0) + 1, forKey: cell) | |
} | |
return newDict | |
} | |
.filter { (cell, count) -> Bool in | |
count == 3 | |
} | |
.map { (cell, count) in cell }) | |
return Board(living.union(newCells)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment