Как случайным образом заполнить строки матрицы? - PullRequest
1 голос
/ 29 мая 2019

У меня есть матрица с 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.log( 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"

Ответы [ 3 ]

0 голосов
/ 29 мая 2019

Вы можете создать массив чисел до 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.log(output)
0 голосов
/ 29 мая 2019

Не самый элегантный, но он сначала создает плоский список уникальных случайностей и сокращает его до 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.log (fillRand (4,5))
0 голосов
/ 29 мая 2019

Вы можете сделать это в следующих шагах:

  • Сначала создайте функцию, которая принимает два параметра 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.log(randMatrix(3,5).join('\n'))
...