// 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);
}
I have a function that will return the number of subsets that add up to 0.
I am given this solution, but I don't understand why it actually works.
int countZeroSumSubsets(Vector<int> &v, int index, int sumSoFar) {
if (index == v.size()) {
return (sumSoFar == 0);
} else {
return countZeroSumSubsets(v, index + 1, sumSoFar + v[index])
+ countZeroSumSubsets(v, index + 1, sumSoFar);
}
}
I get that it is going through a general inclusion / exclusion pattern, and for each integer in the vector, it is deciding whether to include, or exclude this integer in the subset. The base case being the end of this vector, and will return whether the sum of that subset is equal to 0 or not.
What I don't understand, is how does the function actually keep track of the number of times the base case returned true (i.e. number of subsets that sum to zero), since it just returns a bool.
To try and understand it further, I coded up my own solution (below) but I still don't quite understand it.
int countZeroSumLeonard(Vector<int> &v, int index, int sumSoFar, int& count) {
// Base case, index = size
if (index == v.size()) {
if (sumSoFar == 0) {
count++;
}
} else {
// include that number in our sum
countZeroSumLeonard(v, index + 1, sumSoFar + v[index], count);
// exclude that number from our sum
countZeroSumLeonard(v, index + 1, sumSoFar, count);
}
return count;
}
Here is my test divide and conquer program, but it gives me an error. I am heading in the right direction?
public class getSum {
static int sum = 0;
public static void main(String[] args) {
int[] numbers = {2,2,2,2,2,2,2,2};
int amount = 0;
amount = sumArray(0,numbers.length,numbers);
System.out.print(amount);
}
public static int sumArray(int first, int last, int[] A){
int index = last - first;
if(index == 1){
return sum;
}else if(index <= 4 && index > 1){
for(int i = first; first < last; i++){
sum += A[i];
}
return sum;
}
return (sumArray(first, last / 2, A) + sumArray(last / 2, A.length, A));
}
}
Here is the error
Exception in thread "main" java.lang.StackOverflowError
at getSum.sumArray(getSum.java:16)
I am looking for a simple example of taking an array of 16 and breaking it down to base case 4. I am having trouble completely understanding how to spit the array, then split it again. then combine all the splits in the end.
You can use recursion for divide and conquer. You keep recursing on smaller arrays until you find a match, then climb up the recusion tree.
For example: find if a number is in the array using the recursive function isIn(Number x, Array a)
Boolean isIn(Number x, Array a) {
n = a.size
if n==1 then return a[0]==x
else
return isIn(x, a[0:n/2]) or isIn(x,a[n/2:n])
}
You can see how the problem is split into two smaller problems, and so on, until it reaches the stop condition 'n==1' then it starts returning results up the call tree.
This is pseudo code, you will have to adapt the concept to the programming language you are using
Having trouble completely understanding how to spit the array, then split it again.
Using Recursion you can do that.
I am working on solving a mathematical problem.
What I am trying to do is to have an if statement that compares variable n to a set of variables i 1 through 10. Is there any way to do it in c++?
here is what I am trying to do:
int smallPos(int n){
if (n%for(int i=1;i<=10;i++)==0) {
return n;
}
This is obviously wrong but is any way to get around it?
It looks like you're trying to do this:
int smallPos(int n)
{
return (n % 232792560 == 0) ? n : <sentinel value>; // sentinel_value is the value return if n does not meet requirements
//232792560 is the first number for which n % a: a ∈ {1,2,3...10} This is faster than checking each of these values.
}
What you want to do is this:
int smallPos(int n)
{
for (int i = 1; i <= 10; ++i)
{
if (n % i != 0) // check if n % i == 0, if not, then we shouldn't return n.
{
return -1; // or whatever you want to return when not ALL the remainders are 0.
}
}
return n; // If we get here then all the remainders were 0s.
}
#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.