13,045,285 members (57,662 online)
Rate this:
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 19-Apr-12 10:31am
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.

Rate this:

## Solution 1

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):

```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.
v3
LosEagle 19-Apr-12 18:20pm

Well it seems I found sollution. Thank you :)
Nelek 19-Apr-12 19:19pm

You are welcome

5
Nelek 20-Apr-12 16:35pm

Thank you Wes

Top Experts
Last 24hrsThis month
 OriginalGriff 263 Graeme_Grant 135 ppolymorphe 134 Atlapure Ambrish 80 kp564 70
 OriginalGriff 4,683 RickZeeland 1,854 ppolymorphe 1,708 F-ES Sitecore 1,553 Dave Kreskowiak 1,349