Skip to content

Instantly share code, notes, and snippets.

@alexdrone
Created January 5, 2016 14:03
Show Gist options
  • Save alexdrone/457062a561c7f9189746 to your computer and use it in GitHub Desktop.
Save alexdrone/457062a561c7f9189746 to your computer and use it in GitHub Desktop.
import UIKit
//17.2
public enum TicTacToe { case X, O, Empty }
var matrix = Matrix<TicTacToe>(rows: 3, columns: 3, repeatedValue: TicTacToe.Empty)
var m1 = matrix
m1[0,0] = TicTacToe.X
m1[1,1] = TicTacToe.X
m1[2,2] = TicTacToe.X
m1
extension Matrix where T: TicTacToe {
public func hasWon(player: TicTacToe) -> Bool {
assert(player != TicTacToe.Empty)
assert(self.rows == 3 && self.columns == 3)
//check rows
for r in 0..<self.rows {
var found = true
for c in 0..<self.columuns { found &= self[r,c] == player }
if found { return true }
}
//check columns
for c in 0..<self.colums {
var found = true
for r in 0..<self.rows { found &= self[r,c] == player }
if found { return true }
}
//check diagonal
var i = 0
var j = 0
var found = true
while i < self.rows {
found = self[i,j] == player
i++
j++
}
if found { return true }
//check back diagonal
i = self.rows
j = 0
found = true
while j < self.rows {
found = self[i,j] == player
i--
j++
}
if found { return true }
return false
}
}
print(m1.hasWon(TicTacToe.X))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment