У меня есть матрица с n строками и n столбцами. Мне нужно убедиться, что числа в каждой строке уникальны.
let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;
for ( let i = 0; i < matrixRows; i++ ) {
matrix[ i ] = [];
let j = 0;
while (j < matrixColumns) {
matrix[ i ][ j ] = Math.floor(Math.random() * 5) + 1;
j++;
}
}
console.info( matrix.join('\n') );
It should look something like this
"1,2,3,4,5 \\ here is line break (new row)
1,4,2,5,3 \\ here is line break (new row)
5,4,2,3,1"
Возможный дубликат Как получить уникальные случайные элементы из массива?
Вы можете сделать это, выполнив следующие действия:
rows
и cols
.shuffleArray
, которая принимает массив в качестве аргумента и возвращает новый массив, который перемешивается.cols
. По делу будет [1,2,3,4,5]
. Вы можете сделать это с помощью map()
undefined
длины, равной заданному rows
.map()
для этого и верните новый перетасованный массив, который мы создали ранее ([1,2,3,4,5]
)function shuffleArray(arr){
//create a copy of the array
arr = arr.slice();
//create an array on which random items from 'arr' will be added
let res = [];
//create while loop which will run until all the elements from arr are removed
while(arr.length){
//generate a random index in range of length of 'arr'
let i = Math.floor(arr.length * Math.random())
//push element at that index to result array
res.push(arr[i]);
//remove that element from the orignal array i.e 'arr'
arr.splice(i,1);
}
return res;
}
function randMatrix(rows,cols){
//create an array which will shuffled again and again.
let genArr = [...Array(cols)].map((x,i) => i + 1);
return [...Array(rows)] // create an array of undefined of length equal to rows
.map(x => shuffleArray(genArr)) // change that each to another shuffled array.
}
console.info(randMatrix(3,5).join('\n'))
Вы можете создать массив чисел до matrixColumns
, используя Array.from()
. Затем случайным образом перемешивайте массив на каждой итерации и создавайте строки (из этого ответа)
// https://stackoverflow.com/a/18806417/3082296
function shuffle(arr) {
let i = arr.length,
copy = [...arr], // take a copy
output = [];
while (i--) {
const j = Math.floor(Math.random() * (i + 1));
output.push(copy.splice(j, 1)[0]);
}
return output
}
let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;
// Natural numbers upto matrixColumns
const numbers = Array.from({ length: matrixColumns }, (_, i) => ++i)
const output = Array.from({ length: matrixRows }, _ => shuffle(numbers))
console.info(output)
Не самый элегантный, но он сначала создает плоский список уникальных случайных чисел и сводит его к матрице 2d n * m:
function fillRand (n, m) {
let rands = [];
do {
var rand = Math.random ();
} while (!~rands.indexOf (rand) && rands.push (rand) < n*m);
return rands.reduce ((mat, cur, i) => {
let last;
if (i%n==0) {
mat.push ([]);
}
last = mat[mat.length - 1]
last.push (cur);
return mat;
},[])
}
console.info (fillRand (4,5))
Будет ли это всегда столбец 3x5 и случайные числа от 1 до 5?