#include <iostream>
#include <ctime>
#include <cstdlib>
#include <conio.h>
using namespace std;
int main(){
int question[9];
unsigned seed = time(NULL);
srand(seed);
for(int i=0; i < 10; i++){
question[i]=0;
}
for(int i=0; i < 10; i++){
question[i] = rand()/100%(10)+ 1;
//rand();
for(int x=0; x < 10; x++){
if(i==x) continue;
else{
while(question[i]==question[x]){
question[i] = rand()/100%(10)+ 1;
}
}
}
cout << question[i] << endl;
}
getch();
}
int numbersfound = 1;
//generate 1st number
int numbers[10];
numbers[0] = gen_num ;
while(numbersfound < 10)
{
//generate number here
for(int i = 0; i < numbersfound; i++)
{
if(generated_number == numbers[i])break;
if(i == numbersfound-1)numbersfound++;
}
}
. I mainly just inserted the LinearSearch function and replaced one of your for loops with the for loop Infarction fixed. Just google "c++ unique random numbers" and I got it from the first result. Anyway here it is
.#include <iostream>
#include <ctime>
#include <conio.h>
using namespace std;
int LinearSearch(const int number[], int value) //Determines if the given number already exists
{
int index = 0;
int position = -1;
bool found = false; //Bool for duplicate number
while (index < 15 && !found)
{
if (number[index] == value) //If any integer in the list is equal to the new
{ //random number
found = true; //Sets bool to true because it found a duplicate
position = index; //Sets position to where it found the duplicate
}
index++; //Increments through the list of numbers
}
return position; //Returns -1 if number is unique, else if duplicate is found
}
int main(){
int question[14]; //List of numbers
int temp; //Random number holder
unsigned seed = time(NULL);
srand(seed);
for(int i=0; i < 15; i++){
question[i]=0; //Set all integers in array to 0
}
for(int i = 0; i < 15; i++)
{
do {
temp = rand() % 15 + 1; // Generate random number
}
while (LinearSearch(question, temp) != -1); // Call function to check for duplicates of randomly generated number
//Repeats proccess until return value is equal to -1
question[i] = temp; // If it's unique then save the number
cout << question[i] << endl; //Print to screen
}
getch(); //Wait for user to press any key
}
class UniqueRand
{
private:
int min, max, OptionsLeft;
bool bUsed[];
public:
void Initialize(int min=0, int max=1000)
{
this.min = min;
this.max = max;
bUsed = new bool[max-min];
}
int Random()
{
for(int i=0; i<max-min; i++)
{
if(bUsed[i]==false)
{
OptionsLeft++;
}
}
if(OptionsLeft==0)
{
return -1;
}
int retval = (rand()%(max-min));
while(bUsed[retval]==true)
{
retval = (rand()%(max-min));
}
bUsed[retval]=true;
OptionsLeft=0;
return (retval+min);
}
void Reset()
{
for(int i=0; i<max-min; i++)
{
bUsed[i]=false;
}
}
};
UniqueRand myRandGen; myRandGen.Initialize(20,500); int mygeneratedrang = myRandGen.Random();