计算递归函数中变量的结果



我已经编写了打印楼梯算法。给定 n 打印楼梯 n 层的函数。

    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);

如您所见,我必须从外部传入i变量。我想知道如何在计算函数体内 i 的值时完成,以便它是自包含的并且从全局范围内一无所获

递归超级有趣 -

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))

ni 是相关的,因为i只是 n 的初始值减去 n +1 的当前值,因此我们可以很好地捕获它:

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);

我认为这样的事情会起作用

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);

希望这有帮助!

结束救援:

/** 
  * @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);

最新更新