1

I'm trying to use GKShuffledDistribution in one of my apps but the nextInt(upperBound:) method doesn't work the same as the nextInt method in that it doesn't exhaust all possible values. To demonstrate, open a playground and do this:

import GameplayKit
let shuffled = GKShuffledDistribution.init(lowestValue: 0, highestValue: 100)

for _ in 0...25{
    shuffled.nextInt(upperBound: 100)
}

I got 2 duplicates using this method. If I replaced it with:

shuffled.nextInt()

I don't get any duplicates. Is this how nextInt(upperBound:) supposed to work? If it is, can some one point me to documentation explaining this? Thanks.

Jack Ngai
  • 157
  • 1
  • 9

1 Answers1

1

upperBound is provided to let you ask for a random value between your lowestValue and a new (temporary) highestValue that's less than the highestValue you've set when creating your GKShuffledDistribution instance.

Oops. That's mealy mouthed.

Let me try this more pictorially.

IF you normally want a random number between 0 and 20, but sometimes you want one that's only between 0 and 10, from this same shuffle, then you can set upperBound to 10 and a number will be "pulled out" that's between 0 and 10, of the numbers left in your current shuffle cycle.

Well... at least I think that's how it's supposed to work.

Theoretically, when you set the upperBound to 100, as in your example, the highestValue should be the determinant of activity, since the docs suggest:

The actual upper bound on numbers generated by this method is the lesser of the highestValue property and the upperBound parameter.

Confused
  • 6,048
  • 6
  • 34
  • 75
  • Thanks for helping me trying to understand this. So when I used `upperBound` in the for loop, it was temporarily changing that value to 100 every time I went through the for loop, causing the duplicates that I was seeing. Is this correct? – Jack Ngai Jan 27 '17 at 00:15
  • I'm not entirely sure how it works when you use the same number as your `highestValue`. Or how many numbers you're pumping out before you see repeats. There might be a bug. GameplayKit is used by about 3 people, so it wouldn't have been thoroughly tested. – Confused Jan 27 '17 at 08:28
  • So I tested this in the playground by setting upperBound to 5 and the for loop 0...3. The results I got were "4, 0, 1, 1", confirming your original answer that upperBound becomes the temporary "highestValue" in the for loop. Once the loop iterates, no memory of the temporary "highestValue" is retained, thus I got a repeated value before all possible values were selected. Your answer help me understand this parameter when Apple failed to do so. Thank you. – Jack Ngai Feb 01 '17 at 04:51