Created
July 8, 2016 11:14
-
-
Save ivanbruel/b669294c7604b5f3f6a8345074d3d561 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
//: 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