Reputation: 123
I'm trying to calculate a positive average from an arraylist. It takes values from an arraylist but calculates only "positive" numbers, While testing
Integer[] array = new Integer[]{3, 2, -4, -7};
ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(array));
System.out.printf(averagePositive(arrayList));
I have tried using abs but it didn't work.
public static double averagePositive(ArrayList<Integer> values) {
if (values == null || values.isEmpty())
return 0.0;
int sum = 0;
int n = values.size();
for (int i = 0; i < n ; i++)
if (values.get(i) > 0.0) {
sum += values.get(i);
}
return ((double) sum) / n;
}
My desired output is 2.50 but getting 1.25
Upvotes: 1
Views: 1291
Reputation: 3600
Your n
is equal to the size of array. Instead it should have been count of the total positive number
public static void main(String[] args) {
Integer[] array = new Integer[] { 3, 2, -4, -7 };
ArrayList arrayList = new ArrayList(Arrays.asList(array));
System.out.println(averagePositive(arrayList));
}
public static double averagePositive(ArrayList<Integer> values) {
if (values == null || values.isEmpty())
return 0.0;
int sum = 0;
int n = 0;
for (int i = 0; i < values.size(); i++)
if (values.get(i) > 0.0) {
sum += values.get(i);
n++;
}
return ((double) sum) / n;
}
Upvotes: 1
Reputation: 3393
You should count how many positive values you have instead on dividing by the list size:
int positiveCount = 0;
for (int i = 0; i < n ; i++)
if (values.get(i) > 0.0) {
sum += values.get(i);
positiveCount++;
}
return ((double) sum) / positiveCount;
Or you can use Streams:
public static double averagePositive(List<Integer> values) {
return values.stream()
.filter(d -> d > 0.0)
.mapToDouble(Function.identity())
.average().orElse(0.0);
}
Upvotes: 0
Reputation: 506
You need to divide the sum with the number of positive elements, not the total size.
public static double averagePositive(ArrayList<Integer> values) {
if (values == null || values.isEmpty())
return 0.0;
int sum = 0;
int positive_n = 0;
for (int i = 0; i < n ; i++)
if (values.get(i) > 0.0) {
sum += values.get(i);
positive_n++;
}
return ((double) sum) / positive_n;
}
Upvotes: 0
Reputation: 3131
Your code is almost correct. The only part you're missing is that you want to take avg of positive elements, so total amount of elements should be 2 in your case. You should count only positive elements, like this:
int n = 0;
for (int i = 0; i < n ; i++)
if (values.get(i) > 0.0) {
sum += values.get(i);
n++;
}
This should do the trick.
Upvotes: 0
Reputation: 393801
You should count the positives and divide by that count, not by n
:
int count = 0;
for (int i = 0; i < n ; i++) {
if (values.get(i) > 0.0) {
sum += values.get(i);
count++;
}
}
if (count > 0) {
return ((double) sum) / count;
} else {
return 0;
}
Upvotes: 2