0

I have two sets of arrays in my app that consist of 3 images each. Every time my app is used, I want one of the two arrays to be set as array _finalSelection (e.g. each time one or the other should be set to _finalSelection randomly). How can I achieve this?

ViewController.m

-(void)viewDidLoad {

     _pageImages = @[@"britt001.png", @"britt02.png", @"britt030.png"];
     _pageImages2 = @[@"britt001.png", @"britt02.png", @"britt030.png"];

     _finalSelection = [one of the two above arrays]; 

}
Brittany
  • 1,359
  • 4
  • 24
  • 63

1 Answers1

2

Use arc4random() division by 2.

_finalSelection = arc4random() % 2 ? _pageImages : _pageImages2;
M.S.
  • 152
  • 8
  • 4
    `_finalSelection = arc4random_uniform(2) ? _pageImages1 : _pageImages2` – ɯɐɹʞ Oct 08 '18 at 22:40
  • 2
    It's better to use `arc4random_uniform(2)` instead as ` % 2` will introduce modulo bias on the random distribution. More details here: https://stackoverflow.com/a/29956021/5329717 – Kamil.S Oct 09 '18 at 09:50
  • @Kamil.S no modulo bias in case of `% 2`. – M.S. Oct 09 '18 at 10:36
  • @M.S. You're right `% 2` is indeed a special case and there is no bias (I did benchmark that). I'd still opt for `arc4random_uniform` giving consistent results for arbitrary range. In terms of code maintainability it might make a difference. Anyway thanks for clarifying. – Kamil.S Oct 09 '18 at 10:50