An array gets filled up with random elements (negative and positive). Now I want to calculate the sum of ONLY the positive elements.
I开发者_运维问答terative there is no problem, but in the recursion version I can only get the sum of both negative and positive.
How can I "check" in the recursive version that it only sums up the positive elements?
Iterative version:
public int IterSomPosElem(int[] tabel, int n)
{
n = 0;
for (int i = 0; i < tabel.Length; i++)
{
if (tabel[i] >= 0)
{
n += tabel[i];
}
}
return n;
}
Recursive version at the moment (sums up all the elements instead of only the positive):
public int RecuSomPosElem(int[] tabel, int n)
{
if(n == 1)
return tabel[0]; //stopCriterium
else
{
return (tabel[n - 1] + RecuSomPosElem(tabel, n - 1)); // how to check, so it only sums up the postive elements and "ignores" the negative elements.
}
}
Is this homework? Why do you need to do this with a recursive function?
In the real world, it would be some simple LINQ
int positiveSum = tabel.Where(i => i > 0).Sum();
How about
int foo[] = new [] {1, -9, 10, 8, -16, ...};
int sumOfPostiveInts = foo.Sum(x => x < 0 ? 0 : x);
or...foo.Where(x => x > 0).Sum();
Something like?
public int RecuSomPosElem(int[] tabel, int n)
{
if(n == 1)
return tabel[0]; //stopCriterium
else
{
var valueToSum = tabel[n - 1] > 0 ? tabel[n - 1] : 0;
return (valueToSum + RecuSomPosElem(tabel, n - 1));
}
}
public int RecuSomPosElem(int[] tabel, int n)
{
if(n == 1)
return tabel[0]; //stopCriterium
else
{
if (tabel[n - 1] > 0)
return (tabel[n - 1] + RecuSomPosElem(tabel, n - 1));
else
return RecuSomPosElem(tabel, n - 1));
}
}
You're so close! Using your algorithm, but just adding a check to see if the current value in table is negative or not. If it is negative move on to the next array item:
private static int RecuSomPosElem(int[] tabel, int n)
{
int i = n - 1;
while (tabel[i] < 0 && i > 0)
i--;
if (i == 0)
{
return 0; //stopCriterium
}
else
{
return (tabel[i] + RecuSomPosElem(tabel, i));
}
}
Use this:
public int Rsum(int[] data, int currentIndex, int LastIndex)
{
if(currentIndex < LastIndex)
{
if (data[currentIndex] > 0)
{
return (data[currentIndex] + Rsum(data, ++currentIndex, LastIndex));
}
else
{
return Rsum(data, ++currentIndex, LastIndex);
}
}
return 0;
}
See if it solves:
public int sumPositiveNumbersR(int[] v, int n){
int sum;
if(n < 0) return 0; //stopCriterium
else{
if(v[n] > 0){
sum = v[n] + sumPositiveNumbersR(v, n-1); //scrolls the vector and sum
return sum;
}else
return sumPositiveNumbersR(v, n-1); //scrolls the vector
}
精彩评论