-4

While entering random numbers in an array, my goal is to have a random number in element [x] different from the previous one [x-1] that's the only constraint. I believe to be achieving this but my problem is that when I run the following code my output does not display all elements.

        int[] array = new int[10];
        Random number = new Random();

        for(int i = 0; i < array.Length; i++)
        {
            int randomNumber = number.Next(3) + 1;
            if (i == 0)
            {
                array[0] = randomNumber;    
            }
            else
            {
                array[i] = randomNumber;

                while (array[i] == array[i - 1])
                {
                    array[i] = randomNumber;
                }
            }

            Console.Write(array[i] + " ");
        }
        Console.ReadLine();
phoenix
  • 1
  • 2
  • After you read [ask] and take the [Tour], is the constraint that each number be different than just the *previous* value? Then ask an actual question. – Ňɏssa Pøngjǣrdenlarp Apr 03 '18 at 05:00
  • If you want a random number from 1 to 3, why not generate a random number from 1 to 3 instead of generating a random number from 0 to 2 and then adding 1 to it? – jmcilhinney Apr 03 '18 at 05:10

1 Answers1

0

The issue is that, for each element, you only ever generate one random number. If that number happens to be the same as the previous one, you don't generate a new one but just keep using the same one. This:

while (array[i] == array[i - 1])
{
    array[i] = randomNumber;
}

should be like this:

while (array[i] == array[i - 1])
{
    randomNumber = number.Next(3) + 1;
    array[i] = randomNumber;
}
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
  • Thanks! I'm still learning, can't believe I missed that. I appreciate your help. – phoenix Apr 03 '18 at 05:15
  • This is a perfect example of why you need to debug your code rather than just read it. When you simply read code, you see what you expect to see much of the time. If you actually debug the code then you see what actually happens. If you don't know how to debug, learn. In future, if you haven't set a breakpoint and stepped through the code, it's too soon to post a question. If you'd debugged here then you'd have seen straight away that the number never changed at that point. – jmcilhinney Apr 03 '18 at 05:17
  • Yes, you're absolutely right. I will keep this in mind, thanks again. – phoenix Apr 03 '18 at 05:24