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.
Aucun commentaire:
Enregistrer un commentaire