-1

I would like to generate random numbers from 1 to 16 , but once that number has been generated I would like it so that it cannot be generated again in the matrix. I couldn't find a way to do that, so thanks for the help!

Asia Piazza
  • 95
  • 2
  • 9
  • 4
    Hint: create a list of all 16 numbers that are available. Then shuffle it. There are lots of questions and answers about shuffling. – Jon Skeet Feb 02 '20 at 15:16
  • 3
    Does this answer your question? [Generating random numbers without repeating.C#](https://stackoverflow.com/questions/30014901/generating-random-numbers-without-repeating-c) – Marius Feb 02 '20 at 15:19

1 Answers1

1

A very easy way to achieve this is to generate all the numbers, shuffle them and just fill the matrix with them.

Random rng = new Random(); // System.Random
List<(double random, int value)> values = new List<(double random, int value)>(); // list for shuffling
for ( int i = 0; i < 16; i++ ) {
    values.Add( ( rng.NextDouble(), i + 1 ) ); // random position and the value
}
values.Sort( ( a, b ) => b.random - a.random ); // sort using the random position. Note : Sort is a System.Linq extension method
int[,] matrix = new int[4,4];
for ( int i = 0; i < values.length; i++ ) {
    matrix[ i % 4, i / 4 ] = values[ i ].value; // populate the matrix
    // i % 4 just loops i between 0 and 3
    // i / 4 divides i by 4 and rounds DOWN, ie. increases by 1 each 4
}
Peri
  • 574
  • 1
  • 3
  • 19
  • How can you guarantee that no repeating values appear in the matrix? – Carlos Feb 02 '20 at 16:52
  • There are no repeated values in the list it is populated by. The loop generates 1..16 as the value and some random number as the order. – Peri Feb 02 '20 at 16:53
  • That's an interesting approach. What if the random position appears duplicate (very low chance)? Sorting will just put the values side-by-side, correct? – Carlos Feb 02 '20 at 16:56
  • Yes, then they will appear in the same order as in the origin list. – Peri Feb 02 '20 at 16:58