How to calculate average of an array for only entered values - java

I'm trying to calculate the average of an array for only the values that aren't 0. My array is of size 15, because it could have up to 15 values in it.
When I calculate the average, it uses all 15 values, even though 12 of them are 0 at the start. How do I prevent 0.0’s from being considered?
for(double element: majorA) {
Sum += element;
}
average = sum / majorA.length;
System.out.printf("%.5f\n", average);
The array also isn't a defined set, but dependent on what the user inputs. The initial array is:
double[] majorA = new double[15];
Then gets values as need:
majorA[0] = num1;
majorA[1] = num2;
...

I would just add a counter that keeps track and use that instead of the array length.
int count = 0;
for(double element: majorA) {
if(element > 0.0) {
Sum += element;
count += 1;
}
}
average = sum / count;
System.out.printf("%.5f\n", average);

You can do it in one line with
Arrays.stream(majorA).filter(d -> d != 0).average().orElse(0)
this will filter out all values that are 0s and will calculate the average. Even if there is nothing left in the array will display 0 because of .orElse(0)

you can use a counter in the loop that increments only if the number !=0
int count = 0;
for(double element: majorA) {
if(element != 0.0){
sum += element;
count++;
}
}
average = (count == 0) ? 0 : sum / count;

Related

Finding the minimum sum and maximum sum of a list of integers in an array

I am currently working on a HackerRank practice question and I only pass 5 test cases and I have no idea why. I've thought of all edge cases that I can think of myself but I fail most test cases.
Problem:
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
Example -
The minimum sum is 1 + 3 + 5 + 7 = 16 and the maximum sum is 3 + 5 + 7 + 9 = 24. The function prints
16 24
This is my solution so far:
public static void miniMaxSum(List<Integer> arr) {
// Write your code here
Collections.sort(arr);
int max = 0;
int min = 0;
int sum = 0;
int smallest = arr.get(0);
int largest = arr.get(4);
for (int i=0; i<arr.size(); i++) {
sum += arr.get(i);
}
min = sum - largest;
max = sum - smallest;
System.out.print(min+ " " + max);
}
I have no idea what test cases I'm failing since it doesn't tell me. I've tried arrays with duplicates, massive numbers, unsorted, and it all gives me expected answer. Please help!
Use long datatype because there is possibility of Integer overflowing or use 16 bit Integer.
public static void miniMaxSum(List<Integer> arr) {
// Write your code here
Collections.sort(arr);
long max = 0;
long min = 0;
long sum = 0;
long smallest = arr.get(0);
long largest = arr.get(4);
for (int i=0; i<arr.size(); i++) {
sum += arr.get(i);
}
min = sum - largest;
max = sum - smallest;
System.out.print(min+ " " + max);
}
}

Java - Finding the average of an array while excluding a particular value.

I am trying to calculate and return the average of an array of integer values. The problem is, the array I am calculating the average from has values I need to find the average of, and values I need to exclude.
For example, take this as being my data set in the array.
20, -999, -10, 50, -999, 40, 30
I need to find the average but exclude any -999 value from the calculation.
How can I go about removing the -999 value from my sums and then find the new value to divide by at the end? Is there a way to keep count of the values I exclude? How can I exclude a value and move on to the next?
public static double averageTemperature(int[] temperatures)
{
double sum = 0.0;
double avg = 0.0;
for (int i =0; i < temperatures.length; i++)
{
if (i == -999)
{
// what technique is there to exlude and keep counting?
}
else
{
sum += i;
}
}
avg = sum / temperatures.length;
return avg;
}
This should be pretty straightforward - just use a variable as counter for the "valid" entries. You also need to access the values in the array properly. Here's a proposal (untested), which assumes "valid" entries are those not equal t0 -999 (modify the condition as you like):
public static double averageTemperature(int[] temperatures)
{
double sum = 0.0;
double avg = 0.0;
int validEntries = 0;
for (int i =0; i < temperatures.length; i++)
{
// process only "valid" entries
if (temperatures[i] != -999)
{
sum += temperatures[i];
++validEntries;
}
}
avg = sum / validEntries;
return avg;
}
Using Java 8 you can do;
temperatures = Arrays.stream(temperatures).filter(x -> x != -999).toArray();
You can exclude any array value this way using predicate statements.
Calculating the mean is as simple as just looping the array and dividing by the length then.
float mean;
for (int i = 0; i < temperatures.length; ++i) {
mean += (float) temperatures[i];
}
mean /= (float) temperatures.length;
Note to use a float for the mean and cast your integer array values to float also to avoid integer division, as well as the length of the array.
suppose you are correct with the logic but you are not getting the sum of the temperature values.
public static double averageTemperature(int[] temperatures)
{
double sum = 0.0;
double avg = 0.0;
for (int i =0; i < temperatures.length; i++)
{
if (temperatures[i] == -999)
{
continue;
}
else
{
sum += temperatures[i];
}
}
avg = sum / temperatures.length;
return avg;
}
hope this is what you are looking for.
The easiest way to compute the average while filtering out any unwanted values would be:
double average = Arrays.stream(temperatures)
.filter(i -> i != -999)
.average();

Java will not add first integer when computing average

I am new to Java, so I apologize if I am simply overlooking something simple. I wrote this code to make a few simple calculations, but when I run it, Java does not seem to be adding my first integer that is input when calculating the average. Everything else seems to be fine, so I would appreciate any help. Thanks.
import java.util.Scanner;
public class IntegerCalc {
public static void main(String[] args){
System.out.println("Enter a list of non-negative integers.");
System.out.println("Enter a negative number to indicate the end of your input.");
Scanner keyboard = new Scanner(System.in);
int min = keyboard.nextInt();
int max = min;
double average = 0;
double numberOfInt= 1;
int next = keyboard.nextInt();
double total = 0;
while (next > 0){
if (next > max)
max = next;
else if (next < min)
min = next;
total = total + next;
numberOfInt++;
next = keyboard.nextInt();
}
average = total/numberOfInt;
System.out.println("The largest integer is " + max);
System.out.println("The smallest integer is " + min);
System.out.println("The average is " + average);
}
}
It looks like your code does sum all the input numbers, but your numberOfInt is off by one.
You should initialize it to
double numberOfInt= 0;
instead of
double numberOfInt= 1;
You only want to increment numberOfInt when you add the current value of next to the total, so the first time you add next to total, numberOfInt should become 1.
What I can see is that inside while loop you have this condition:
if (next > max)
max = next;
else if (next < min)
min = next;
Your first value never goes to total.Your first value will count towards average is only when value of next is equal to first value.To solve this problem you can initialize total with max or min(since they are equal initially):
double total = (double) max;
your int numberOfInt should not be initialized at value 1. Since you increment it by 1 with each iteration of your loop, it's value is off by one. Instead, initialize it at value 0.

Java, can't find average of an array

I need to write a program that finds an average of all values in the array and then returns ones larger than the average.
import java.util.*;
public class AboveAverage {
public static void main(String args[]) throws Exception {
Scanner kbd = new Scanner(System.in);
int count=0, num;
int nums[] = new int[1000];
double sum = 0;
double average = 0;
System.out.println("Input +ve integers, to stop type 0");
num = kbd.nextInt();
while( num > 0 ) {
nums[count] = num;
count = count + 1;
num = kbd.nextInt();
}
int d = 0;
while ( d < 1000 ) {
sum += nums[d];
d++;
average = sum / nums[d];
}
for(int i=0; i < count ; i=i+1) {
System.out.print(nums[i] + " ");
}
System.out.println(average);
}
}
In my opinion problem is in this line
I tried the one below which gives an exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000
at AboveAvarage.main(AboveAvarage.java:23)
average = sum / nums[d];
I also tried
average = sum / nums.length;
Which gave me the sum instead of the average.
Remember that array indices in Java go from zero? This means the allowed indices in your nums array are 0 through 999.
Now look at this loop:
int d = 0;
while ( d < 1000 ) {
sum += nums[d];
d++;
average = sum / nums[d];
}
First, it adds the current number to the sum. This is correct.
Then, it increments the number.
Then it uses the incremented number to access nums[d] to calculate the average.
Now, imagine that you are at the last round. d is 999.
First, it adds the current number to the sum.
Then it increments d. Now it is 1000.
Then it uses the incremented number to access nums[d]. But this means nums[1000]. And that's an illegal index.
So this explains why you have an ArrayIndexOutOfBoundsException. You should never use the index again after you incremented it, because the while only guaranteed that its previous value was less than 1000. If you change the value, you need to test again. This is why normally the increment step is the last in the loop.
As for your logic:
To calculate an average, you first need to know the sum. After you know the sum, you can divide by the number of items you are averaging. So you need to divide the sum by the number of items you read.
So:
You should not do a loop up to 1000. If you entered 0 after 5 numbers when you inputted the data, then there will be no values in the rest of the array (or rather, there will be zeros there).
You can calculate the sum, as another answer told you, in the first loop. No need to do that in the second loop.
You don't calculate the sum and the average in the same step. You first have to complete calculating the sum (finish the loop, be it the first or the second), and only then you can divide by the number of items (which you saved in count).
Then you have to go through another loop, that prints the numbers that are larger than the average. Your print loop prints all the numbers. You should check each number, see if it is greater than the average you calculated, and only if it is, print it.
Hint: there should really only be two loops: One that reads the numbers and calculates the count and the sum. Then you calculate the average, but that's not a repeating action, so it should not be in a loop. The second loop is for printing the numbers that are above average.
In the while loop that is gathering values, you are using count to track how many values are provided.
In the subsequent loop to calculate the average, you should only look at count items of the array:
int d = 0;
while(d<count) {
sum += nums[d];
}
average = sum/count;
Note you don't need to calculate average within the loop - do it once you've summed the values.
You don't need the other while loop, add up sum upon input. When done, just divide by count
while( num > 0 ) {
nums[count] = num;
count = count + 1;
sum += num;
num = kbd.nextInt();
}
average = sum / count;

How can I divide a range into n equal bins?

I have a range [min-max]. min and max are of type double. I want to divide this interval into n equal intervals.(n is an integer). How can I achieve this in Java?
For example :
say I have a range [10-50]. and n=4 .
output should be a list of ranges like [10-20] [20-30][30-40] [40-50]
So what you need here is a formula for the limits of the smaller ranges. First lets start off by computing the length of each small range:
// let range be [start, end]
// let the number of smaller ranges be n
double total_length = end - start;
double subrange_length = total_length/n;
After that do a simple cycle for the smaller ranges moving the left end of the current range with the value computed above on each step:
double current_start = start;
for (int i = 0; i < n; ++i) {
System.out.printl("Smaller range: [" + current_start + ", " + (current_start + subrange_length) + "]");
current_start += subrange_length;
}
If have the Range given in the form of an array with two elements (min and max)
double[] range = new double[] {min, max};
int n = 4;
you could try it this way. What you get from divideRange is a two-dimensional array with subranges of the given range, with each of them having the wanted length.
public double[][] divideRange(double[] range, n) {
double[][] ranges = new double[n][2];
double length = (range[1] - range[0])/n;
ranges[0][0] = range[0];
ranges[0][1] = range[0]+length;
for(int i = 1; i < n; i++) {
ranges[i][0] = ranges[i-1][1];
ranges[i][1] = ranges[i-1][1]+length;
}
return ranges;
}
What you can do is use what #Achintya used, double dist = (double)(max-min)/n; Then starting from the min, add dist to it and that is the max of your first interval.
So it'd be something like:
[min, min + dist], [min + dist, min + 2*dist]... until min + n*dist >= max.
int counter = 0;
while(true) {
CreateInterval(min + counter*dist, min + (counter+1)*dist);
if (min+(counter+1)*dist >= max) {
//if we have reached the max, we are done
break;
}
}

Categories