Recursive function
Iteration
// recursive function
function factorial(n) {
if (n === 0) {
return 1;
}
return factorial(n - 1) * n
}
// iteration
function factorial(n) {
let result = 1;
for (let i = 1; i < n + 1; i += 1) {
result *= i;
}
return result;
}
function fib(n) {
// base case
if (n < 3) {
return 1;
}
// recursive case
return fib(n - 1) + fib(n - 2);
}
// test code
for (let i = 0; i < 11; i += 1) {
console.log(fib(i));
}
function fib(n) {
// base case
let current = 1;
let previous = 1;
// recursive case
for (let i = 1; i < n; i += 1) {
temp = previous;
previous = current;
current = current + temp;
}
return current;
}
// test code
for (let i = 0; i < 11; i += 1) {
console.log(fib(i));
}
function flip(some_list) {
// base case
if (some_list.length <= 1) {
return some_list;
}
// recursive case
return some_list.slice(-1).concat(flip(some_list.slice(0, -1)));
}
# test code
console.log(flip([1,2,3,4,5]))
function move_disk(disk_num, start_peg, end_peg) {
console.log(`${disk_num}번 원판을 ${start_peg}번 기둥에서 ${end_peg}번 기둥으로 이동`);
}
function hanoi(num_disks, start_peg, end_peg) {
// base case
if (num_disks === 1) {
move_disk(1, start_peg, end_peg);
}
// recursive case
else {
hanoi(num_disks - 1, start_peg, 6 - start_peg - end_peg);
move_disk(num_disks, start_peg, end_peg);
hanoi(num_disks - 1, 6 - start_peg - end_peg, end_peg);
}
}
// test code
hanoi(3, 1, 3);
Reference