Reputation: 181
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.
Upvotes: 1
Views: 411
Reputation: 727097
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.
Upvotes: 2
Reputation: 16864
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;
}
Upvotes: 1
Reputation: 5973
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.
Upvotes: 0
Reputation: 150765
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.
Upvotes: 1