Daniel
Daniel

Reputation: 41

Make an array of random unique numbers in a certain range

I'm working on a school project and I need to create an array (size of 30) of random unique numbers between 1 and 70.

I managed to find how to create an array of random unique numbers, but not between 1 and 70.

public int[] ShuffleArray(int[] arr)
{
    Random rand = new Random();
    int[] array = new int[70];
    for (int i = 0; i < 70; i++)
        array[i] = i + 1;
    int[] MyRandomArray = array.OrderBy(x => rand.Next(1, 71)).ToArray();
    for (int k = 0; k < arr.Length; k++)
        arr[k] = MyRandomArray[k];
    return arr;
}

I changed it based on feedback, but it still doesn't work.

Upvotes: 0

Views: 1423

Answers (1)

Pierre-Luc Pineault
Pierre-Luc Pineault

Reputation: 9191

The three steps are:

  1. Generate all the choices
  2. Shuffle them
  3. Take the first 30

Looks like you got 1 and 2 covered So currently you have 70 numbers, in random order. What's left is the step 3, taking the first 30.

You can achieve it with Take. It returns an IEnumerable, so you can use ToArray to transform it into an array afterwards.

return MyRandomArray.Take(30).ToArray();

So with the code you had, it would look like this:

public int[] ShuffleArray(int[] arr)
{
    Random rand = new Random();
    int i;
    int[] array = new int[70];

    for (i = 0; i < 70; i++)
        array[i] = i + 1;

    int[] MyRandomArray = array.OrderBy(x => rand.Next()).ToArray();

    return MyRandomArray.Take(30).ToArray();
}

While we're here, let's fix a couple things too.

You can join the declaration and use of i in your for loop:

for (int i = 0; i < 70; i++)

In C#, the convention is to have variables written in camelCase, so MyRandomArray should be named myRandomArray.

You could abbreviate your for loop with the following:

int[] array = Enumerable.Range(1,70).ToArray();

Finally, if you want to really optimize things, you could join that declaration with the OrderBy and Take in a single line to drop the temporary variables:

public int[] ShuffleArray(int[] arr)
{
    Random rand = new Random();
    return Enumerable.Range(1, 70).OrderBy(x => rand.Next()).Take(30).ToArray();
}

Upvotes: 3

Related Questions