1

I'm looking to create a list of 'random' numbers from 1 to 15 but without any repetition. I have created an array and looking to store each number in it but can't figure out how to do this. I've gotten as far as creating the random list and storing them in the array but can't quite get to ensure there are no repetitions. Any help would be appreciated. My code is as follows:

    int[] myList = new int[15];
    Random random = new Random();

    for (int i = 0; myList.Length; i++)
    {
     myList[i] = random.Next(1, 15);
    }
Gomer
  • 27
  • 3
  • possible duplicate of [Random shuffling of an array](http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array) – user140547 Aug 15 '15 at 09:20

3 Answers3

1

Because the size of your list is equal to the possible values, you can just create the list in normal order:

int[] myList = new int[15];
for (int i = 0; i < myList.Length; i++)
{
    myList[i] = i + 1;
}

and then shuffle it, for example by assigning a random value to each entry and sort by that value:

Random random = new Random();
myList = myList.OrderBy(a => random.Next()).ToArray();
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
0

You can do it using Fisher–Yates shuffle.

Sample Implementation:

int n = 15;
int[] myList = new int[n];
Random random = new Random();

for (int i = 0; i < n; i++)
{
    myList[i] = i + 1;
}
for (int i = n - 1; i >= 1; i--)
{
    int j = random.Next(1, i);
    int temp=myList[i];
    myList[i]=myList[j];
    myList[j]=temp;
}
xashru
  • 3,400
  • 2
  • 17
  • 30
0

You need to get the algorithm right.

Start from i=15

Pick a random number from 1 to i.

Append it to the list.

Swap it with (i-1)th index.

Decrement i by 1.

Repeat the above steps.

The code for above can be:

int[] myList = new int[15];
int[] original_list = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    Random random = new Random();

    for (int i = myList.Length; i>=0; i--)
    {int randNo = random.Next(0, i-1);
     myList[i] = original_list[randNo];
     swap(original_list[i-1],original_list[randNo]); //your swap method
    }
Animesh Sharma
  • 3,258
  • 1
  • 17
  • 33