I saw the following as an exercise in a website. It basically says write the following function without using recursion and without using structures like vector, stack, etc:
void rec(int n) {
if (n != 0) {
cout << n << " ";
rec(n-1);
rec(n-1);
}
}
At first I thought it was going to be easy, but I'm suprisingly struggling to accomplish it.
To understand it better, I defined it like a math function as the following:
f(x) = {1 if x = 0, f(x-1) + f(x-1) otherwise} (where + operator means concatenation and - is the normal minus)
However, Unrolling this made it harder, and I'm stuck. Is there any direct way to write it as a loop? And also, more generally, is there an algorithm to solve this type of problems?
Imagine the loop being put "on pause" while you go in to the function call. Just because the function happens to be a recursive call, it works the same as any function you call within a loop. The new recursive call starts its for loop and again, pauses while calling the functions again, and so on.
All iterative loops can be made into recursive functions. However, not ALL recursive functions can be iterative loops, or they are at least VERY complex. You won't find recursion in simple applications. However, they can be particularly useful in mathematical programming, searching algorithms and compilers.
Is a while loop intrinsically a recursion? then, yes, a while loop is a form of recursion. Recursive functions are another form of recursion (another example of recursive definition).
If you fiddle with it enough, you can get at least one way that will output the ordered sequence without revisiting it :)
let n = 5
// Recursive
let rec_str = ''
function rec(n) {
if (n != 0) {
rec_str += n
rec(n-1);
rec(n-1);
}
}
rec(n)
console.log(rec_str)
// Iterative
function f(n){
let str = ''
for (let i=1; i<1<<n; i++){
let t = i
let p = n
let k = (1 << n) - 1
while (k > 2){
if (t < 2){
break
} else if (t <= k){
t = t - 1
p = p - 1
k = k >> 1
} else {
t = t - k
}
}
str += p
}
console.log(str)
}
f(n)
(The code is building a string, which I think should be disallowed according to the rules, but only for demonstration; we could just output the number instead.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With