0

i have an array with 12 objects {0,1,2,3,4,5,6,7,8,9,10,11}

from this array i have to pick 6 values randomly,but they are unique not repeated.

i am using this

for (int i =0; i<6; i++) 
{
    NSLog(@"%d",rand()%12);

}

it gets as 7 1 5 2 10 8

for second time it gets as 0 2 11 1 0 5,Here 0 is repeated.But i always need as my first output means values are not repeated.

how can i done,

can any one please help me.

Thank u in advance.

Jitendra
  • 5,055
  • 2
  • 22
  • 42
Mahesh Babu
  • 3,395
  • 9
  • 48
  • 97
  • This question can help you : http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray Then you pick up your 6 values from the array ;) – j_freyre Mar 07 '11 at 10:30

4 Answers4

1

How about using a mutable copy of the array and each time removing the element from the copy of the array and reducing the array length you use by one?

Ron Srebro
  • 6,663
  • 3
  • 27
  • 40
1

Try this

  1. Get the random number using rand().
  2. Check if the previous no is the same if yes get random number again. Else add the generated no to the result array.
  3. Repeat till u get the required number of elements in ur result array

Hope this helps..

visakh7
  • 26,380
  • 8
  • 55
  • 69
  • i think it is a long process,if i have 40 images need to select 20 images,then i need to retrieve 20 times and check it 20 times if same then the process is extends – Mahesh Babu Mar 07 '11 at 10:44
0

You can do this in 2 steps:

1) Make a list of unique elements from the original list

2) Use the rand procedure that you mentioned to pick elements from the new list.

To solve 1), I think there are 2 ways

1a) Sort the elements. With the sorted array it should be easy to filter out the duplicate elements.

1b) Create a object of the NSSet class to create a set of elements. Go through the array and add the elements to the NSSet object. NSSet will have unique elements from the original array.

Himadri Choudhury
  • 10,217
  • 6
  • 39
  • 47
0

use Fisher-Yates shuffle algorithm to shuffle your array. than take first 6 elements.

Vivart
  • 14,900
  • 6
  • 36
  • 74