I have numbers in integer that is 0, 17, 23, 44, 57, 60, 66, 83, 89, 91, 100, but i want to random 6 number from that number, how to do that? I can show only for one random number from 0-100 but i dont know how to show 6 number from selected number. Please teach.
4 Answers
If you would like to pick six numbers without repetitions from the array, shuffle the array using Knuth-Fisher–Yates shuffle, and take the first six numbers:
int data[] = {0, 17, 23, 44, 57, 60, 66, 83, 89, 91, 100};
// Knuth-Fisher-Yates
for (int i = 10 ; i > 0 ; i--) {
int n = rand() % (i+1);
int tmp = data[i];
data[i] = data[n];
data[n] = tmp;
}
The first six elements of the data
array contain a random selection from the original 11-element array.

- 714,442
- 84
- 1,110
- 1,523
-
+1 : indeed he needs a shuffle behavior not a random one in this particular case ! – Seb T. Aug 24 '12 at 12:50
Put the numbers in an array. Use a random number generator to get a random number between 0 and 1 less than the length of the array, and then get the number at that index.
That's just one way of doing it.

- 146,289
- 39
- 203
- 257
For fetching the random number into array for that following code may be useful to you
[array objectAtIndex: (random() % [array count])]
Here is the example
NSUInteger firstObject = 0;
for (int i = 0; i<[myNSMutableArray count];i++) {
NSUInteger randomIndex = random() % [myNSMutableArray count];
[myNSMutableArray exchangeObjectAtIndex:firstObject withObjectAtIndex:randomIndex];
firstObject +=1;
}

- 16,776
- 8
- 50
- 72
-
Your implementation contains a very common [implementation error of picking a random element from the entire range](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Implementation_errors). The selection is biased, as explained in the wiki article. – Sergey Kalinichenko Aug 24 '12 at 12:48
-
See this post: Generating random numbers in Objective-C
There are lots of ways to do this. This particular method has a very good response. To get 6 random numbers simply run the function 6 times.