简体   繁体   中英

Shuffle an array with a consistent order, based on today's date - Swift

I want to shuffle an array of Any objects, but the order should remain consistent any time I perform the shuffle during the current calendar day.

let myArray = [1, 2, 3, 4, 5]
print(myArray.myShuffleForDateFunction(Date()))

//output today is always e.g. [3, 5, 1, 2, 4] 
//output tomorrow is always e.g. [1, 4, 5, 3, 2], etc

So want some random order generator that I seed with today's date, eg

let todayAtMidnight = Calendar.current.startOfDay(for: Date())
let secondsSince1970UntilTodayAtMidnight = todayAtMidnight.timeIntervalSince1970

I've looked at shuffle(using:) , but can I pass it a generator seeded with my date, or is there something else I can use?

Something like this?

I looked up how to seed random number generators and found this topic: Generating random numbers in swift

Using your technique to get todays midnight date as a number... you can seed the number generator and get the same random sequence per midnight date.

import GameplayKit

let myArray = [1, 2, 3, 4, 5]

let calendar = Calendar.current
let todayAtMidnight = calendar.startOfDay(for: Date())
let seed = UInt64(todayAtMidnight.timeIntervalSince1970)

var mersenneTwister = GKMersenneTwisterRandomSource(seed: seed)
let fixedArrayByDate = mersenneTwister.arrayByShufflingObjects(in: myArray)
print(fixedArrayByDate)

This prints out for today's date:

[2, 3, 4, 1, 5]

As suggested by Daniel, one could set up an extension for fun:

import GameplayKit

extension Array {
    func shuffledByDate(_ date: Date) -> [Any] {
        let calendar = Calendar.current
        let todayAtMidnight = calendar.startOfDay(for: date)
        let seed = UInt64(todayAtMidnight.timeIntervalSince1970)
        
        let mersenneTwister = GKMersenneTwisterRandomSource(seed: seed)
        return mersenneTwister.arrayByShufflingObjects(in: self)
    }
}

let myArray = [1, 2, 3, 4, 5].shuffledByDate(Date())
print(myArray)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM