-8

I want to create multidimensional Array with Random r = new Random();

Each element should be generated randomly and they all must also be different elements. None of them should be same. Also I can not use any function.

Here is array but there are same elements. I want to all the elements were different.

   for (int i=0; i<3; i++)
        {
            for(int j=0; j<4; j++)
            {
                arr[i, j] = rand.Next(1,25);
            }
        }
pirho
  • 11,565
  • 12
  • 43
  • 70
  • “Each element should be generated randomly but there must be all different elements” is a contradiction. Perhaps you are looking for a [shuffle](https://stackoverflow.com/questions/273313/)? – Dour High Arch Nov 17 '17 at 22:10
  • I just need if statement which will check if element is same – Luka Mamulaishvili Nov 17 '17 at 22:12
  • 3
    There are only 25 possible numbers according to your code. You could make a `List` containing all 25, then shuffle the list, and then populate your array by taking one number after the other from your list. – Blorgbeard Nov 17 '17 at 22:14
  • 1
    So, whenever you create a new random element, check if it already exists, if so, generate a new one instead? – SirDarius Nov 17 '17 at 22:14
  • To do a shuffle, step through the array and swap values at each location with some other random location in the array. – David Rector Nov 17 '17 at 22:18
  • Possible duplicate of [Randomize a List](https://stackoverflow.com/questions/273313/randomize-a-listt) – Prune Nov 17 '17 at 22:43
  • 1
    @DavidRector that's *almost* a correct shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Implementation_errors – Blorgbeard Nov 17 '17 at 23:13
  • @Blorgbeard, Why almost? It's up to the programmer to deal with random number generator bias errors; I just said "random" meaning actual random numbers. – David Rector Nov 21 '17 at 01:27
  • 1
    @DavidRector sorry, that was annoyingly vague of me. I'm not referring to RNG bias. When you iterate and swap, you need to pick a random location *after* the current position. See second para under Implementation Errors at that link. – Blorgbeard Nov 21 '17 at 02:09

1 Answers1

1

In the lazy version, 1D shuffled array can be copied to 2D array:

Random rand = new Random();
int[] shuffled = Enumerable.Range(1, 25).OrderBy(rand.Next).ToArray();

int[,] arr = new int[3, 4];
Buffer.BlockCopy(shuffled, 0, arr, 0, arr.Length * sizeof(int));
Slai
  • 22,144
  • 5
  • 45
  • 53