Homework, trying to learn recursion is this correct? - recursion

Ok, recursion is giving me "coders block" I have 2 homework assignments this week, one of them is simply the following..
Design a function that accepts an integer argument and returns the sum of all the integers from
1 up to the number passed as an argument. For example, if 50 is
passed
as an argument, the fu
nction
will return the sum
of 1, 2, 3, 4,
...
.50
. Use the recursion to calculate the sum.
This is my solution... am I understanding how this works? The book is teaching us via some fake psuedocode so I know it's not "real" code....
Function Integer SumAll(Integer Number)
If Number > 0 Then
Return Number + SumAll(Number-1)
Else
Return 0
End If
End Function
OK I think this is it, I wrote this in c++ to test it out.
#include <iostream>
using namespace std;
int SumAll(int Number){
if (Number > 0) {
return Number + SumAll(Number-1);
}
}
int main(){
cout<<SumAll(2);
return 0;
}

Your C++ code is buggy because the base case needs to be treated in the recursive function itself.
Your pseudocode is basically correct except that it doesn't work when Number < 0; you should really have an error message in that case.
I agree with the comments that you cannot possibly work in the dark; use a real programming language. Your pseudocode looks a lot like Pascal, so maybe you can use Free Pascal here. Otherwise, I'd recommend Python.
In Python 3, the code would look like this:
def sum_all(number):
if number > 1:
return number + sum_all(number-1)
elif number == 1: # base case
return 1
else:
raise Exception("negative number")
print(sum_all(10))
which would correctly return 55.
When I made my studies, the teacher also used some kind of pseudocode similar to Pascal. We agreed very early on that I would use Turbo Pascal instead, and that helped me a lot because I was able to test things on the PC.

Related

Change the sign of one number to match the sign of another number

I'm not really sure what to search for on this.
If I have a variable A = 10. And another variable B. If B is negative I want to make A = -10. If B is positive I want A = 10.
Here is how I have been doing this quite often:
A = A * abs(B) / B
The obvious issue here is that if B is zero I get a divide by zero error.
Is there a better (preferably mathematical) way to accomplish this without the complexity of conditional statements?
Backstory. I am working with students in a graphical robotics programming language called Lego EV3.
The algorithm above looks like this:
Using a conditional statement it looks like this:
Quite the waste of space, especially when you are working on 13" laptop screens. And confusing.
Just to turn #MBo's comment into an official answer, note that many languages have a function called sign(x) or signum(x) that returns -1, 0, or 1 if x is negative, zero, or positive respectively, and another function abs(x) (for absolute value) that can be used together to achieve your purpose:
A = abs(A) * sign(B)
will copy the sign from B to A if B ≠ 0. If B == 0 you will have to do something extra.
Many languages (C++, Java, python) also have a straightforward copysign(x, y) function that does exactly what you want, returning x modified to have y's sign.
In many programming languages, a simple if statement would work:
A = 10;
if (B < 0) {
A = -1*A;
}
If your language supports ternary expressions, we could reduce the above to a single line:
A = B < 0 ? -1*A : A;
Another option might be to define a helper function:
reverseSign(A, B) {
if (B < 0) {
return -1*A;
}
else {
return A;
}
}
C99 has the (POSIX) function copysign that does just this. Fortran has had this for ages. It's also a IEEE 754 recommended function

How find all strings i can create with 3 char

I have 3 char "abc".
All combinations with these 3 characters are 3^3 = 27:
aaa, aab, aac, aba, ... etc.
I write a pseudo-code to print all of these combinations:
string dictionary[3] = {"a", "b", "c"};
string str[3];
for (i=0;i<3;++i) {
str[0]=dictionary[i];
for (j=0;j<3;++j) {
str[1]=dictionary[j];
for(k=0;k<3;++k) {
str[2]=dictionary[k];
println(str);
}
}
}
Now, I can see that all loops start at 0 and end at 2.
So I thought there was a way to make this function as a recursive function, although in fact no basic step can be distinguished.
So, i asked myself:
Is it really possible to create a recursive function for this type of problem?
If it existed, would it be more or less efficient than the iterative method?
If the number of usable chars would increase, performance would be worse or better?

What does this recursive function do?

I got this question in an interview. So, this seems to me a messed up Fibonacci seq. sum generator and this gives a stackoverflow. Because if(n==0) should be if(n<3) (exit condition is wrong). What should be the precise answer to this question? What was expected as an answer?
foo (int n) {
if (n == 0) return 1;
return foo(n-1) + foo(n-2);
}
UPDATE
What does this recursive function do?
What do you infer when you see these 3 lines of code. No debugging.
Yes, it's just a recursive Fibonacci method with an incorrect base case (although I don't think I'd use n < 3 either... it depends on how you define it).
As for "what was expected as an answer" - that would depend on the question. Were you asked exactly the question in the title of your post? If so, the answer is "it recurses forever until it blows up the stack when you pass it any value other than 0" - with an explanation, of course. (It will never end because either n-1 isn't 0, or n-2 isn't 0, or both.)
EDIT: The above answers the first question. To answer "What do you infer when you see these 3 lines of code" - I would infer that the developer in question has never run the code with a value other than 0, or doesn't care about whether or not the code works.
The problem with the code posted is that if we evaluate foo(1) we need to find foo(0) and foo (-1), foo(-1) then needs to find foo(-2) and foo(-3) and so on. This will keep putting more calls to foo() until there is no more space in the memory resulting in a stack overflow. How many calls to foo are made will depend on the size of the call stack, which will be implementation specific.
When I see these lines of code I immediately get the impression that whoever wrote it hasn't thought about all the possible inputs that could be fed to the function.
To make a recursive Fibonacci function that doesn't fail for foo(1) or a negative input we get:
foo (int n) {
if( n < 0 ) return 0;
if (n == 0) return 1;
return foo(n-1) + foo(n-2);
}
Edit: perhaps the return for a negative number should be something else, as the fibonacci sequence isn't implicitly defined for negative indexes.
However if we use the extension that fib(-n) = (-1)^(n+1) fib(n) we could get the following code:
int fib(int n) {
if( n == -1){
return 1;
}else if ( n < 0 ){
return ( (-1)^(-n+1 ) * fib(-n) );
}else if (n == 0){
return 1;
}else{
return fib(n-1) + fib(n-2);
}
}
suppose, you call foo ( 1 ), it will have two sub calls of foo(0) and foo(-1). As you can see, once you get to foo(-1), n will decrease indefinitely and will never reach a terminating condition.
The precise answer would be:
foo (int n) {
if (n <= 1) return 1; // assuming 0th and 1st fib is 1
return foo(n-1) + foo(n-2);
}
Its a recursive fibonacci function with 0th element being 1.
Ignoring the incorrect termination condition, the code is the "naive" recursive implementation of the Fibonacci function. It has very poor big-O time complexity. It would work fine for small n, but if n is greater than say 50 (I'm just guessing that number), then it would take "forever" to run.

What are block expressions actually good for?

I just solved the first problem from Project Euler in JavaFX for the fun of it and wondered what block expressions are actually good for? Why are they superior to functions? Is it the because of the narrowed scope? Less to write? Performance?
Here's the Euler example. I used a block here but I don't know if it actually makes sense
// sums up all number from low to high exclusive which are divisible by a or b
function sumDivisibleBy(a: Integer, b: Integer, high: Integer) {
def low = if (a <= b) a else b;
def sum = {
var result = 0;
for (i in [low .. <high] where i mod a == 0 or i mod b == 0) {
result += i
}
result
}
}
Does a block make sense here?
Well, no, not really, it looks like extra complexity with no real benefit. Try removing the sum variable and the block and you will see that the code still works the same.
In general block expressions can be useful when you want to create an anonymous scope rather than factoring the code into a function, most of the time you should rather create a function.

Base case in a recursive method

A theoretical question here about the base or halting case in a recursive method, what's its standards?
I mean, is it normal not to have body in it, just a return statement?
Is it always like the following:
if (input operation value)
return sth;
Do you have different thoughts about it?
The pattern for recursive functions is that they look something like this:
f( value )
if ( test value )
return value
else
return f( simplify value )
I don't think you can say much more than that about general cases.
The base case is to terminate the loop (avoid becoming an infinite recursion). There's no standard in the base case, any input that is simple enough to be solved exactly can be chosen as one.
For example, this is perfectly valid:
int factorial (int n) {
if (n <= 5) {
// Not just a return statement
int x = 1;
while (n > 0) {
x *= n;
-- n;
}
return x;
} else {
return n * factorial(n-1);
}
}
In some cases, your base case is
return literal
In some cases, your base case is not simply "return a literal".
There cannot be a "standard" -- it depends on your function.
The "Syracuse Function" http://en.wikipedia.org/wiki/Collatz_conjecture for example,
doesn't have a trivial base case or a trivial literal value.
"Do you have different thoughts about it??" Isn't really a sensible question.
The recursion has to terminate, that's all. A trivial tail recursion may have a "base case" that returns a literal, or it may be a calculation. A more complex recursion may not have a trivial "base case".
It depends entirely on the particular recursive function. In general, it can't be an empty return; statement, though - for any recursive function that returns a value, the base case should also return a value of that type, since func(base) is also a perfectly valid call. For example, a recursive factorial function would return a 1 as the base value.

Resources