A generator for random numbers that are uniformly distributed across many samplings, but where short sequences of similar values are unlikely.
SDKs
- iOS 9.0+
- macOS 10.11+
- Mac Catalyst 13.0+
- tvOS 9.0+
Framework
- Gameplay
Kit
Declaration
class GKShuffledDistribution : GKRandom Distribution
Overview
The behavior of a shuffled distribution is sometimes called “fair” randomization, because true randomness in games can result in extended “lucky streaks” or “unlucky streaks” for players. To create a shuffled distribution and use it to generate random numbers, use the methods defined by its superclass GKRandom
.
The GKShuffled
class inherits its entire interface from its superclass—to initialize and use a shuffled distribution, use the methods listed in GKRandom
. A shuffled distribution differs from its superclass in behavior only. Consider the code snippets below:
// Uniform distribution
let uniform = GKRandomDistribution.d6()
for _ in 1...100 { print(uniform.nextInt()) }
// Shuffled distribution
let shuffled = GKShuffledDistribution.d6()
for _ in 1...100 { print(shuffled.nextInt()) }
In this example, each distribution generates 100 random integers from a simulated six-sided die. In both cases, the distribution of results is roughly uniform—that is, the number of occurrences of any specific value is about the same as that of any other value. However, the shuffled distribution makes sure not to repeat any one value until it has used all of its possible values. In this example, if the die rolls a 1, the shuffled distribution will not generate another 1 for at least five more rolls.
Important
The randomization services provided in GameplayKit are suitable for reliably creating deterministic, pseudorandom gameplay mechanics, but are not cryptographically robust. For cryptography, obfuscation, or cipher uses, use the Security framework, described in Cryptographic Services Guide.
For more information on choosing and using randomizers in GameplayKit, read Randomization in GameplayKit Programming Guide.