Click to See Complete Forum and Search --> : Finding a sub-array that sums to y


yackles
January 24th, 2008, 01:23 PM
I am doing my taxes and have a long list of fractional shares sold as a result of dividend reinvestment. In order to reconcile the sale transactions, I need to be able to assemble the fractional purchases on reinvestment with the sales. Given the volume of reinvestments, and share fractions out to four decimals, this is not trivial to do by hand. The problem simplifies to the below:

Is there a simple script (perl, python, awk, VB) to identify all elements, if any, of an array that sum to a target number?

Specifically,

Inputs:

1. arbitrarily long comma-delimited list of real numbers, x1 .. xn
2. target number, y (can be last element of input list)

Output: all sub-arrays adding to y or "NULL" if none

E.g., with y last element of input list

Input:

1, 2, 3, 4, 5, 6, 7, 8, 9, 7

Output:

7
1, 6
2, 5
3, 4
1, 2, 4

Cheers,

Mike

code_carnage
January 25th, 2008, 05:12 AM
1, 2, 3, 4, 5, 6, 7, 8, 9, 7

If y = 7 there are only two subarray..
Your output should be .
3,4
7

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 7}
int size = 10;
for(int i =0; i<size; i++)
{
int sum =0;
for(int j = i;j<size;j++)
{
sum+= arr[j];
if(sum == y) //bingo you found one
print(i,j);
if(sum >y)
break;
}
}
void print(int i, int j)
{
while( i <= j )
cout<<arr[i];
}
complexity n-square.

I think it should work..Havent tested though
good luck.

yackles
January 25th, 2008, 01:13 PM
I realize now that I have misused the term subarray. Subsets is what I meant, so that any and all elements summing to the target are listed.

That said, the code you've provided gives me a start, so many thanks.