-(int) randomIndexByWeights:( NSArray* )weights
{
// add weights
int weightsTotal = 0;
for( int i = 0; i < [weights count]; i++ )
{
weightsTotal+= [[weights objectAtIndex: i] intValue];
}
float randomNum = ((float)rand() / RAND_MAX) * 1;
int rand =(int)(randomNum * weightsTotal);
// step through array to find where that would be
weightsTotal = 0;
for( int x = 0; x < [weights count]; x++ )
{
weightsTotal+= [[weights objectAtIndex: x] intValue];
if( weightsTotal >= rand)
{
return x;
}
}
// if random num is exactly = weightsTotal
return [weights count] - 1;
}
NSArray *weights=@[@75,@20,@5];
NSArray *typeArray=@[@"s",@"m",@"b"];
NSString *type;
for(int i=0;i<100;i++)
{
type = typeArray[ [self randomIndexByWeights:weights] ];
//75 time is string s displayed
//70 time is string m displayed
//5 time is string b displayed
}
Comments
Post a Comment