NEW: Master Swift design patterns with my latest book! >>

How to generate shaped random numbers using GKGaussianDistribution

Written by Paul Hudson    @twostraws

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:

import GameplayKit

Second, create an instance of GKGaussianDistribution, telling it the lowest and highest values it can generate:

let distribution = GKGaussianDistribution(lowestValue: 1, highestValue: 8)

Finally, call 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.

Available from iOS 9.0 – see Hacking with Swift tutorial 35

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Master iOS 11 now!

My book Practical iOS 11 gives you seven complete coding projects that teach all the major new features in iOS 11 in a smart, practical way.

Click here to visit the Hacking with Swift store >>