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!
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
}
How can you guarantee that no repeating values appear in the matrix?
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.
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?
Yes, then they will appear in the same order as in the origin list.