Click here to Skip to main content
15,886,083 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,
What to do if I want to generate random numbers to more variables but some of them will have generated value except value which is saved in some other variables? It may be hard to understand what I want :D so I will show you some code (which is wrong but it can explain better what I mean).

int variable_1 = rand.Next(1,14)
int variable_2 = rand.Next(1,14.Except(variable_1)) //So what I want is to save value to variable_2 which minimum is 1 and maximum is 14 but the value of variable_2 can't be equal to value in variable_1


The sollution which will work for even more variables would be best :). Can you please help me? I tried to think about some algorithms myself and tried google and MSDN and nothing helped me. Thanks for any kind of help!
Posted
Comments
Peter_in_2780 19-Apr-12 18:03pm    
Is your problem the same as shuffling a deck of cards and dealing one at a time? If so, do just that. Make an array of the integers you can choose from, then use a random number generator to swap pairs many times. Then just take the numbers in order.

1 solution

I don't know if there is a direct way to do that at once, but you could do the generation of the second random number inside a loop that breaks when it is different of the previous one.

I mean something like (getting your code as example):

C++
int variable_1;
int variable_2;
variable_1 = rand.Next(1,14)
do
{
   variable_2 = rand.Next(1,14)
} while (variable_2 == variable_1) // If the first try gets the same value it repeats until it generate one that is not equal


But this solution can only be taken into consideration if the number of variables to check before accepting the new one is not big, so the conditions don't get too much. Using a recursive function that checks the previous ones and recalls itself if not matching would be another possibility.

Problem with that is: the bigger the number of variables you want to create, the bigger time it gets to find a correct value for the next.

how many variables are you speaking about? And the range for the random numbers? Must all variables have "unique" value?
If there are many variables and all of them must have a unique value you could do another thing, like creating an array to hold the values from 1 to range_limit, sorting them randomally and getting them from there.
 
Share this answer
 
v3
Comments
LosEagle 19-Apr-12 18:20pm    
Well it seems I found sollution. Thank you :)
Nelek 19-Apr-12 19:19pm    
You are welcome
[no name] 19-Apr-12 23:18pm    
5
Nelek 20-Apr-12 16:35pm    
Thank you Wes

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900