I am trying to write a problem that outputs a similar pattern to this using recursion.
cascade(12345) //should print
12345
1234
123
12
1
12
123
1234
12345
I figured out how to do the descending part but I am stuck on how to ascend back up! This is what I have so far...
function cascade(number) {
let strNum = number.toString()
let numLength = strNum.length;
let lengthTracker = numLength
let hasHit1 = false;
console.log(strNum)
if (lengthTracker > 1 && hasHit1 === false) {
strNum = strNum.substring(0, strNum.length - 1);
lengthTracker--;
return cascade(strNum)
} else {
return strNum;
}
}
cascade(143)
this successfully outputs
'143'
'14'
'1'
How would I add the numbers back onto it one by one afterward?
Thank you for your time!
Another (recursive) approach by using a string.
function cascade(s) {
s = s.toString();
console.log(s);
if (s.length === 1) return; // exit condition
cascade(s.slice(0, -1));
console.log(s);
}
cascade(12345);
.as-console-wrapper { max-height: 100% !important; top: 0; }
RECURSIVE APPROACH 🔁
function cascade(n) {
if (n === 0) return;
const remain = Math.floor(n / 10);
console.log(n);
String(remain).length !== 1 ? cascade(remain) : console.log(remain);
console.log(n);
}
cascade(12345);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
ITERATIVE APPROACH ⏯
function cascade(n) {
const lasts = [];
while (n) {
lasts.push(n);
console.log(n);
n = Math.floor(n / 10);
}
lasts.length--;
while (lasts.length) console.log(lasts.pop());
}
cascade(12345);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
A simple recursion will return these values, leaving you to log them in a separate step. It might look like this:
const cascade = (n) =>
n < 10 ? [n] : [n, ... cascade ((n - n % 10) / 10), n]
for (let n of cascade (12345)) console .log (n)
.as-console-wrapper {max-height: 100% !important; top: 0}
Note the separate line to print the result, since the function returns an array such as
[12345, 1234, 123, 12, 1, 12, 123, 1234, 12345]
The little bit of math in the argument to the recursive call to cascade calculates the new number when we strip off the last digit and divide by ten. We could do this in different ways replacing the function body with:
n < 10 ? [n] : [n, ... cascade (Math .floor (n / 10)), n]
or the slightly more obscure, but shorter
n < 10 ? [n] : [n, ... cascade (~~ (n / 10)), n]