Question

First of all sorry about the question title, It is hard to get this question out in a few words.

Basically I have an NS array that is being populated by letters in a word. The letters are then being randomly displayed and the user has to find the correct letters to make the word up. Currently I am using code similar to this:

int length = [arrayForCount count];
int randomindex = arc4random() % length;

This does acheive what I want however because it is random each call it produces the same int, which in turn will produce for example two letter e's but not another letter which is in the array.

I have also tried

randIdx = random() % [arrayForRound count];

Could someone please help me to find a way of randomly displaying values from the array, but not missing or doubling up on some letters?

Let me know if more information is needed, thanks for the help in advanced. T

Was it helpful?

Solution

As mentioned in my comments, copy the objects of the original array to a mutable array and shuffle it as:

NSUInteger count = [array count]; //array is the mutable copy of original array
for (NSUInteger i = 0; i < count; ++i) {
    NSInteger elements = count - i;
    NSInteger n = (arc4random() % elements) + i;
    [array exchangeObjectAtIndex:i withObjectAtIndex:n];
}

Now you can access objects in array one bye one and it will unique. You wont miss any objects as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top