Escada Javascript

Asked

Viewed 534 times

2

"use strict"
let array = []
function exibeNumero(entrada) {
    for (let i = 0; i < entrada; i++) {
        array.push("#".repeat(i))
    }
    for (const entrada of array) {
        console.log(entrada)
    }
}
exibeNumero(10)

I’m trying to change the side of the ladder. That’s the result I’m getting inserir a descrição da imagem aqui

I want to reverse her side, stay like this inserir a descrição da imagem aqui

3 answers

3

Try using this loop:

for (const linha of array) {
    console.log(linha.padStart(entrada-1, ' '))
}

The method padStart adds the character passed as the second parameter at the beginning of the string, until it reaches the size passed in the first parameter.

1


Also can solve using only the repeat you already have in your code. The idea is to first write a certain amount of spaces and then join with a number of # that makes sense for the line on which it goes.

In a scenario where the final size is 5 characters, each line would have the following characters::

  • 4 spaces, 1 #
  • 3 spaces, 2 #
  • 2 spaces, 3 #
  • 1 space, 4 #
  • 0 spaces, 5 #

Implementation:

let array = []
function exibeNumero(entrada) {
    for (let i = 0; i < entrada; i++) {
        array.push(" ".repeat(entrada - i - 1) + "#".repeat(i + 1))
        //          ^^^^^^^^^^^^^^^^^^^^^^^^^^                ^^^
    }
    for (const entrada of array) {
        console.log(entrada)
    }
}
exibeNumero(5)

The only instruction changed was the one that puts the element in the array. Note that it was necessary to change the repeat of the # so that the first time already write a character instead of zero.

0

A solution:

function escada (n){   

    var array = [];
    var cont = 1;

    for (i=0; i<n; i++){
        array[i] = '#'.repeat(cont).padStart(n);
        cont++;
    }
    return array;
}

Browser other questions tagged

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