Why is my recursiveMinimum function not working? - c++

#include <iostream>
using namespace std;
int recursiveMinimum(int [], int n);
int main ()
{
int theArray[3] = {1,2,3};
cout << recursiveMinimum(theArray, 0);
cout << endl;
return 0;
}
// pass in array and 0 to indicate first element
// returns smallest number in an array
int recursiveMinimum (int anArray[], int n) // nth element is smallest element in anArray
{
while (anArray[n+1] != NULL)
{
int smallest = n;
if (anArray[n+1] <= anArray[n])
smallest = n + 1;
//if last element has not been reached
return recursiveMinimum(anArray, smallest);
}
}
My function exits, but it doesn't return anything. I tried to set the base case to when the outside of the array is reached. The return 0 line in main is reached so I'm pretty sure the base case in my function is being reached.
Here is the working function:
#include <iostream>
using namespace std;
int recursiveMinimum(int a[],int min,int index,int size);
int main()
{
int a[6] = {8, 2, 55, 3, 11, 9};
cout << recursiveMinimum(a,a[0],1,6) << endl;
return 0;
}
// pass in the array, the first element,
// 1 to indicate 2nd element, and the number of elements
int recursiveMinimum(int a[],int min,int i,int size)
{
if(i == size )
return min;
else if(i < size)
{
if(a[i] < min)
recursiveMinimum(a,a[i], i + 1, size);
else
recursiveMinimum(a,min, i + 1, size);
}
}
Thank you to everyone who helped. Due to time constraints I sent out a SOS (Stack Overflow distress Signal), however next time I will definitely step through the debugger prior to asking a question.

Have you stepped through this in a debugger? It should become fairly obvious when you do.

You are recursing within the while loop:
while( condition )
recursive call
while( condition )
recursive call
.
.
.
Instead what you probably were thinking was
if( condition )
recursive call
recursive call
recursive call
you see? Get rid of the while and replace it with an "if" statement.

You need to have an end case with a recursive function.
At the moment, your function always returns itself. This will recurse until the stack runs out. You need to have a check that says "I'm done", which will return a value rather than the result of another function call.

Because your while loop never terminates. Why are you sure anArray[n+1] will ever be NULL?

You never break your recursion. Actually I wonder that this compiles as your function doesn't even have a defined return value in case it reaches the end. Also using while there seems unnecessary as the function execution stops after the return anyway.

Instead of
int recursiveMinimum(int array[], int n);
I think that recursiveMinimum should be defined as
int recursiveMinimum(int array[], int index, int length);
with the intention that recursiveMinimum will return the minimum value in array between indexes index and length (i.e., min array[i] where i in [index, length)). Of course, you want to define this recursively. So then I would note that the minimum value in array between indexes index and length is
min(array[index], recursiveMinimum(array, index + 1, length));
Of course, there are boundary cases (such as when index = length - 1). In this case you would just return array[index] as the minimum.
Hope this helps. Let me know if this does not make sense.

You're misunderstanding the point of a recursive function. If a certain condition is true, then you return the result of a call to the recursive function, otherwise you return some other value. For example, here is a recursive definition of the factorial function (e.g. 5!, or "5 factorial", is 5*4*3*2*1, which is 125):
int
factorial (int n)
{
if (n == 1)
return n;
return (n * factorial (n - 1));
}
How it works:
If n is 1, then return 1 since 1! is 1.
Otherwise, return n multiplied by one less than n.
For example, if n is 5, then the return value is the result of the expression 5 * factorial (5 - 1), which is the same as 5 * factorial (4). Of course, the same thing happens again since it's a recursive function and 4 is not 1. So you end up with 5 * factorial (4), which is the same as 5 * (4 * factorial (4 - 1)), or 5 * (4 * factorial (3)).
You should be able to see the pattern now and how the factorial function works. Your recursiveMinimum function should adhere to the same general idea -- if something is true (or not true), return the result of a call the function (possibly with some additional things like the value n inside the factorial function needs to be multiplied by the result of the factorial function), else return a certain value and code the function to handle it appropriately. In other words, you need a "final" exit condition, such as the n == 1 condition in the factorial function above.
Good luck!

int recursiveMinimum(int a[],int min,int index,int size)
{
if(index == size )
return min;
else if(i < size)
{
if(a[i] < min)
recursiveMinimum(a,a[i],++index,size);
else
recursiveMinimum(a,min,++index,size);
}
}
int main()
{
int a[] = {1,2,3,0,-4};
int min = recursiveMinimum(a,a[0],1,5));
return 0;
}
When you use recursion make sure that you must put some exit condition to end it ,otherwise you will have in infinite recursion and you program will hang.
I think finding minimum is more efficient,easy and simple using iteration rather than recursion.

Related

Could you please explain me the the working of following code?

// This is a function to check if the given array is sorted or not by recurssion
#include<iostream>
using namespace std;
bool sorted(int arr[],int n)
{
if(n==1)
{
return true;
}
I am cofused here when n will reach 1 then it will return true to "restArray" after that if array is not sorted then how will "restArray" become false?
bool restArray = sorted(arr+1, n-1);
return (arr[0]<=arr[1] && restArray);
}
int main()
{
int arr[]={1,6,3,4,5};
cout<<sorted(arr,5);
return 0;
}
As in every recursion there are two cases
First the trivial case if (n == 1): An array of size 1 (ie only a single element) is always sorted. Thus it returns true and stops the recursion
And if n is still greater than 1, you do the recursive call and check if the array without the first element is sorted (bool restArray = sorted(arr+1, n-1)), then you check if the first element of the array is less than the second element (a[0] < a[1]). (btw I'd probably check for <= here) And finally you combine those two checks with &&.
So for your example, it will at some point in time check 6 < 3, which will return false thus the overall result will become false.
But for sake of optimization, I'd suggest to reorder your statements a bit, such that you won't need the recursive call, if the order of the first two elements in the array is already wrong. And as #Scheff's Cat mentioned in the comments: When you convert it to a tail recursion, any decdent compiler will be able to refactor that recursion into a (much cheaper) iteration ...
And I'd also check for n <= 1 otherwise you might end up in an infinite recursion if you method is (wrongly!) called with n = 0.
bool sorted(int arr[],int n)
{
if (n <= 1)
{
return true;
}
return arr[0] <= arr[1] && sorted(arr+1, n-1);
}
or even simpler
bool sorted(int arr[], int n) {
return n <= 1
? true
: arr[0] <= arr[1] && sorted(arr+1, n-1);
}

how can i return the index of an integer in an array using a recursive function?

i have to find the index of an integer in an array using a recursive function this is what i have up to now:
#include <iostream>
int linear_search(int array[], int choice_, int size) {
if (array[choice_] >= 0) {
return array[choice_];
}
else {
return -1;
}
}
for example if the:
int array[]= {3,4,7,8};
if i type that i want to search for number 3 it should give me the index of 0 but instead it gives me the number 8. can i get some advise please?
Recursion is about narrowing down a problem to a smaller problem.
In the case of this particular search, try to think of it in terms of the found-item being either in the first position in the array, or maybe in the remainder of the array. This then reduces the problem to searching a smaller array, until you either find the item or you hit the trivial case of an empty array.
int linear_search(int array[], int choice_, int size)
{
// Array is empty -- not found
if (size <= 0)
return -1;
// Found at position 0
if (array[0] == choice_)
return 0;
// TODO: Search position in remaining array
int pos = linear_search(/* USE BRAIN HERE */);
// TODO: You may want to do something to the result before returning it
return pos;
}
As you can see, I've left some parts for you to fill in. I have faith in you. You can do it!
Happy coding!
This is binary search. It is a recursive function.
int binary_search_recursive(const int b[], int search_key, int low, int high)
{
if (low > high)
return -1;
int mid = low + (high - low) / 2;
if (search_key == b[mid])
return mid;
else if (search_key < b[mid])
return binary_search_recursive(b, search_key, low, mid - 1);
else
return binary_search_recursive(b, search_key, mid + 1, high);
}
This code is wrong
if (array[choice_] >= 0) {
return array[choice_];
When you do array[choice_] you are looking at the array value at index choice_. That is not what you want. Instead you want to find out if the array at some index is equal to choice_. That would be if (array[some_index] == choice_) return some_index;
Further, to make this a recursive approach, the function needs to call itself. Your code doesn't do that so it's not recursive.
Here is a recursive approach:
int searchArray(const int* array, const int choice_, const int size)
{
if (size > 0)
{
if (array[size-1] == choice_) return size-1; // Hit! Return the index
return searchArray(array, choice_, size-1); // Recursive call - pretend array is 1 shorter
}
return -1;
}
The code looks at the last element in the array.
If it is a hit it simply returns the index.
If it is not a hit, it calls itself but decrements size to pretend that the array is one element shorter.
In this way it goes from the end of the array towards the start of the array while looking for choice_.
BTW: Notice that it's a very bad idea to use recursion for this task - never do that! Use a simple for loop. But I guess this is just another example of a very bad homework task...

Integer is set to -858990820 in program using a recursive algorithm - I kind of get it why, not sure though

My program should build a number (in the k parameter) which is obtained with each of the even digits in the a[] array. n is the number of elements of the array.
void F (int n, int a[], int &k) {
if (n == 0)
{
if (a[0] % 2 == 0)
{
k = a[0];
}
else
{
k = -1;
}
}
else
{
F(n - 1, a, k);
if (a[n] % 2 == 0)
{
k = k * 10 + a[n];
}
}
}
BTW I'm not that good at recursion. It might not be an okay algorithm. I'm trying to get better.
The problem is as follows: if I cout k, it shows me -858990820.
If I use a cout k in the else condition to see what's happening, the result is fine UNTIL some point it suddenly turns into that negative number.
[
I think that number appears because of the array. It goes out of bounds at some point but I don't get when.
Calling F(n-1, a, k) at the beginning of the else condition should have resolved this. (because the array stops at n-1 and if I call that in the else condition as the first thing in there it should not ever reach n).
Can you explain to me what's happening and help me fix it?
////edit:
I forgot to mention: if there is no even number, k equals -1.
You have a problem here:
else
{
F(n - 1, a, k);
if (a[n] % 2 == 0)
{
k = k * 10 + a[n];
}
}
If your initial call to this function is:
int a[10];
F(100, a, &k);
Then accessing a[n] is going to access a[10], which is beyond the allocated bounds of the array. Remember that in C, array indexes are 0 through n; in this case, 9 is the index of the last item.

Recursive coin change c++

My program seems to be crashing every time it recursive calling in the minimum function. Can anyone tell me why it is crashing. It would instantly freeze after i call the minimum function. Is it because im using a vector?
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
int minimum(vector<int> denom, int s, int N) //take in denomination , sizeofcoin, and value of N
{
if(N == 0)
{
return 1;
}
else if(N < 0 || (N > 0 && s <=0))
{
return 0;
}
else
{
return min(minimum(denom,s - 1, N), 1 + minimum(denom, s,N-denom[s-1]));
}
}
int main()
{
int N;
unsigned int sizeofcoin;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter the number of different denominations: " << endl;
cin >> sizeofcoin;
vector<int> denom(sizeofcoin);
for(unsigned int i= 0; i < sizeofcoin; i++)
{
cout << "Enter denomination #" << (i+1) << endl; //save all the denominations in an array
cin >> denom[i];
}
sort(denom.begin() , denom.end(),greater<int>()); //sort the array from largest to smallest
if(denom.back() != 1) //check the end of the array (since the back is smallest now) if it has 1
{
denom.push_back(1); //Will include 1 if the user does not input a 1 (doesn't have to be used)
}
minimum(denom,sizeofcoin,N);
return 0;
}
I tried to explain your minimum() function to your rubber duck, and your rubber duck has a question for you. Here's how our conversation went:
int minimum(vector<int> denom, int s, int N) //take in denomination , sizeofcoin, and value of N
{
if(N <= 0)
{
return 0;
}
Me: this minimum() recursive function immediately returns if its third parameter, N, is 0, or negative.
Your Rubber Duck: Ok.
return (minimum(denom,s - 1, N)...
(Here, I tried explaining your first recursion call here, to your rubber duck):
Me: So, this makes a recursive call, with the same parameters, except that the 2nd parameter is decremented. The third parameter is N.
Your Rubber Duck: So, if the third parameter's value, N, is unchanged, and the recursive function returns without recursing only when N is 0 or negative, and the initial call to minimum() passes a value greater than 0 for N, then when exactly do you expect this recursion to stop?
I couldn't answer this question myself, maybe you can explain this to your rubber duck, by yourself. When does recursion stop, here?
You have the recursive call minimum(denom,s - 1, N) so N will never be less than or equal to 0, and the recursion will never end.
This would have been very easy to find out if you learned how to use a debugger, and stepped through the code line by line, and stepped into the recursive calls.
Another thing that I want to point out is that you are trying to return the sum of two values:
(minimum(denom,s - 1, N) + minimum(denom, s,N-denom[s-1])
instead what you should do is:
min(minimum(denom,s - 1, N), 1 + minimum(denom, s,N-denom[s-1]))
The idea is that in first call you've not used any coin but in second call you have used one, so adding 1 for the same.
Look for a Dynamic Programming solution for the same.
https://people.cs.clemson.edu/~bcdean/dp_practice/

recursive function error: "stack overflow"

I wrote this function that supposed to find smallest positive integer that is divisible by every number 1 through 20. I get "stack overflow error", even though, when I test for numbers 1 through 10, it works just fine.
here is my code:
#include<iostream>
#include<cstdlib>
using namespace std;
// function prototype
int smallPos(int k, int m,int n);
int main(){
printf("the smallest positive number that is divisible by 1 through 20 is %d ", smallPos(1,1,13));
}
int smallPos(int k, int n, int m){
int div=0;
for(int i = n;i<=m;i++) {
if (k%i==0)
div++;
}
if (div==m) {
return k;
} else {
k+=1;
smallPos(k,n,m);
}
}
Why does it happen? The number shouldn't be that big anyway.
Thank you!
The final condition (div == m) will never be true. For div to become equal to m, the number k should be divisible by all of the numbers in range [n,m).
Edit: I've reread the text in the printf() call to understand what the function does. You're looking for the first number divisible by all numbers in the range. If my calculations are correct, this number should be the product of all unique prime factors of the numbers in the range. For the range [1,13] (as per the function call, not the text), this number should be:
30030 = 1 * 2 * 3 * 5 * 7 * 9 * 11 * 13
Now, this means you are going to invoke the function recursively over 30,000 times, which is obviously way too many times for the size of stack you're using (defaults are relatively small). For a range this size, you should really consider writing an iterative function instead.
Edit: here's an iterative version that seems to work.
int smallPos ( int n, int m )
{
int k = 0;
while ( ++k )
{
int count = 0;
for (int i = n; i<=m; i++)
{
if (k%i==0) {
++count;
}
}
if (count == (m-n+1)) {
return k;
}
}
return k;
}
Indeed, the result for smallPos(1,10), the result is 2520. It seems my previous estimate was a lower bound, not a fixed result.
Your smallPos function incurs undefined behaviour since it is not returning a value in all execution paths. You may want to say return smallPos(k,n,m); in the last part (or just return smallPos(k + 1, n, m); in one go).