开发者

How can I randomly draw from an NSMutableArray and not use the same number twice?

For a game I am making, I am passing an array of objects of a set number that I am going to have the user identify. I would like to mak开发者_运维技巧e the presentation of these objects random. But I also need to make it so that the same object isn't presented twice.

So this is the solution I have thought of tentatively: I pass in an array of objects to my game controller, of size 10. In the game controller I create a random number between 0-9 and then pull from the array with that number as the index...I don't know if that will work though because I need to make sure that the same random number isn't used in a game session.

Any thoughts on how I might accomplish this type of random game logic?

Thanks


You should look for a shuffling algorithm and shuffle your array contents.

This way you can just pop numbers off the array without worrying if they've been used before - when you get to the last number, reshuffle the array and repeat.

Here's an example: http://www.cocoanetics.com/2009/04/shuffling-an-nsarray/


To avoid having the same index come up more than once I'd remove the object from the array each time. If you base the random number of the size of the array you should be fine. Make a copy of the array if you want to be able to re-create it to start over again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜