Skip to content

Instantly share code, notes, and snippets.

@siejkowski
Created November 14, 2015 17:16
Show Gist options
  • Save siejkowski/c102176f6f6461055d53 to your computer and use it in GitHub Desktop.
Save siejkowski/c102176f6f6461055d53 to your computer and use it in GitHub Desktop.
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