Hellow there programmers I am facing a issue
#include<iostream>
using namespace std;
bool Check(int arr[], int size, int con)
{
for (int i = 0; i < size; i++)
{
if (arr[i] == con)
{
return true;
}
for (int j = i+1; j < size;j++)
{
if (arr[i]+arr[j] == con)
{
return true;
}
for (int k = j + 1; k < size; k++)
{
if (arr[i] + arr[j] + arr[k] == con)
{
return true;
}
for (int l = k + 1; l < size;l++)
{
if (arr[i] + arr[j] + arr[k] + arr[l] == con)
{
return true;
}
}
}
}
}
}
int main()
{
int size;
int con;
cout << "Enter desire size of array" << endl;
cin >> size;
cout << "ENter number" << endl;
cin >> con;
int *arr = new int[size];
for (int i = 0; i < size; i++)
{
cin >> *(arr + i);
}
if (Check(arr, size, con) == true)
{
cout << "YESSS!!";
}
else
{
cout << "NOOO!!";
}
}
I have to make subsets of an array and add them individually({1,2} = 1+2) if i get the result match with user input(con) output will be YES or NO. now the problem I am facing is I dont know how much size will user input give if he/she puts size of array is 4, 4 loops will be needed. Is thr any one my subset program works on every size of array p.s: sorry for my bad english
Here's a simple example of a recursive implementation of your function:
bool Check(int *arr, int size, int con, int curr_sum = 0)
{
for (int i = 0; i < size; i++)
{
int new_sum = curr_sum + arr[i];
if (new_sum == con
|| Check(arr + i, size - i, con, new_sum))
{
return true;
}
}
return false;
}
Here's how it works...
We pass around a curr_sum
parameter that holds the sum from the parent recursion. The current recursion will go through adding all of its indexes to it, looking for curr_sum + arr[i] == con
. If it doesn't, then we'll take the new sum (curr_sum + arr[i]
) and put it through another round of recursion starting on the index after the one we're currently looking at.
BEWARE: this is an O(n^2) implementation that you're working with, so it'll be extremely slow (and since this is recursion, liable to stack overflow) as you deal with larger sized arrays.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments