Quick actions

cmd+k|ctrl+k

Navigation

Languages

Dynamic Table

Snippet info

Language

JavaScript

Visibility

public

Author

franskbarek

Created

2023-03-20T04:05:49.725499Z

Updated

2023-03-20T08:13:16.365031Z

function dinamicTable(X, y) {
  // Find the longest length of a number in the array
  const max_length = Math.max(...X.map((num) => num.toString().length));

  // Calculate the number of rows needed
  const num_rows = Math.ceil(X.length / y);

  // Create the table
  let table = "+";
  for (let i = 0; i < y; i++) {
    table += "=".repeat(max_length) + "+";
  }
  table += "\n";

  for (let i = 0; i < num_rows; i++) {
    for (let j = 0; j < y; j++) {
      const index = i * y + j;
      if (index >= X.length) {
        break;
      }
      let num_str = X[index].toString();
      if (num_str.length < max_length) {
        num_str = "*".repeat(max_length - num_str.length) + num_str;
      }
      table += "|" + num_str;
    }
    // Add extra columns with no numbers to make the table relative
    const num_extra_cols = y - (X.length % y);
    if (i === num_rows - 1 && num_extra_cols !== y) {
      for (let j = 0; j < num_extra_cols; j++) {
        if (X.length == y--) return (table += "|" + " ".repeat(max_length));
      }
    }
    table += "|\n+";
    for (let i = 0; i < y; i++) {
      table += "=".repeat(max_length) + "+";
    }
    table += "\n";
  }

  return table;
}

// Sample input
const X = [12, 444, 54643, 3155, 667543, 8637, 0, 369, 7516, 335];
const y = 4;

// Call the function and print the output
console.log(dinamicTable(X, y));
INFO