iOS - How To Choose Objects in Array More-So Then

2019-08-31 11:44发布

I have an array that contains a variety of strings. I want to choose a the objects at indexes 3,7 & 9 more-so then all the other objects..how can I achieve this. (Let's say every time I grab an object within the array, I want there to be a 80% chance that object at index 3,7 or 9 is selected)

Here's my array:

 NSMutableArray* animalImagesArray = [[NSMutableArray alloc] initWithObjects:@"bull.png",@"bunny.png",@"chicken.png",@"cow.png",@"crocodile.png",@"dog.png",@"donkey.png",@"duck.png",@"elephant.png",@"giraffe.png",@"goat.png",@"hippo.png",@"horse.png",@"lion.png",@"monkey.png",@"parrot.png",@"pig.png",@"rooster.png",@"sheep.png",@"snake.png",@"tiger.png",@"warthog.png",@"zebra.png", nil];

Any help would be greatly appreciated. Thanks in advance!

2条回答
在下西门庆
2楼-- · 2019-08-31 12:28

How about a preliminary random variable from 1–5. If a number in [1,4] is chosen then choose an index at random from the set {3,7,9}. Otherwise choose an object at random from the rest of the array.

(Also, since every object in the array has the suffix .png, you might as well remove that and just concatenate it later using stringWithFormat)

查看更多
来,给爷笑一个
3楼-- · 2019-08-31 12:36

I like Lyndsey Scott's answer so thought I'd implement it so that you can still get the original index of the word.

If you have an array of 10 items and you want 3 of them (combined equally) to have an 80% chance of being chosen then that means the other 7 have a chance of 20%.

So...

I worked it out like this...

We know 7 is 20%. So 100% is 35. 80% of 35 is 28.

Ideally you should be doing this calculation in the app not on paper :) Maybe store the individual weights of each item in an array or something. That way you can create the weighted array dynamically for any number of items and different weights etc...

You'll need 28 of the other 3 (in total) so 9 of two of them and 10 of the other. (Let's make it 9 each for ease).

So you can do like this...

NSMutableArray *weightedArray = [NSMutableArray array];

for (int i=0 ; i<originalArray.count ; ++i) {
    if (i == 3 || i == 7 || i == 9) {
        for (int count=0 ; count<9 ; ++count) {
            [weightedArray addObject:array[i]];
        }
    } else {
        [weightedArray addObject:array[i]];
    }
}

// Now you can select from the weighted array.

id randomObject = weightedArray[arc4random_uniform(weightedArray.count)];

//Index of object

NSUInteger origIndex = [originalArray indexOfObject:randomObject];

It might be an idea to store the individual weights or something and then calculate the number you need to put at run time.

As Sandy Chapman pointed out in the comments you could also created a weighted array of indices for the original array so you would have...

[0, 1, 2, 3, 3, 3, ..., 4, 5, 6, 7, 7, 7..., 8, 9, 9, 9, 9, ..., 10]

That way you can get the index without having to get the original item.

Either way will work.

查看更多
登录 后发表回答