|
-
Oct 20th, 2001, 03:42 PM
#1
Thread Starter
Hyperactive Member
Non repeating random numbers
I used to do a simple program which randomly picks 10 questions from 20 questions for the user to answer. These 10 questions cannot be repeated.
I programmed in such a way that I kept track of the questions selected and if the same question pops up again, it is discarded and I go on to pick the next random question and repeating the checking again.
There is nothing wrong with my code. But only the first question is random, rand(),(or rather my code,) kept giving me the consecutive numbers.
Eg.
Q17 <-first number is always random.
Q18 <-the rest are not
Q19
Q20
Q1
Q2
Q3
Q4
Q5
Q6
One of my classmates did it this way, he set a random number(ranged between 1 to 1000) to each question , then he sorted them. And he only picked the first 10 of the sorted numbers. And he succeeded.
Can I know how you all do non-repeating random numbers. Anyway that mini project was years ago and was done with.
-
Oct 20th, 2001, 09:41 PM
#2
Addicted Member
Did you put
srand((unsigned)time(NULL));
int your code? If no it may be your problems. Add it before you become to use random. You will need to include time.h.
Also, I don't know for C++, but the VB equivalent reveals to be buggy if you do this often, so you would better to put it once in you main procedure.
-
Oct 21st, 2001, 02:27 AM
#3
Thread Starter
Hyperactive Member
-
Oct 21st, 2001, 10:15 AM
#4
Waht you want is randomly selected numbers in a range, like
1-20, like simulating dealing cards from a deck.
This is a disussion of this from a VB point of view.
I'm not a in place where I can write this in C.
http://www.vbforums.com./showthread....ghlight=random
-
Oct 21st, 2001, 08:44 PM
#5
Thread Starter
Hyperactive Member
After I read the thread you post, I understand your code but not really sure it could work or not. So I convert it to C and it work! Three cheers for Jim!
Code:
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char* argv[])
{
int i,j,arr[20],tmp;
j=0;
while(j<20)
{
arr[j]=j;
++j;
}
j=19;
srand((unsigned)time( NULL ));
while (j >= 0)
{
i = (rand()%19);
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
--j;
}
j=0;
while(j<20)
{
cout<<arr[j]<<endl;
++j;
}
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|