Function Ladder

Asked

Viewed 537 times

1

I’m studying javascript now and have a question on how to make a ladder program:

inserir a descrição da imagem aqui

Follow my code below:

function escada(numero) {

  var arrayEscada = [];

  var espaco = " ";
  var traco = "#";

  for (var i = 0; i < numero ; i++) {

     numero = numero - 1;
     arrayEscada.push(espaco * numero);
     arrayEscada.push(traco * (i + 1) );

  }

  return arrayEscada;
}

1 answer

3

The problem lies in the fact that, unlike other languages, to repeat a character in Javascript, you cannot do something like this:

'#' * 5; // NaN

Must use the method String.prototype.repeat.

Anyway, you can do something like this:

function escada(degraus) {
  const escadaArray = [];
  const espacoChar = ' ';
  const degrauChar = '#';

  for (let i = 1; i <= degraus; i++) {
    const espacosParaAdd = espacoChar.repeat(degraus - i);
    const degrausParaAdd = degrauChar.repeat(i);

    escadaArray.push(espacosParaAdd + degrausParaAdd);
  }

  return escadaArray;
}

console.log(escada(3));
console.log(escada(5));

Some notes regarding the above example:

  1. We define the number of steps of each walk from the variable (i), that is incremented with each iteration;
  2. To calculate the number of spaces to be placed before the step, simply subtract the total number of steps from the number of steps of the current iteration (i).

Going a little further, if you want a slightly less imperative solution, you can do so too (example a little more advanced):

function makeStair(steps, step = '#', space = ' ') {
  return Array.from(
    { length: steps },
    (el, i) => space.repeat(steps - i) + step.repeat(++i)
  );
}

console.log(makeStair(3));
console.log(makeStair(5));

Recommended reading:

Browser other questions tagged

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