Skip to content

Instantly share code, notes, and snippets.

@mikebuss
Last active March 27, 2017 01:51
Show Gist options
  • Save mikebuss/c00ebbe1c3b9c8d76cd3c91ddc8dcd19 to your computer and use it in GitHub Desktop.
Save mikebuss/c00ebbe1c3b9c8d76cd3c91ddc8dcd19 to your computer and use it in GitHub Desktop.
Counting Sheep
import Foundation
struct Input {
let numberTestCases: Int // Included in input, but not needed
let testCases: [Int]
}
func inputFromStandardInput() -> Input {
let standardInput = FileHandle.standardInput
let input = standardInput.availableData
let text = String(data: input, encoding: String.Encoding.utf8)!
let array: [Int?] = text.components(separatedBy: CharacterSet.newlines).map({Int($0)})
let filtered: [Int] = array.filter({$0 != nil}).map({$0!})
return Input(numberTestCases: filtered[0], testCases: Array(filtered[1...filtered.count-1]))
}
func lastNumberBeforeFallingAsleepForValue(value: Int) -> Int? {
guard value > 0 else { return nil }
var tally = [
0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0
]
var index = 1
var lastNumber: Int? = nil
while (tallyIsComplete(tally: tally) == false) {
lastNumber = value * index
index = index + 1
tally = updatedTallyWithValue(value: lastNumber!, tally: tally)
}
return lastNumber
}
func updatedTallyWithValue(value: Int, tally: [Int: Int]) -> [Int: Int] {
var updatedTally = tally
for character in value.description.characters.map({ Int(String($0))! }) {
updatedTally[character] = 1
}
return updatedTally
}
func tallyIsComplete(tally: [Int: Int]) -> Bool {
return tally.filter{$0.value == 0}.count == 0
}
let input = inputFromStandardInput()
for (index, value) in input.testCases.enumerated() {
let caseNumber = index + 1
if let lastNumber = lastNumberBeforeFallingAsleepForValue(value: value) {
print("Case #\(caseNumber): \(lastNumber)")
} else {
print("Case #\(caseNumber): INSOMNIA")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment