开发者

how to get select elements randomly from an array

开发者 https://www.devze.com 2023-02-15 10:29 出处:网络
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 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.


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?


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


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.


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

0

精彩评论

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