Number triangle

Easy TimeO(n²) SpaceO(n²)

Given a row count n, return a triangle whose rows count up from 1, as an array of n strings. Row 1 is "1", row 2 is "12", and row i runs 1 to i. The counting restarts on every row, and the numbers are written with no separator between them.

Examples

Example 1

Input
n = 5
Output
1
12
123
1234
12345
["1","12","123","1234","12345"]
Every row begins at 1 again and stops at its own number.

Example 2

Input
n = 10
Output
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
["1","12","123","1234","12345","123456","1234567","12345678","123456789","12345678910"]
Row 10 ends 910, which is 9 followed by 10 — with no separator, a two-digit number runs into its neighbour.

The Code

function numberTriangle(n) {
  const rows = [];
  for (let row = 1; row <= n; row++) {
    let line = "";
    for (let col = 1; col <= row; col++) {
      line += col;
    }
    rows.push(line);
  }
  return rows;
}
numberTriangle(5);
Done

The first 19 calls, of 27. This one does not fit on a page.

Step through numberTriangle(5) call by call

Explanation

A row prints its own count of positions, not a running total, so it depends on nothing outside itself. That is the whole difference from Floyd’s triangle: the same two loops, printing a different thing.

  1. 1

    row is 1 and the inner loop runs while col is at most row. line += col appends the counter itself rather than a star, so the row reads "1".

    1
    0

    row=1col=1

    rows.push("1")

  2. 2

    row is 2. col is declared in the inner loop’s own header, so it starts at 1 again here — the row reads "12" rather than carrying on from where row 1 stopped.

    1
    0
    12
    1

    row=2col=1 then 2

    rows.push("12")

  3. 3

    row is 3, so col runs 1, 2, 3. Every number a row prints is worked out from col alone, which is why no row depends on any other.

    1
    0
    12
    1
    123
    2

    row=3col=1 … 3

    rows.push("123")

  4. 4

    row is 4 — four passes, the digits 1 to 4.

    1
    0
    12
    1
    123
    2
    1234
    3

    row=4col=1 … 4

    rows.push("1234")

  5. 5

    row is 5, so col runs 1 to 5 and the row reads "12345". row++ then fails row <= n and the five strings are returned.

    1
    0
    12
    1
    123
    2
    1234
    3
    12345
    4

    row=5col=1 … 5

    return rows → 5 rows