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.

Piyo
  • 181
  • 1
  • 2
  • 9

4 Answers4

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
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.

Abizern
  • 146,289
  • 39
  • 203
  • 257
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;

}
Nimit Parekh
  • 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
  • Thanks for informing me.+1 for it – Nimit Parekh Aug 24 '12 at 12:50
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.

Community
  • 1
  • 1
ddoor
  • 5,819
  • 9
  • 34
  • 41