2

I have a matrix with n-rows and n-columns. I need to make sure that the numbers in each row are unique.

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 Answers3

0

You can do that in following steps:

  • First create a function which takes two parameters rows and cols
  • Then create a helper function shuffleArray which takes an array as argument and return a new array which is shuffled.
  • In the main function create an array of number for the no of cols. In the case it will be [1,2,3,4,5]. You can do that using map()
  • Then create an array of undefined of length equal to the given rows.
  • Use map() on that and return a new shuffled array that we created before([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'))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You could create an array of numbers upto matrixColumns using Array.from(). Then shuffle the array randomly in every iteration and create rows (from this answer)

// 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)
adiga
  • 34,372
  • 9
  • 61
  • 83
0

Not the most elegant, but this first creates a flat list of unique randoms and reduces that to a 2d n*m matrix:

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))
Moritz Roessler
  • 8,542
  • 26
  • 51