This is just a piece of the code. How can I make this not use the same number repeated times? The container has 7 slots and the numbers have to be in the interval of 1 - 35.
You could code around the problem directly, instead of relying on some "black box" container to do it.
I suggest something like:
1 2 3 4 5 6 7 8 9 10 11 12
int x = 0;
while(x <= 6)
{
tal[x] = rand()%35 + 1;
bool unique = true;
for( int j=0; j<x; ++j )// check if that value exists in the array already
if( tal[j] == tal[x] )
unique = false;// skip incrementing x below and try again
if( unique )
x++;
}
@fun2code You see, that's impossible, since it will be if(tal[0] == tal[0])
because both int x; and int j; is 0. I tried it and my program skips creating any lines at all.
As the number of values you're generating approaches the amount of numbers in your range (98 values, min 1, max 100 for example) it should become more efficient to fill the vector with all values in the range, shuffle it, and resize.
I might be close to an solution. But the thing is, after tal[search]; has compared itself to tal[x] and both increases by one, tal[1] can still be what tal[0] was. Can I somehow add the numbers already taken into another array and then give the condition that the new number if identical can be everything BUT the ones in the array containing already used numbers?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int x = 0;
int search = 0;
while(x <= 6) //Give int tal[7] 7 random numers
{
tal[x] = rand()%35 + 1;
while(search < x) //Search if there's identical numbers
{
while(tal[x] == tal[search]) //Alternatively replace tal if identical so the same number doesn't appear multiple times
{
tal[x] = rand()%35 + 1;
}
search++;
}
search = 0;
x++;
}
That might work, but I have to explain what that does for the teacher, and I understand about 10% of that... I've just been programming for 5 months and the only thing I know is the basics, if-else and loops.
If you find a duplicate, don't increase x and just let the loop iterate again:
1 2 3 4 5 6 7 8 9 10 11
while ( x <= 6 )
{
tal[x] = rand()%35 + 1;
int search = 0 ;
while ( search < x && tal[x] != tal[search] )
++search ;
if ( search == x ) // no duplicate found
++x ;
}
Can I somehow add the numbers already taken into another array and then give the condition that the new number if identical can be everything BUT the ones in the array containing already used numbers?
Yes. Use an array of bools.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//...
bool alreadyUsed[36] = { false }; // everything is initialized to false
// ...
do
{
tal[x] = rand() % 35 + 1;
} while (alreadyUsed[tal[x]]);
alreadyUsed[tal[x]] = true;
//...