-1

Im a beginner at programming and im currently learning C# in school. I've got a task to make an array containing every number between 1-20 in order of size. Then randomize the order in which the numbers appear in the array. I've tried different methods, but i can't seem to get it to work. This is what im working with at the moment:

        int random = 0;
        Random rNG = new Random();
        int[] twenty = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
        int[] check = new int[20];
        for (int i = 0; i < 20; i++)
        {
            random = rNG.Next(1, 21);
            foreach (int check2 in check)
            {
                if (random != check2)
                {
                    check[i] = random;
                    twenty[i] = random;
                    break;
                }
            }
        }

        foreach (int write in twenty)
        {
            Console.Write(write + ", ");
        }

Coding in Visual Studio 2015 in a console project.

Thanks in advance for the help/suggestions!

  • 2
    What you're talking about is called shuffling. The question has been asked numerous times on SO. – itsme86 Nov 16 '16 at 16:05

2 Answers2

0

I would say, don't bother trying to change the order, randomise the way in which you access the index instead.

Having your numbers in the array in order is fine. If you write some code to access i at random then you'll have the same effect.

Ross Miller
  • 656
  • 3
  • 9
  • Since OP is supposed to change the order, I feel like a professor wouldn't give a very good grade with this approach. It would produce the same output, but it's kind of a work around to avoid solving the given problem. – Sam W Nov 16 '16 at 16:13
  • True. Depends on the specifics of the task. Display a random order or physically change it in the array? – Ross Miller Nov 16 '16 at 16:15
0

Look into using your rNG in conjunction with twenty.OrderBy(/*hint something goes here*/).ToArray(). I don't want to give you the exact solution since it's your homework, but you should be able to figure it out from there.

Sam W
  • 599
  • 2
  • 16