Reputation: 2901
What is the easiest way to generate 5 random numbers from 1 to 200 such that
randnum[0] < randnum[1] < randnum[2] < randnum[3] < randnum[4]
My code looks like this but it always overflows at randnum[4]
limit_upper = 10; // generate random number up to 10 for randnum[0]
limit_lower = 0;
srand((time(0));
for (x = 0; x < 5; x++) {
randnum[x] = 1 + limit_lower + (unsigned int) rand() % limit_upper;
limit_lower = limit_lower + randnum[x];
limit_upper = (limit_upper * 2) + (unsigned int) rand() % limit_upper;
}
The random numbers to be generated should not repeat.
Any help?
Thank you.
Upvotes: 0
Views: 572
Reputation: 2901
As the accepted answer sugggests, here is the solution:
#include <stdio.h>
#include <stdlib.h>
void quicksort(int arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
if (left < j)
quicksort(arr, left, j);
if (i < right)
quicksort(arr, i, right);
}
int main() {
int i;
int x;
int random[5];
srand(time(0));
for (i = 0; i < 5; i++) {
random[i] = 0;
}
for (i = 0; i < 5; i++) {
random[i] = rand() % 201;
for (x = 1; x < i; x++) {
if (random[x] == random[i]) {
i--;
continue;
}
}
}
quicksort(random, 0, 4);
for (i = 0; i < 5; i++) {
printf("random[%0d]: %0d \n", i, random[i]);
}
return 0;
}
Maybe someone will find it useful.
Upvotes: 1
Reputation: 46960
This is a classic problem covered from several angles by Jon Bentley in Programming Perls. I highly recommend this book.
Upvotes: 0
Reputation: 2323
Generate random numbers from 1 to 200, sort them as you go, discard duplicates, until you have 5.
Upvotes: 4
Reputation: 2544
As azhrei pointed out, you're over complicating things. Generate five random numbers between 0 and 200 while throwing out duplicates and sort when finished. This will work well unless you're planning on expanding your code significantly beyond five numbers or have some crazy performance requirements. You'll thank yourself later for the straight forward readable bug-free code. Also, you will remove any artificial limitations to your randomness.
Upvotes: 1
Reputation: 1
Looking at your last line, limit_upper could become anything up to 267 by the 3rd iteration.
The max increase being limit_upper*2 + limit_upper-1 (about 3*limit_upper).
That you get the same problem every time are you seeding your random generator?
Upvotes: 0