我写了打印阶梯算法。给定 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的值时完成它,使其成为自包含的,并且不会从全局范围得到任何东西
答案 0 :(得分:2)
递归非常有趣-
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))
答案 1 :(得分: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);
答案 2 :(得分:1)
我认为类似的事情会起作用
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);
希望这会有所帮助!
答案 3 :(得分:1)
n
和i
是相关的,因为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);