1

I'm a really beginner and for now im preparing for JavaScript bootcamp. Unfortunately i stuck with one of pre-work excercises.

My task is to do muliplication table, put it into empty 2D Array and print it precisely in this form:

1 x 1 = 1 | 1 x 2 = 2 | 1 x 3 = 3
2 x 1 = 2 | 2 x 2 = 4 | 2 x 3 = 6
3 x 1 = 3 | 3 x 2 = 6 | 3 x 3 = 9

On start I have 2 var declared: const n = 3; const calc = [];

I know i have to start with 'for' loop - and i have no idea whats next;

for (let i = 1; i <= n; i++) { }

EDIT: Thanks for help, correct code below:

const n = 3;
const calc = [];


for(let i = 0; i < n; i++){
    calc[i] = [];
    for(let k = 0; k < n; k++){
        calc[i][k] = (i + 1) + ' * ' + (k + 1) + ' = ' + (i + 1) * (k + 1);
    }
}
for(let i = 0; i < calc.length; i++){
    console.log(String(calc[i]).replaceAll(',', ' | '));
}

4 Answers4

0

This is what I have come up with...

n = 3;
// create table array
table = [];
for(row=0; row<n;row++){
    // generate an array for each row
    table.push([])
    for(col=0; col<n;col++){
        // add the multiplication to each column in the row
        // Notice that the column and row numbers start at zero in an array so 1 is added before multiplying
        table[row].push((col+1) + ' x ' + (row+1) + ' = ' + (col+1)*(row+1));
    }
}
// print the array to the console for fun
console.log(table);
// go through each row in table array, convert it to a string and replace ',' with ' | ' and printing it to the log
// Notice that in the replace argument you have to use /,/g instead of ',' in order to replace all commas and not just the first one
for(row=0; row<table.length;row++){ 
    console.log(String(table[row]).replace(/,/g, ' | '))
}

I have added a bit of commenting. Hopefully you can see what is going on.

avt613
  • 309
  • 2
  • 5
0

You need two 'for' loops to fill the array in 2D. After that you need another 'for' loop to print each row (for example in a paragraph tag).

Working example:

const n = 3; 
const calc = [];

for(i = 0; i < n; i++){
    calc[i] = [];         //add the inner arrays (the second dimension)
    for(k = 0; k < n; k++){ 
        calc[i][k] = (k + 1) + ' x ' + (i + 1) + ' = ' + (k + 1) * (i + 1);
    }
}

for(i = 0; i < calc.length; i++){ 
    const p = document.createElement("p");
                          //convert each inner array to a string
    p.innerHTML = String(calc[i]).replaceAll(',', ' | ');
    document.querySelector('#container').appendChild(p);
}
<div id="container"></div>
biberman
  • 5,606
  • 4
  • 11
  • 35
0

Here is the code I would write to solve your problem.

function generate(num, fn) {
  var a = Array(num), b = 0;
  while (b < num) a[b] = fn(b++);
  return a;
}
const table = (num, fn, separator) => generate(num, fn).join(separator);
const entry = (a, b) => `${a} x ${b} = ${a * b}`;
const result = table(3, row => table(3, col => entry(row + 1, col + 1), ' | '), '\n');

console.log(result);

generate returns an array like [fn(0), fn(1), fn(2), ..., fn(num-1)]. There's more than one way to do this but what I provided here is pretty quick.

table calls generate, but with the elements joined together into a string with a separator between them.

entry formats the text of one entry in the table like: 2 x 3 = 6

The result is a table of tables (a two-dimensional table) with | delimiting the columns and \n delimiting the rows.

Note:

If you insist on having a complete 2D array, you could defer the joins until later like this, but it's slower:

function generate(num, fn) {
  var array = Array(num), i = 0;
  while (i < num) array[i] = fn(i++);
  return array;
}
const entry = (a, b) => `${a} x ${b} = ${a * b}`;
const array2d = generate(3, row => generate(3, col => entry(row + 1, col + 1)));
const result = array2d.map(row => row.join(' | ')).join('\n');

console.log(result);
Wyck
  • 10,311
  • 6
  • 39
  • 60
0

1 Loop for Rows and 1 Loop for Columns

OP wasn't specific about what said output of the multiplication table should be in -- HTML, text, ponies...?

A table can be generated by an outer loop and an inner loop:

  1. The outer loop generates an array rows of a table.
    [row 1, row 2, row 3]

  2. The inner loop generates an array of cells (forming a column) for each row.
    [col 1, col 2, col 3]

  3. So a 2D array looks like one or more arrays within an array.
    [ row 1[col 1, col 2, col 3], row 2[col 1, col 2, col 3], row 3[col 1, col 2, col 3] ]

The example below is a function that will pass a number (num) through and return a table with the same amount of rows and columns as the parameter passed (num). Each cell will contain the text of a simple formula:

row number * col number = X

Each col is delimited by a pipe |, and each row is delimited by a new line.

Details are commented in Snippet

// Pass a number [num]
function mTable(num) {
  // Declare [row] array [rData]
  const rData = [];
  // for each [row] until [num] is reached...
  for (let row = 1; row <= num; row++) {
    //... declare [col] array [cData]...
    const cData = [];
    //... then for each [col] until [num] is reached...
    for (let col = 1; col <= num; col++) {
      //... generate the text✱ repesenting the product of the row and column numbers...
      const cell = `${row} X ${col} = ${row*col}`;
      //... next, push it to the [cData] array
      cData.push(cell);
    }
    // Once the [cData] is created, convert it into a formatted line of text delimited by pipes '|'
    const data = cData.join(' | ');
    // Push the [cData] array into the [rData] array
    rData.push(data);
  }
  // After the last [cData] array is pushed into the [tData] array, output [tData] as a formatted line of text delimited by new lines✱
  return rData.join(`
`);
}

// Generate a 3x3 table 
console.log(mTable(3));

// Generate a 8x8 table
console.log(mTable(8));

/* 
✱The special syntax wrapped in grave ticks `...` is called template literals see References
*/

References

zer00ne
  • 41,936
  • 6
  • 41
  • 68