Return with a recursive function - algorithm

I'm curious how return works when using a recursive function. For example, in the factorial function below, x will reach 1 before any calculations can actually occur.
int factorial (int x){
if (x==1){
return 1;
}else{
return x * factorial(x - 1);
}
}
Suppose x = 3. Following the logic, it seems it should loop 3 times and return 1:
3 != 1
so else: 3 * factorial (2).
What's factorial (2)?
Well return to top: 2 != 1
so else: 2 * factorial (1).
What's factorial (1)?
Return to top: 1 == 1,
so: return 1.
But, of course it will actually return 6. So how does it work, exactly?

Every time you say "well what's the value from that recursive call?", you're dropping the x * from the previous iteration. Without doing that:
factorial(3)
3 * factorial(2)
3 * (2 * factorial(1))
3 * (2 * 1)
= 6
Recursive calling is not like a goto to the top of the function again with new arguments.1 We call the function again with new arguments, but only that invocation has the new argument value: the caller still has the old value of its arguments and variables.
1 Unless we're talking about tail recursion, which we aren't, and that's just an optimization anyways.

It's not returning to top, it's invoking the factorial function inside the factorial function.
Indeed, at the end, it returns 1, but it returns it as a result in the line
return x * factorial(x - 1);
of the previous call to factorial, where x was 2. This in turn returns 2 * 1 to the previous call to factorial where x was 3. So this gives 3 * 2, returning the result - 6 - to the first invocation of the function.

A recursive function call is no different from an ordinary function call. So there's no connection between the return of one call and the return of another.
In the example, the first return statement is
return 3 * factorial(2)
which multiplies 3 by the return value of calling factorial with an argument of 2.
But the return value of factorial(2) is
return 2 * factorial(1)
which multiplies 2 by the return value of calling factorial with an argument of 1.
But the return value of factorial(1) is 1.
So return 2 * factorial(1) is the same as return 2 * 1, which is 2.
So return 3 * factorial(2) is the same as return 3 * 2, which is 6.

In the first step, x = 3. Your function then returns 3 * factorial(2), which itself returns 2 * factorial(1) (since x still isn't equal to 1), and finally, factorial(1) returns 1.
So in the end you get 3 * 2 * 1 = 6.

Stack frame is a record that is used at run time to store information about a function call, including the parameters, local variables, register values, and return address. For each successive function calls we are pushing stack frame into stack and when any active function (function which is at top of the stack) gets return call, it’s stack frame is popped up from the stack and the function below it gets active. Here is the example.
So, finally the function factorial(3) return value 6.

Related

Excess (-1) in base 4 representation

I've been trying to wrap my head around this one problem for the last couple of days, and I can't figure out a way to solve it. So, here it goes:
Given the base 4(that is 0, 1, 2, 3 as digits for a number), find the excess (-1) in base 4 representation of any negative or positive integer number.
examples:
-6 = (-1)22
conversely, (-1)22 in excess (-1) of base 4 = 2 * 4^0 + 2 * 4^1 + (-1) * 4^2 = 2 + 8 - 16 = 10 - 16 = -6 in base 10
27 = 2(-1)(-1)
conversely, 2(-1)(-1) = (-1) * 4^0 + (-1) * 4^1 + 2 * 4^2 = -1 - 4 + 32 = 27
I did come up with a few algorithms for positive numbers, but none of them hold true for all negative numbers, so into the trash they went.
Can anyone give me some kind of clue here? Thanks!
----------------
Edit: I'm going to try to rephrase this question in such a way that it does not raise any confusions.
Consider the radix obtained by subtracting 1 from every digit, called the excess-(-1) of base 4. In this radix, any number can be represented using the digits -1, 0, 1, 2. So, the problem asks for an algorithm that gets as an input any integer number, and gives as output the representation of that given number.
Examples:
decimal -6 = -1 2 2 for the excess-(-1) of base 4.
To verify this, we take the representation -1 -1 2 and transform it to a decimal number, start from the right-most digit and use the generic base n to base 10 algorithm, like so:
number = 2 * 4^0 + 2 * 4^1 + (-1) * 4^2 = 2 + 4 - 16 = -6
I don't know if "quaterit" is the correct word for the radix in this representation, but I'm going to use it anyway.
Since you say you already have an algorithm for positive numbers, I'll try to take a negative number as an input and write something that uses what you already have. The code below doesn't quite work, but I'll explain why at the end.
int[] BaseFourExcessForNegativeNumbers(int x) {
int powerOfFour = 1;
while (-powerOfFour > x) {
powerOfFour *= 4;
}
int firstQuaterit = -1;
int remainder = x + powerOfFour;
int[] otherQuaterits;
if (remainder >= 0) {
otherQuaterits = BaseFourExcessForPositiveNumbers(remainder);
} else {
otherQuaterits = BaseFourExcessForNegativeNumbers(remainder);
}
int[] result = new int[otherQuaterits.Length + 1];
result[0] = firstQuaterit;
for (int index = 0; index < otherQuaterits.Length; ++index) {
result[index + 1] = otherQuaterits[index];
}
return result;
}
The idea here is that every negative number x will start with a (-1) in this representation. If that (-1) is in the 4^n position, we want to find out how to represent x - (-1)*4^n to see how to represent the rest of the number.
The reason the code I wrote won't work is that it doesn't take into consideration the possibility that the second quaterit is a 0. If that happens, the array my code will produce will be missing that 0. In fact, if BaseFourExcessForPositiveNumbers is written in the same way, the resulting array will be missing every 0, but will otherwise be correct. A workaround is to keep track of which place the first quaterit takes, and then make the array that size, and fill it from the back to the front.

Possible Staircases using Dynamic Programming

For the Staircase problem mentioned in the URL http://acm.timus.ru/problem.aspx?num=1017&locale=en
Can we solve it in linear time O(k) where k is the maximum steps possible? I felt like missing some logic using below approach
Any Suggestions?
Below is the code That I have implemented:
def answer(n):
steps = determine_steps(n)
x = ((n -1) - n/steps) * ((n-2) - n/steps + 1) #Minimum of two stair case
for i in range(3, steps):
x = x * ((n-i)/i) #Stairs from 3 can go from minimum height 0 to max (n-i)/i
return x
def determine_steps(n):
"""Determine no of steps possible"""
steps = 1;
while (steps * steps + steps) <= 2 * n:
steps = steps + 1
return steps - 1
#print answer(212)
print answer(212)
Suppose, you have a function which takes 2 parameters, one left which is number of bricks left and the other one is curr which is the current height of the step which you are on. Now, at any step you have 2 options. The first option is to increase the height of the current step you are on by adding one more brick, i.e., rec(left-1, curr+1) and the second option is to create a new step whose height should be greater than curr ,i.e., rec(left-curr-1, curr+1) ( you created a step of height curr+1 ). Now, left can never be negative , thus if left<0 then return 0. And when left is 0 that means, we have created a valid staircase,thus if left==0 then return 1.
This case: if dp[left][curr] !=-1 is just for memoization.
Now, rec( 212-1, 1 ) means a step of height 1 is created and it is the current step. And for final answer 1 is subtracted because any valid staircase should contain at least 2 steps so, subtracting 1 for single step staircase.
# your code goes here
dp = [ [-1]*501 for i in range(501) ]
def rec(left, curr):
if left<0:
return 0
if left==0:
return 1
if dp[left][curr] !=-1:
return dp[left][curr]
dp[left][curr] = rec(left-1, curr+1) + rec( left-curr-1, curr+1)
return dp[left][curr]
print ( rec(212-1,1) - 1 )
Feel free to comment back, if you are not able to understand the code.

How to have a custom rounding function?

Basically, I need FormatNumber to behave slightly differently. Of course, we can write our own MyFormatNumber, but basically, it should return the following:
59.080 returns 59.08
59.081 returns 59.08
59.082 returns 59.08
59.083 returns 59.08
59.084 returns 59.09 ←
59.085 returns 59.09
59.086 returns 59.09
59.087 returns 59.09
59.088 returns 59.09
59.089 returns 59.09
As you can see, the only difference is when the 3rd decimal place is a 4, then I would like to round up. That is, when the input's third decimal place is 4 or greater, then do a round up, otherwise round down.
How can we do such a function in Classic ASP?
A custom rounding function could be implemented like this:
Function CustomRound(n)
If n * 1000 Mod 10 < 4 Then
CustomRound = Int(n * 100) / 100
Else
CustomRound = (Int(n * 100) + 1) / 100
End If
End Function

Why does .to_s break this code?

I'm working on a Codewars Ruby problem, and don't understand the error I'm seeing. Here are the instructions:
Coding decimal numbers with factorials is a way of writing out numbers
in a base system that depends on factorials, rather than powers of
numbers. In this system, the last digit is always 0 and is in base 0!.
The digit before that is either 0 or 1 and is in base 1!. The digit
before that is either 0, 1, or 2 and is in base 2!. More generally,
the nth-to-last digit in always 0, 1, 2, ..., or n and is in base n!.
Example : decimal number 463 is coded as "341010"
because 463 (base 10) = 3×5! + 4×4! + 1×3! + 0×2! + 1×1! + 0×0!
If we are limited to digits 0...9 the biggest number we can code is
10! - 1.
So we extend 0..9 with letters A to Z. With these 36 digits we can
code up to 36! − 1 = 37199332678990121746799944815083519999999910
(base 10)
We code two functions, the first one will code a decimal number and
return a string with the factorial representation :
"dec2FactString(nb)"
the second one will decode a string with a factorial representation
and produce the decimal representation : "factString2Dec(str)".
Given numbers will be positive.
Note
You can hope tests with Big Integers in Clojure, Python, Ruby, Haskel
but not with Java and others where the number "nb" in
"dec2FactString(nb)" is at most a long.
Ref: http://en.wikipedia.org/wiki/Factorial_number_system
def dec2FactString(nb)
if nb <= 0 then
num = 1
else
num = (nb * dec2FactString(nb - 1))
end
return num
end
Note that this method is only the first half of the problem. This code appears to work inasmuch as it returns the correct factorial, as a Fixnum when using this test:
Test.assert_equals(dec2FactString(4), "24")
Since the instructions ask for a string, I'd normally think that just adding ".to_s" to the num variable would take care of that, but instead I'm seeing a consistent "String can't be coerced into Fixnum (TypeError)" error message. I've tried pushing the output to an array and printing from there, but saw the same error.
I read up on Fixnum a little, and I understand the error in terms of adding a Fixnum to a string won't work, but I don't think I'm doing that in this case - I just want to convert the Fixnum output into a string. Am I missing something?
Observe - this code breaks and produces the error below it:
def dec2FactString(nb)
if nb <= 0 then
num = 1
else
num = (nb * dec2FactString(nb - 1))
end
return num.to_s
end
Example from description
`*': String can't be coerced into Fixnum (TypeError)
from `dec2FactString'
from `dec2FactString'
from `dec2FactString'
from `dec2FactString'
from `block in
'
from `block in describe'
from `measure'
from `describe'
from `
'
You're calling this function recursively. If you calculated the factorial of 1 and left to_s in there, it'd be fine since you're not reusing the variable.
However, if you do place to_s in there, what would you expect the result of num = (nb * dec2FactString(nb - 1)) to be? dec2FactString would be returning a str instead of a Fixnum, and you can't/shouldn't be able to do multiplication between a number and a string.
What you could do is split the responsibilities of stringification and calculation by creating two methods - one that delegates to the recursive function, and one that coerces its result into a string.
def dec2FactString(nb)
return fact(nb).to_s
end
def fact(nb)
if nb <= 0 then
1
else
nb * fact(nb - 1)
end
end
Firstly, Factorial is only defined on non-negative numbers and so your first test is incorrect (if nb <= 0). The recursion should stop when the number is 0 and should return 1 at that point.
Because your recursion returns a string and not a number, you cannot multiply the string by a Fixnum in the next round of recursion. Your recursion can be expanded via the substitution method to the following.
dec2FactString(5)
5 * dec2FactString(4)
5 * 4 * dec2FactString(3)
5 * 4 * 3 * dec2FactString(2)
5 * 4 * 3 * 2 * dec2FactString(1)
5 * 4 * 3 * 2 * 1 * dec2FactString(0)
5 * 4 * 3 * 2 * 1 * "1"
... That is the point where the recursion ends in an error since dec2FactString(0) returns "1"
It would be far better to break it into two functions. One that calculates factorial recursively and one that converts the final answer to a string. Also, you don't need to explicitly return a value in Ruby. The last line of a function is the return value.
I won't give you the complete code as you won't learn anything. As a few hints, do some research on tail call optimisation, recursion and return values in Ruby. This will allow you to craft a better implementation of the recursive function.
Happy coding!

Return values not working as expected in Ruby in a program that solves fibonacci sequence using dynamic programming

I'm new to ruby so I'm probably making a very newbie mistake here but I tried Googling for an answer and couldn't figure out the reason why this code is giving weird behavior. This code is very simple, and uses basic dynamic programming to store intermediate result to a Hash so it is used later to speed up the computation.
$existingSequence = {0 => 1, 1 => 2}
def fib(n)
if $existingSequence.has_key? n
return $existingSequence.values_at n;
end
if n == 0
return 1;
elsif n == 1
return 2;
end
$existingSequence[n] = fib(n - 1) + fib(n - 2)
return $existingSequence[n];
end
n = fib(2)
puts n
I expect this code to output 3 since that makes a call to fib(1) and fib(0) which returns 2 and 1 respectively, and then added to be 3. But the output is 1 and 2.
Hash.values_at returns an array, so when the code does fib(1) + fib(0), it's concatenating the arrays [2] and [1] together, resulting in the answer [2, 1]. Instead of:
return $existingSequence.values_at n;
...you should do this instead:
return $existingSequence[n]
BTW, the Fibonacci sequence traditionally starts with 0 and 1, not 1 and 2.
Slightly off-topic, here's a fun way of doing essentially the same thing, but using the Hash default value mechanism to use the Hash not only for caching, but also for computing the values:
fibs = { 0 => 0, 1 => 1 }.tap do |fibs|
fibs.default_proc = ->(fibs, n) { fibs[n] = fibs[n-1] + fibs[n-2] }
end
fibs[9]
# => 34
Note: I didn't come up with this myself, I stole it from here.
The second line of fib should read:
return $existingSequence[n]
instead of
return $existingSequence.values_at n
Add puts $existingSequence to the end of the file to see the difference.

Resources