Mahesh Babu
Mahesh Babu

Reputation: 3433

how to get select elements randomly from an array

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.

Upvotes: 0

Views: 824

Answers (4)

Vivart
Vivart

Reputation: 15313

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

Upvotes: 0

visakh7
visakh7

Reputation: 26390

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..

Upvotes: 1

Himadri Choudhury
Himadri Choudhury

Reputation: 10353

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.

Upvotes: 0

Ron Srebro
Ron Srebro

Reputation: 6862

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?

Upvotes: 1

Related Questions