0

Given an NSArray of objects eg [NSArray arrayWithObjects:A, B, C, D, E, nil], I can choose a random set of N objects from the array by using a for loop and an arc4random function e.g.

NSArray *objArray = [NSArray arrayWithObjects:A, B, C, D, E, nil];
NSMutableArray *newArray = [NSMutableArray alloc] init];
for(int i=0;i<N;i++){

   id randIndex = arc4random() % N;
   [newArray addObject:[objArray objectAtIndex:randIndex];
}

This works fine, but what I'd like is to be able to specify a weighting for each of the elements in objArray that defines how likely that element is to be selected by the randIndex. It seems this selection could be dependent on previous selections (or not).

NSArray *weights = [NSArray arrayWithObjects:@1, @0.5, @1, @1, @1]; would mean:

A - 1
B - 0.5 // 0.5 times as likely to appear
C - 0.3 // 0.3 times as likely to appear
D - 0.1 // 0.1x times as likely to appear
E - 0   // Will never appear

etc so the weights above would lead to having more object A's and no object E's. Thanks.

Yuyutsu
  • 2,509
  • 22
  • 38
  • 1
    possible duplicate of [iOS - How To Choose Objects in Array More-So Then Others](http://stackoverflow.com/questions/27383350/ios-how-to-choose-objects-in-array-more-so-then-others) – Lyndsey Scott Jan 01 '15 at 13:47
  • For the general case take a look here http://stackoverflow.com/questions/13635448/generate-random-numbers-within-a-range-with-different-probabilities/13637027#13637027. – user515430 Jan 01 '15 at 15:13
  • If you are giving probability of occurrence as weightage, how is probability of A = 1. This indicates A will be selected always. The sum of probabilities of all elements should be 1. – rakeshbs Jan 01 '15 at 15:22

0 Answers0