根据今天的日期,以一致的顺序随机排列数组 - Swift
Shuffle an array with a consistent order, based on today's date - Swift
我想打乱 Any
个对象的数组,但在当前日历日执行打乱时顺序应该保持一致。
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
所以想要一些我用今天的日期作为种子的随机顺序生成器,例如
let todayAtMidnight = Calendar.current.startOfDay(for: Date())
let secondsSince1970UntilTodayAtMidnight = todayAtMidnight.timeIntervalSince1970
我看过 shuffle(using:)
,但我可以将它传递给它一个用我的约会对象作为种子的生成器吗,或者我可以使用其他东西吗?
是这样的吗?
我查找了如何播种随机数生成器并找到了这个主题:
Generating random numbers in swift
使用您的技术将今天的午夜日期作为数字...您可以为数字生成器播种并在每个午夜日期获得相同的随机序列。
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)
打印出今天的日期:
[2, 3, 4, 1, 5]
按照丹尼尔的建议,可以设置一个扩展程序来玩一下:
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)
我想打乱 Any
个对象的数组,但在当前日历日执行打乱时顺序应该保持一致。
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
所以想要一些我用今天的日期作为种子的随机顺序生成器,例如
let todayAtMidnight = Calendar.current.startOfDay(for: Date())
let secondsSince1970UntilTodayAtMidnight = todayAtMidnight.timeIntervalSince1970
我看过 shuffle(using:)
,但我可以将它传递给它一个用我的约会对象作为种子的生成器吗,或者我可以使用其他东西吗?
是这样的吗?
我查找了如何播种随机数生成器并找到了这个主题: Generating random numbers in swift
使用您的技术将今天的午夜日期作为数字...您可以为数字生成器播种并在每个午夜日期获得相同的随机序列。
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)
打印出今天的日期:
[2, 3, 4, 1, 5]
按照丹尼尔的建议,可以设置一个扩展程序来玩一下:
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)