Last active
February 15, 2017 01:39
-
-
Save vkelembet/3c4e10361f7511b408a29ec44cf590fe to your computer and use it in GitHub Desktop.
Code example for question on Stack Overflow: https://stackoverflow.com/questions/42236846/generate-number-in-certain-range-from-current-date-of-device-in-swift-3
This file contains hidden or 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 UIKit | |
| func date(from dateString: String) -> Date? { | |
| let dateFormatter = DateFormatter() | |
| dateFormatter.dateFormat = "d/M/yyyy" | |
| dateFormatter.locale = Locale.init(identifier: "en_GB") | |
| return dateFormatter.date(from: dateString) | |
| } | |
| func components(from date: Date) -> DateComponents { | |
| let calendar = Calendar(identifier: .gregorian) | |
| return calendar.dateComponents([.day, .month, .year], from: date) | |
| } | |
| func seed(fromDay day: Int, month: Int, year: Int) -> Int { | |
| return year * 372 + month * 31 + day | |
| } | |
| func random(usingSeed seed: Int) -> Int { | |
| srand48(seed) | |
| let random = drand48() | |
| return Int(floor(random * 1000)) | |
| } | |
| func random(fromDateString dateString: String) -> Int? { | |
| guard let date = date(from: dateString) else { | |
| return nil | |
| } | |
| let comp = components(from: date) | |
| guard let day = comp.day, let month = comp.month, let year = comp.year else { | |
| return nil | |
| } | |
| let seedValue = seed(fromDay: day, month: month, year: year) | |
| return random(usingSeed: seedValue) | |
| } | |
| random(fromDateString: "14/2/2017") // 223 | |
| random(fromDateString: "14/2/2017") // 223 | |
| random(fromDateString: "15/2/2017") // 94 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment