Swift version: 5.6
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 In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.
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.