Find largest average set of results in array - java

I have a 2D array and I want to find the largest average set of results, so far I can calculate the average of each set of results but I'm not sure how to select the biggest from the output.
My code:
static int[][] studentMarksArray = new int[10][3];
for(int i=0;i<10;i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
System.out.println(total);
}
An attempted solution:
for(int i=0;i<10;i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
double newTotal = total;
if(newTotal>total){
newTotal = total;
System.out.println(newTotal);
}
}

Like this:
double max = 0;
for(int i = 0; i < 10; i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
max = Math.max(max, total);
}
or if you want the index:
int index = -1;
double max = 0;
for(int i = 0; i < 10; i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
if(Math.max(max, total) == total) {
index = i;
max = total;
}
}
Ok if you want to have an array of averages at the end, do this:
int index = -1;
double max = 0;
double [] averages = new double[10];
for(int i = 0; i < 10; i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
averages[i] = total;
if(Math.max(max, total) == total) {
index = i;
max = total;
}
}

add this after variable initialisation
int largest=0,lp=0;
add this before forloop ends but after calculating total
if(largest<total){
largest=total;lp=i;
}
at the end of forloop you will have largest average in the variable largest and its position in variable i.

You can save the outPut at every step in to a priority queue(which saves the elements in natural ordering) and in the last step the pull() the highest value from this priority queue.
import java.util.PriorityQueue;
public class Test1 {
public static void main(String[] arg){
int[][] studentMarksArray = new int[10][3];
PriorityQueue<Double> pq = new PriorityQueue<Double>();
for(int i=0;i<10;i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
System.out.println(total);
pq.add(total);
}
System.out.println(pq.poll());;
}
}

Related

Trying to get the average for each element in a two dimensional array

I have a program where i have to find the average for each student score from a text file and display it as a 2D array.
I am stuck - all I accomplish every time is getting the average for each row or column, but i have to find the average for each value in the text file.
For example: 76 / 48 = 1.5 (rounding off to 1 decimal)
Here my code:
public void studentAverage(double average) throws
FileNotFoundException
{
File infile= new File("qdata.txt");
Scanner sc = new Scanner(infile);
double rowNum = 0;
for (int row = 0; row < arr.length; row++)
{
for (int col = 0; col < arr[row].length; col++)
{
//Im stucked here
rowNum += arr[row][col];
}
average = rowNum / arr[row].length;
System.out.println("StudentAverage is: "+average);
rowNum = 0;
}
}
The average for each value in the entire grid is just a single number (I think). So, all you need to is to take the running sum and then divide by the number of cells:
double sum = 0.0d;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
sum += arr[row][col];
}
}
int size = arr.length*arr[0].length;
double average = sum / size;
System.out.println("StudentAverage is: " + average);
In my calculation of the size, which is the total number of students, I am assuming that your 2D array is not jagged. That is, I assume that each row has the same number of columns' worth of data.
You could use streams for this.
To get the overall average
double average = Arrays.stream(arr)
.flatMapToInt(Arrays::stream)
.average();
And to get the average per row:
double[] averagePerRow = Ararys.stream(arr)
.map(Arrays::stream)
.mapToDouble(IntStream::average)
.toArray();
This works for any 2D int array, jagged or not.
I would use List for this
public void studentAverage() throws FileNotFoundException {
File infile= new File("qdata.txt");
Scanner sc = new Scanner(infile);
double rowNum = 0;
List<List<Integer>> grades = new ArrayList<>();
double totalCount = 0.0;
while (sc.hasNext()) {
List<Integer> row = new ArrayList<>();
Scanner lineScanner= new Scanner(sc.nextLine());
while (lineScanner.hasNextInt()) {
row.add(lineScanner.nextInt());
}
grades.add(row);
totalCount += row.size();
}
int index = 0;
for (List<Integer> list : grades) {
for (Integer grade : list) {
System.out.println("Student average is " + (double)Math.round(grade.doubleValue() / totalCount * 10) / 10);
}
}
}
Check this Link - How to find average of elements in 2d array JAVA?
public class AverageElements {
private static double[][] array;
public static void main (String[] args){
// Initialize array
initializeArray();
// Calculate average
System.out.println(getAverage());
}
private static void initializeArray(){
array = new double[5][2];
array[0][0]=1.1;
array[0][1]=12.3;
array[1][0]=3.4;
array[1][1]=5.8;
array[2][0]=9.8;
array[2][1]=5.7;
array[3][0]=4.6;
array[3][1]=7.45698;
array[4][0]=1.22;
array[4][1]=3.1478;
}
private static double getAverage(){
int counter=0;
double sum = 0;
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
sum = sum+array[i][j];
counter++;
}
}
return sum / counter;
}
}
double sum=0;
int size=0;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
sum += arr[row][col];
}
size+=arr[row].length;
}
double average = sum/size;
System.out.println("StudentAverage is: "+average);

Java sentinel - reading text file into array

I've written a Java program which reads a series of real numbers from a text file into an array. I would like to use -1.0 as a sentinel so that scanner stops reading from the file when it reaches -1.0.
I'm struggling to insert the sentinel in the correct position, and also unsure if this should be done with an if or while statement. Any help much appreciated:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class CalculatingWeights {
public static void main(String[] args) throws FileNotFoundException {
//Create file and scanner objects
File inputFile = new File("in.txt");
Scanner in = new Scanner(inputFile);
//declare variables
double [] myArray = new double [100];
int i = 0;
double min = myArray[0];
double max = myArray[0];
//Read numbers from file, add to array and determine min/max values
while(in.hasNextDouble()) {
myArray[i] = in.nextDouble();
if(myArray[i] < min) {
min = myArray[i];
}
if(myArray[i] > max) {
max = myArray[i];
}
i++;
}
//Calculate and print weighting
for(int index = 0; index < myArray.length; index++) {
double num = myArray[index];
double weighting = (num - min) / (max - min);
System.out.printf("%8.4f %4.2f\n", num, weighting);
}
}
}
without changing a lot of your code use this
double [] myArray = new double [100];
int count = 0;
double min = myArray[0];
double max = myArray[0];
//Read numbers from file, add to array and determine min/max values
while(in.hasNextDouble()) {
myArray[count] = in.nextDouble();
//sentinel
if(myArray[count]==-1.0)
break;
if(myArray[count] < min) {
min = myArray[count];
}
if(myArray[count] > max) {
max = myArray[count];
}
count++;
}
//Calculate and print weighting
for(int index = 0; index < count; index++) {//<-----NOTE HERE: as the array is filled upto "count"
double num = myArray[index];
double weighting = (num - min) / (max - min);
System.out.printf("%8.4f %4.2f\n", num, weighting);
}

Java: array return largest number error

I want to find the largest number in an array then print them out, but I getting incorrect largest number output. Below is the output, as you can see the second and the third output for the largest number are incorrect.
Below is my code:
double x [][] = {{3.24,-0.96},
{-1.56,-0.61},
{-1.1,2.5},
{1.36,-4.8}};
String y [] = {"B","C","A","C"};
double w[][] = {{0,1.94,3.82},{0,-4.9,-4.03},{0,4.48,3.25}};
double threshold = 1;
int n = x.length;
int m = w.length;
double total [] = new double[3];
double max = 0;
double input = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
total[j] = (threshold * w[j][0]) + (x[i][0] * w[j][1]) + (x[i][1] * w[j][2]);
System.out.print(total[j] +", ");
input = total[j];
max = Math.max(input,max);
}
System.out.println();
System.out.println("Maximum is "+ max);
}
You never reset your max value, so it is still set as the max from the last calculation.
It will also fail when all values are below zero. You should initialise max to Integer.MIN_VALUE before each run.
You are continuing to keep the max value from j Loop for the subsequent i loop.
Reset the value of Max to min value before the start of subsequent i loop. Also edit the initial declaration from sero to min value.
Please refer below
double x [][] = {{3.24,-0.96},
{-1.56,-0.61},
{-1.1,2.5},
{1.36,-4.8}};
String y [] = {"B","C","A","C"};
double w[][] = {{0,1.94,3.82},{0,-4.9,-4.03},{0,4.48,3.25}};
double threshold = 1;
int n = x.length;
int m = w.length;
double total [] = new double[3];
double max = Integer.MIN_VALUE;
double input = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
total[j] = (threshold * w[j][0]) + (x[i][0] * w[j][1]) + (x[i][1] * w[j][2]);
System.out.print(total[j] +", ");
input = total[j];
max = Math.max(input,max);
}
System.out.println();
System.out.println("Maximum is "+ max);
max = Integer.MIN_VALUE;
}

How to use an array as type double?

I'm first using a scanner for user input and then calculating the mean.
I keep getting the error "lossy conversion from double to int".
It works when I use everything as type integer, but when calculating the mean it just converts it to an integer and it most of the time the mean isn't a whole number.
import java.util.Scanner;
public class CalculateMean {
public static void main(String[] args) {
Scanner enterValues = new Scanner(System.in);
System.out.println("Enter the number of values. ");
double n = enterValues.nextDouble();
double[] set = new double[n];
System.out.println("Enter values.");
for(double x=0; x<n; x++) {
set[x] = enterValues.nextDouble();
}
double sum = 0;
for(double cnt=0; cnt < set.length; cnt++) {
sum += set[cnt];
}
double mean = sum / n;
System.out.println("The average of the values is " + mean);
}
}
Even if the array element type is double, the index type is int. So your n, x, and cnt should be int, as you're using them to index into the array.
See the comment markers below:
import java.util.Scanner;
public class CalculateMean {
public static void main(String[] args) {
Scanner enterValues = new Scanner(System.in);
System.out.println("Enter the number of values. ");
int n = enterValues.nextInt(); // <== They won't give you 6.3 values, will they?
double[] set = new double[n];
System.out.println("Enter values.");
for (int x = 0; x < n; x++) { // <==
set[x] = enterValues.nextDouble();
}
double sum = 0;
for (int cnt = 0; cnt < set.length; cnt++) { // <==
sum += set[cnt];
}
double mean = sum / n;
System.out.println("The average of the values is " + mean);
}
}
To iterate the loop and in size of array use int not double like:
int n = enterValues.nextInt();
double[] set = new double[n];
...
for(int x=0; x<n; x++)
....
for(int cnt=0; cnt < set.length; cnt++)
Here is the code
package newPack;
import java.util.Scanner;
public class CalculateMean
{
public static void main(String[] args)
{
Scanner enterValues = new Scanner(System.in);
System.out.println("Enter the number of values. ");
int n = enterValues.nextInt();
double[] set = new double[n];
System.out.println("Enter values.");
for(int x=0; x<n; x++)
{
set[x] = enterValues.nextDouble();
}
double sum = 0;
for(int cnt=0; cnt < set.length; cnt++)
{
sum += set[cnt];
}
double mean = sum / n;
System.out.println("The average of the values is " + mean);
}
}

Finding the average in a partially filled array

The Idea is to create a method that is static that will calculate the average salary for a partially-filled array. Assume that numEmployees holds the number of elements in the array that have valid data. numEmployees is passed to the method.
public static double getAverage(double[ ] numEmployees)
{
double total = 0;
double average;
for (int i = 0; i < numEmployees.length; i++)
total += numEmployees[i];
average = total / numEmployees.length;
return average;
}
Do I need to add a part in the method that counts the array that are filled?
like:
int count=0;
int p=0;
if (numEmployees[p]>0)
{
count++;
p++;
}
or should I add a part in my for loop inside the message and change my total to this:
for (int i = 0; i < numEmployees.length || numEmployees>0; i++)
total += numEmployees[i];
Than farther down
average = total / i;
public static double getAverage(double[] numEmployees)
{
double total = 0;
double count = 0;
for (int i = 0; i < numEmployees.length; i++)
if (numEmployees[i] > 0) {
total += numEmployees[i];
count++;
}
return total / count;
}
Note that if there can be no more values after the first 0, it's also good to end the loop when one is detected. What i wrote here looks for any value greater than 0, no matter where the 0's occur.

Categories

Resources