How to print out the 5 unrepeated random numbers among 0 to 10? Thank you very much!!~
How to print out the 5 unrepeated random numbers among 0 to 10? Thank you very much!!~
Last edited by DramaKing; 10-26-2001 at 01:19 AM.
Random numbers are in the FAQ. To make sure numbers are not duplicated you could use a binary tree or stl set.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
You could also write your own function to check duplicates if you don't have or don't know how to use the Standard Template Library.
Are my codes correct?! However, it shows error for the "randomize();". What can I do?? thx!!Code:#include <iostream.h> #include <stdlib.h> int main(void){ randomize(); for (int i=0; i<5; ++i) cout << rand() % 11 <<" "; return 0; }
Randomize() is a non-standard function, you'll need to look at the second example in the FAQ.
The code you've written doesn't guarantee that each number will be unique. Each time you generate a number you could store it and check your previously stored numbers to see whether it's occured before.
zen
I can use randomize now, but my program can't check out the repeated number. Pls help!! Thx!!~Code:#include <iostream.h> #include <stdlib.h> #include <time.h> inline void randomize(){ srand((unsigned)time(NULL)); } int main(void){ int num1 = 0,num2 = 1; randomize(); for (int i=0; i<5; ++i){ num1 = rand() % 10; while (num1 != num2){ cout << num1 <<" "; num2 = num1; } } cout <<endl; return 0; }
How can I make a function to check the duplicates? What I wrote is:
Code:#include <iostream.h> #include <stdlib.h> #include <time.h> inline void randomize(){ srand((unsigned)time(NULL)); } int main(void){ int num1 = 0,num2 = 1; randomize(); for (int i=0; i<5; ++i){ num1 = rand() % 10; while (num1 != num2){ cout << num1 <<" "; num2 = num1; } } cout <<endl; return 0; }
However, it doesn't work. Can anyone tell me how to do it? Thanks!!~
Use a binary tree..... go here for a lesson.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
int randomNumbers[5] = -1; //declare an array of ints and fill with number you know is not valid.
int index = 0; //to keep track of where you are in randomNumbers;
char found = 'n'; //a flag to indicate if current number found in randomNumbers
int i;
each time you generate a random number search the array to see if it is already there:
if randonNumber[0] is -1 then no valid numbers in randomNumbers yet and add current value to this spot.
else if randomNumber[0] not equal -1;
use a loop to look at all values in randomNumbers;
if current random number is same as any in randomNumbers then change found to 'y';
at end of loop check found. if found is 'n' then increment index and assign current random number to that spot in randomNumbers;
keep generating random numbers until index is 4, meaning there are 5 unique random numbers in randomNumbers.