How to generate a 2d matrix with one of the positions chosen separately having a different value?

Asked

Viewed 91 times

1

I want to generate a 10x10 matrix, where all elements will be "B", except one of the positions, which should be chosen randomly and have the value "8".

var m = [];

for(i=0; i < 10; i++){
  
  m[i] = [];
}
document.write("<table>");

for(i=0; i < 10; i++){

  document.write("<tr>");
  
  for(j=0; j<10;j++){
    //
    m[i][j]=["B"];

    document.write("<td>" + m[i][j] +"</td>");
  }
  document.write("</tr>")
}

document.write("</table>");

  • 1

    I reversed the edit because it misread the question (basically it was no longer a question at all, which invalidated the answer). If you want to leave your own solution, just use the answer field below

  • actually just wanted to thank, then tried to delete the text

2 answers

3


Since you want all positions to be "B", except one of them (randomly chosen), which should be "8", you may not even need to create the matrix. Just generate random numbers for the row and column that should have the "8", and in itself loop you check if it is in this row and column:

let tamanho = 10;
// escolhar linha e coluna aleatórias (entre zero e 9)
let linha = Math.floor(Math.random() * tamanho);
let coluna = Math.floor(Math.random() * tamanho);

document.write("<table>");
for (let i = 0; i < tamanho; i++) {
  document.write("<tr>");
  for (let j = 0; j < tamanho; j++) {
    if (i == linha && j == coluna) {
      // estou na linha e coluna escolhidas, imprime 8
      document.write("<td>8</td>");
    } else { // para todas as outras, imprime B
      document.write("<td>B</td>");
    }
  }
  document.write("</tr>")
}

document.write("</table>");


But if you want to save the matrix, just use the same idea to generate the values (and then do another loop to print it out):

let tamanho = 10;
// escolhar linha e coluna aleatórias (entre zero e 9)
let linha = Math.floor(Math.random() * tamanho);
let coluna = Math.floor(Math.random() * tamanho);

let m = [];
for (let i = 0; i < tamanho; i++) {
  m[i] = [];
  for (let j = 0; j < tamanho; j++) {
    if (i == linha && j == coluna) {
      // estou na linha e coluna escolhidas, valor é 8
      m[i].push('8');
    } else { // para todas as outras, valor é B
      m[i].push('B');
    }
  }
}

document.write("<table>");
for (let i = 0; i < tamanho; i++) {
  document.write("<tr>");
  for (let j = 0; j < tamanho; j++) {
    document.write(`<td>${m[i][j]}</td>`);
  }
  document.write("</tr>")
}

document.write("</table>");


Another option is to use fill to fill the arrays. Since in fact the "array" is an array of arrays (an array in which each element is another array), we can do so:

let tamanho = 10;
// criar array e preencher com outros arrays (por sua vez, preenchidos com "B")
let m = Array(tamanho).fill().map(() => Array(tamanho).fill('B'));

// escolhar linha e coluna aleatórias (entre zero e 9) e preencher com "8"
let linha = Math.floor(Math.random() * tamanho);
let coluna = Math.floor(Math.random() * tamanho);
m[linha][coluna] = '8';

document.write("<table>");
for (let i = 0; i < tamanho; i++) {
  document.write("<tr>");
  for (let j = 0; j < tamanho; j++) {
    document.write(`<td>${m[i][j]}</td>`);
  }
  document.write("</tr>")
}

document.write("</table>");

Array(tamanho) create an array of the specified size. Then fill in the positions of m with "nothing" (the first call to fill()), then map each value to another array filled with "B" (if you do only Array(tamanho).fill(Array(tamanho).fill('B')), all positions will be filled with the same array, and by changing a position from one to "8", this change will be reflected across all lines; already using map i guarantee that a new array is generated for each row).

Another way to create the array is:

let m = Array.from(Array(tamanho), () => Array(tamanho).fill('B'));

The idea is the same: I create an array with 10 positions, and each element of this is mapped to another array with 10 positions filled with "B".

-1

What you can do is by Math.random to decide whether to print "B" or "8".

In this example I am testing whether the random number is even shows "B" else "8":

m[i][j]= Math.floor(Math.random()*100) % 10 % 2 == 0 ? "B" : '8';
  • 1

    I’m glad you liked the answers! But the best way to thank those who helped you is to mark "accept" the best answer and vote for all who helped you. This way you make sure that whoever wrote the answer gets something in return, as well as making the site cleaner and more useful for everyone. Adding a new answer like this (which is not an answer to the question and should be removed) makes the site more confusing and can get in the way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.