1

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

4 回答 4

2

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.

于 2012-08-24T12:39:50.137 回答
1

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.

于 2012-08-24T12:34:54.683 回答
1

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;

}
于 2012-08-24T12:37:42.787 回答
0

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.

于 2012-08-24T12:36:17.953 回答