JohnSnow
JohnSnow

Reputation: 454

compute the result of a variable inside a recursive function

I have written the printing staircase algorithm. A function that given n prints the staircase n levels.

    var i = 1;
    function printStaircase(n) {
      //Base case
      if (n < 1) return n;
      //Recursive case
      var line = '';
      line += ' '.repeat(n - 1);
      line += '*'.repeat(i);
      console.log(line);
      i++;
      return printStaircase(n - 1);
    }
    
    printStaircase(10);

As you can see I have to pass in the i variable from the outside. I'm wondering how I can accomplish while computing the value of i inside the function body, so that it is self-contained and gets nothing from the global scope

Upvotes: 0

Views: 54

Answers (4)

Mulan
Mulan

Reputation: 135357

Recursion is super fun -

const chars = (c = "") => (n = 0) =>
  n === 0
    ? ""
    : c + chars (c) (n - 1)

const spaces =
  chars (" ")

const stars = 
  chars ("*")

const newline =
  "\n"

const stairs = (n, m = n - 1) =>
  m <= 0
    ? ""
    : spaces (m)
      + stars (n - m)
      + newline
      + stairs (n, m - 1)
      
console .log (stairs (10))

console .log (stairs (4))

Upvotes: 2

Sylwester
Sylwester

Reputation: 48755

Closure to the rescue:

/** 
  * @return stair case n high
  */
function staircase(n) {
  function helper (cur, str) {
    if (cur < 1) return str;
    return helper(
      cur - 1,
      `${str}${' '.repeat(cur)}${'*'.repeat(n-cur+1)}\n`);
  }
  return helper(n, '');
}

/**
  * prints a staircase n-1 hight
  * @return 0 (don't know why)
  */
function printStaircase(n) {
  console.log(staircase(n));
  return 0;
}

printStaircase(10);
printStaircase(3);

Upvotes: 1

Matt Burland
Matt Burland

Reputation: 45155

n and i are related in that i is simply the inital value of n minus the current value of n +1, so we can capture that quite nicely with something like:

function printStaircase(n) {
  staircaseInternal(n);

  function staircaseInternal(curr) {
    //Base case
    if (curr < 1) return;
    //Recursive case
    var line = ' '.repeat(curr - 1);
    line += '*'.repeat((n - curr) + 1);
    console.log(line);
    staircaseInternal(curr - 1);
  }
}

printStaircase(10);

Upvotes: 1

zenwraight
zenwraight

Reputation: 2000

I think something like this would work

function printStaircase(n, i) {
  //Base case
  if (n < 1) return n;
  //Recursive case
  var line = '';
  line += ' '.repeat(n - 1);
  line += '*'.repeat(i);
  console.log(line);
  i++;
  return printStaircase(n - 1, i);
}
printStaircase(10, 1);

Hope this helps!

Upvotes: 1

Related Questions