Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random Numbers

Status
Not open for further replies.

sheronne

Programmer
Jun 1, 2001
71
US
I want to return a random numbers between lnLow and lnHigh (ex. 1 and 10) but I need to check for duplicate values, What is the quickest most efficient way?

In essence I want to return 1 through 10 in random order, not repeating a value.
 
filling vector x with rand unical values:
include<vector>
using namespace std;
...........
//filling below:
vector<int> x;
vector<int>::iterator y;
for(int i=0;i<10;i++)
{
while(1)
{
int c=rand()%10+1;
y=find(x.begin(),x.end(),c);
if(y==x.end())
{
x.push_back(c);
break;
}
}
} John Fill
1c.bmp


ivfmd@mail.md
 
I would create an array

int values[10]

for(int i=1;i<=10;i++)
{
values = i;
}

then use the random function to swap the values in the array n amount of times.

int temp,swap1,swap2;
for(int x = 0; x < times_to_swap; x++)
{
swap1 = rand%10;
swap2 = rand%10;

temp = values[swap1];
values[swap1] = values[swap2];
values[swap2] = temp;
}

On a side note you may want to seed the random fucntion with time

Matt
 
side note... my loop above is wrong... the internal of the loop with the values array intitialization should be

value[i-1]=i;

sorry... not enough coffee in me at the time of posting.

:)

matt
 
How about
srand (time(NULL))

numonetoten = 1 + rand()% (10 -1+1);

what you have above is
lowerbound + rand()% (upperbound - lowerbound +1)

i think you have to have #include <ctype.h>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top