0

I'm trying to randomize four numbers without them being the same, or else it breaks my code. What can I do to so that they are all the same? This is my code:

Random r = new Random();

_unknown1 = r.Next(1, 8);
_unknown2 = r.Next(1, 8);
_unknown3 = r.Next(1, 8);
_unknown4 = r.Next(1, 8);
BDL
  • 21,052
  • 22
  • 49
  • 55

2 Answers2

3

If I understand your question correctly. You dont want to repeat your random numbers. This might do the trick for you

List<int> randomNumbers = new List<int>(); 
for (int i=0; i<4; i++) 
{    
    int number;
    do 
    {
        number = random.Next(1, 8);
    }
    while (randomNumbers.Contains(number));
    randomNumbers.Add(number);
}
Mohit S
  • 13,723
  • 6
  • 34
  • 69
1

Pull your random numbers from a randomized list:

Random r = new Random();
var set = Enumerable.Range(1, 8)
                    .OrderBy(x => r.Next())
                    .Take(4)
                    .ToList();

_unknown1 = set[0];
_unknown2 = set[1];
_unknown3 = set[2];
_unknown4 = set[3];
Abion47
  • 22,211
  • 4
  • 65
  • 88
  • Wow! that helped a lot! Thanks! – Default Name Jan 16 '17 at 04:28
  • 1
    This is very inefficient for any non-trivial `MaxValue`. If I want 2 random numbers between 1 and 10,000,000 this will generate 10,000,000 values, only to take 2. – Rob Jan 16 '17 at 04:46
  • @Rob If you wanted to generate 2 random values from 10,000,000 possibilities, you can use the regular method as the chance of generating the same 2 numbers would be minuscule. – Abion47 Jan 16 '17 at 04:49
  • 1
    @Abion47 A one in a million chance occurrence happens multiple times a day for any non-trivial application. If your logic says they must be *unique*, you'd better make them unique, rather than say 'well, they'll be unique most of the time'. – Rob Jan 16 '17 at 04:50
  • @Rob You are nitpicking. OP's application is picking 4 unique random numbers from a possible list of 8, not 2 in a list of 10 million. This method isn't the most efficient, but it's the most concise, and the loss of performance due to the difference in efficiency is negligible. If OP was dealing with your kind of case, I would've answered him accordingly, but since he's dealing with a range that is so small with such a high chance of collision, this method will suffice just fine. – Abion47 Jan 16 '17 at 04:56