Last active
April 26, 2017 22:28
-
-
Save acrookston/45de3a7ff465e266016102f1de5b6d06 to your computer and use it in GitHub Desktop.
coding test
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
import Foundation | |
// Given some sorted dates find out if the set contains 5 dates within 30 days of eachother. | |
// I.e. Given a user's login dates, find out if they were logged in 5 or more times in 30 days. | |
extension Date { | |
static func parse(_ str: String) -> Date { | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "yyyy-MM-dd" | |
return dateFormatter.date(from: str)! | |
} | |
func format() -> String { | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "yyyy-MM-dd" | |
return dateFormatter.string(from: self) | |
} | |
} | |
let dates: [Date] = [ | |
.parse("2000-01-01"), | |
.parse("2000-01-02"), | |
.parse("2000-01-03"), | |
.parse("2000-01-04"), | |
.parse("2000-02-06"), | |
.parse("2000-02-07"), | |
.parse("2000-02-08"), | |
.parse("2000-02-09"), | |
.parse("2000-02-10"), | |
] | |
let MONTH : TimeInterval = 30 * 24 * 3600 | |
func matching(_ dates: [Date]) -> Bool { | |
for ix in (0..<dates.count - 4) { | |
if dates[ix + 4].timeIntervalSince(dates[ix]) < MONTH { | |
print("Matched with \(dates[ix].format()) \(dates[ix + 4].format())") | |
return true | |
} | |
} | |
return false | |
} | |
print(matching(dates) ? "YEP" : "NOPE") | |
After removing 2000-01-05
Output
2000-01-01 2000-01-01 false 0
2000-01-02 2000-01-01 false 1
2000-01-03 2000-01-01 false 2
2000-01-04 2000-01-01 false 3
2000-02-06 2000-01-01 true 4
2000-02-06 2000-01-01 true 4 inside
2000-02-06 2000-01-02 true 3 inside
2000-02-06 2000-01-03 true 2 inside
2000-02-06 2000-01-04 true 1 inside
2000-02-07 2000-02-06 false 1
2000-02-08 2000-02-06 false 2
2000-02-09 2000-02-06 false 3
2000-02-10 2000-02-06 false 4
Matched at 2000-02-10 08:00:00 +0000
YEP
New version output (with 2000-01-05
removed):
Matched with 2000-02-06 2000-02-10
YEP
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output