Warm tip: This article is reproduced from stackoverflow.com, please click
c# generator matrix random

matrix 4x4 with random number but not repeat (C#)

发布于 2020-04-11 22:37:40

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!

Questioner
Asia Piazza
Viewed
61
Flutterish 2020-02-03 00:42

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
}