發表文章

目前顯示的是有「random」標籤的文章

使用權重控制隨機選取

圖片
水果  |  Apple  | Orange | Banana | Mango ------------------------------------------ 權重  |   70    |   10   |   10   |   10 從這個表中,我們分派了各個權重,我們希望Apple最常被抽中,所以將權重設定較高的值。 因此我們從這個表來實現作法。 fruits = [[NSArray alloc] initWithObjects:@"apple",@"orange",@"banana",@"mango", nil]; //定義水果 weights = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:70],[NSNumber numberWithInt:10],[NSNumber numberWithInt:10],[NSNumber numberWithInt:10], nil]; //定義權重  int currentfruit=0;     NSMutableArray *weighedfruits = [[NSMutableArray alloc] init];         while (currentfruit<[fruits count]){ //step through each fruit[] element        for (int i = 0; i < [[weights objectAtIndex:currentfruit] intValue]; i++) {                  [weighedfruits addObject: [fruits objectAtIndex:currentfruit]]; ...