How to use the clock as a random generator seed in Swift

1 Answer

0 votes
import Foundation

// Seed the default random number generator using the current time
let seed = time(nil)
srand(UInt32(seed))

// Now you can use the standard random functions
let min = 1
let max = 10

let randomNumber1 = Int.random(in: min...max)
print("Random integer (seeded with clock): \(randomNumber1)")
let randomNumber2 = Int.random(in: min...max)
print("Random integer (seeded with clock): \(randomNumber2)")

let randomDouble1 = Double.random(in: 0.0...1.0)
print("Random double (seeded with clock): \(randomDouble1)")
let randomDouble2 = Double.random(in: 0.0...1.0)
print("Random double (seeded with clock): \(randomDouble2)")



/*
run:

Random integer (seeded with clock): 6
Random integer (seeded with clock): 2
Random double (seeded with clock): 0.30106979117394617
Random double (seeded with clock): 0.79302013280023

*/

 



answered May 8 by avibootz
...