0

Is there any way to seed the random number generator and also specify an upper bound in Swift 3?

BCRwar3
  • 45
  • 1
  • 11
  • 1
    If you're seeding the random number generator, aren't you using the wrong random number generator? `arc4random_uniform` doesn't need seeding. – matt Jan 01 '17 at 22:11
  • Yes but the project I am working on requires the random number generator to be seeded. (I am attempting the Perlin Noise Algorithm in Swift 3) – BCRwar3 Jan 01 '17 at 22:14
  • [How does one generate a random number in Apple's Swift language?](http://stackoverflow.com/questions/24007129/how-does-one-generate-a-random-number-in-apples-swift-language) – clearlight Jan 01 '17 at 22:25
  • 1
    Well, a common way is to use `arc4random_uniform("upper bound")`. This solves the upper bound problem but this is an unseeded random number generator. There also exists `srand48("seed")`, this plants the seed and then you can use `drand48()` to produce a random number between 0.0 and 1.0, this solves the seeding problem but does not allow you to produce a number out of the range of 0.0 and 1.0. – BCRwar3 Jan 01 '17 at 22:31
  • 1
    Never used drand48() but can't you just multiply its 0.0 to 1.0 output by your upper bound? – Ali Beadle Jan 01 '17 at 22:39

1 Answers1

0

The most convenient random number generators in Swift reside in GameKit. This generates random integers between -10 and 10 (inclusive):

import GameKit
let source = GKARC4RandomSource(seed: Data(bytes: [42]))
let random = GKRandomDistribution(randomSource: source, lowestValue: -10, highestValue: 10)

for _ in 0..<10 {
    print(random.nextInt())
}
Code Different
  • 90,614
  • 16
  • 144
  • 163