在Objective C中生成随机加权数

时间:2014-07-02 10:54:52

标签: ios objective-c random

我们有一个具有以下结构的词典:

_availableCharacterClasses = [[NSMutableDictionary alloc] init];
[_availableCharacterClasses setObject:[NSNumber numberWithFloat:[DefaultNova characterSpawnProbability]] forKey:NSStringFromClass([DefaultNova class])];

where probability has a value between 0 (low) and 100 (height)

现在我想从_availableCharacterClasses-Dictionary中选择一个随机密钥(加权) 如何使用目标c存档?

3 个答案:

答案 0 :(得分:1)

啊我觉得现在我的问题是正确的。 我假设概率总和达到100?

int random = arc4random%100;

NSArray *probabilities = [_availableCharacterClasses allObjects];
NSArray *keys = [_availableCharacterClasses allKeys];
CGFloat currentValue = 0;
int index=0;
for(NSNumber *p in probabilities){
    currentValue+=[p floatValue];
    if(random<currentValue){
        //found now get the key
        return keys[index];
    }
    index++;
}

答案 1 :(得分:0)

@Robert我稍微修改了你的解决方案,并提出了以下结果

- (NSUInteger)randomIndexByProbability:(NSArray *)probabilities
{
  CGFloat randomNumber= arc4random_uniform(100) + (float)arc4random_uniform(101)/100;
  NSUInteger weightedIndex = 0;
  CGFloat totalProbability = 0.0;

  for(NSUInteger i=0; i<probabilities.count; i++)
  {
    totalProbability += [probabilities[i] floatValue];

    if(totalProbability >= randomNumber)
    {
      break;
    }
    weightedIndex++;
  }
  return weightedIndex;
}

答案 2 :(得分:0)

如果您想为给定值选择随机密钥,您可以执行以下操作:

float value = 3;    
NSArray * keys = [_availableCharacterClasses.allKeys filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%@[self].floatValue == %f", _availableCharacterClasses, value]];
NSString *anykey = keys[arc4random_uniform(keys.count)];