Random items? Forget arc4radom(), use GamePlayKit in iOS9!
I wanted to use some kind of random data in my recent project, but I had a feeling by using the plain arc4random() function didn’t give me properly shuffled data. I know there is a way to seed the function, but I was looking for more interesting, and easily deployable solution.
Along wit other cool frameworks, Apple announced the GamePlayKit in iOS9 (don’t mismatch with GameKit framework…), and I had a feeling that they implemented something that could be interesting for me. I wasn’t disappointed when I realise that there are few classes, helping the developers in randomisation.
For randomisation purpose Apple added the GKRandomDistribution, which is the superclass of the other two distributions, namely the GKShuffledDistribution and the GKGaussianDistribution.
Based on the documentation the GKGaussianDistribution probably less useful, since the numbers on the middle of distribution range are most likely generated, than the two ends of the range.
GKShuffledDistribution however has a nice feature: it is trying to equally share the results in the range. Actually this was the most interesting for me, until my curiosity led me to open the header file of the class (in Xcode you can open any class header by clicking on the classname while holding the Command button). I found this comment in the header file:
* Do not use with distributions ranging more than 256 between lowest and highest as the shuffling seqeunce is stored internally in memory.
I think that should be mentioned in the documentation, under the link above as well…
Anyway, I put together a small app for iOS devices, and you can download or fork it from my github account: here. The main target is to see the distributions characteristics in the range of 1 to 10.
Challenges:
- What do you need to change to include 0 (zero) as the minimum value?
- Add a possibility to change the maximum value of the distribution range by the user.
- Based on the notes from the header file, how would you cope when the value is bigger than 256 and the user wants to use the GKShuffledDistribution?
- The statistics view isn’t so pretty, not to mention that it holds only 10 data. How could you extend it to dynamically change, based on the user provided maximum value?
Happy coding!