Swift version: 5.1
A shaped random number generator is one that generates each of its possible values but does so in a way that numbers near the middle are more frequent. For example, you might use it generate heights of characters, because most people are around average height while some outliers are much shorter or much taller. For example, if you were generating numbers between 1 and 10, 5 and 6 would be generated significantly more than 1 or 10.
GameplayKit has support for shaped random number generation using
GKGaussianDistribution. First, add an import for the GameplayKit framework:
Second, create an instance of
GKGaussianDistribution, telling it the lowest and highest values it can generate:
let distribution = GKGaussianDistribution(lowestValue: 1, highestValue: 8)
nextInt() on it as needed to generate numbers. You should get find the numbers returned are most commonly 4s and 5s, with quite a few 3s and 6s, not many 2s or 7s, and hardly any 1s or 8s.
SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred by integrating Instabug's SDK in one minute. You will automatically receive device data, network logs, and reproduction steps with every bug and crash report.
Available from iOS 9.0 – see Hacking with Swift tutorial 35
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.