Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivanbruel/b669294c7604b5f3f6a8345074d3d561 to your computer and use it in GitHub Desktop.
Save ivanbruel/b669294c7604b5f3f6a8345074d3d561 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
struct Domino {
let left: Int
let right: Int
init(string: String) {
let split = string.componentsSeparatedByString("-")
left = split.first.flatMap { Int($0) } ?? 0
right = split.last.flatMap { Int($0) } ?? 0
}
func matches(nextDomino: Domino) -> Bool {
return right == nextDomino.left
}
}
func matchCount(dominoString: String) -> Int {
let dominos = dominoString.componentsSeparatedByString(",").map { Domino(string: $0) }
let nextDominos = Array(dominos[1..<dominos.count])
var matches = [Int]()
for index in 0..<nextDominos.count {
let domino = dominos[index]
let nextDomino = nextDominos[index]
let lastMatch = matches.last ?? 0
matches.append(domino.matches(nextDomino) ? lastMatch + 1 : 1)
}
return matches.maxElement() ?? 1
}
func readFile() -> [Int] {
do {
if let fileURL = NSBundle.mainBundle().URLForResource("dominos", withExtension: "txt") {
let file = try String(contentsOfURL: fileURL)
let lines = file.componentsSeparatedByString("\n")
return lines.map { matchCount($0) }
}
} catch (let e) { print(e) }
return []
}
readFile()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment