How to do multiple Array Operations using a single for loop? - java

so I'm being instructed to do the following, I can get it to run just fine, but it needs to be done with only a single for loop and I just can't figure out how to do it. Any help would be appreciated. This is what I came up with. I need to be able to get the Total, Average, Highest number and lowest number with one for loop.
public static void arrayTotalAndAverage(int[] array) {
int[] numbers = { 10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209 };
int total = 0;
double average = 0;
int highest = numbers[0];
int lowest = numbers[0];
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
average = total / numbers.length;
}
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > highest)
highest = numbers[i];
if (numbers[i] < lowest)
lowest = numbers[i];
}
System.out.println("Total");
System.out.println(total);
System.out.println("Average");
System.out.println(average);
System.out.println("Highest number");
System.out.println(highest);
System.out.println("Lowest number");
System.out.println(lowest);
}

You can do all this operations by StreamAPI.
int[] numbers = {10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209};
IntSummaryStatistics statistics = IntStream.of(numbers).summaryStatistics();
System.out.println("total: " + statistics.getSum());
System.out.println("average: " + statistics.getAverage());
System.out.println("minimum: " + statistics.getMin());
System.out.println("maximum: " + statistics.getMax());

Actually, perhaps the most efficient way to proceed here would be to just iterate the array once, and then keep track of state for the minimum, maximum, average, and total:
int[] numbers = { 10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209 };
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int total = 0;
double average = 0;
for (int i=0; i < numbers.length; ++i) {
total += numbers[i];
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
}
average = 1.0d * total / numbers.length;
System.out.println("total: " + total);
System.out.println("average: " + average);
System.out.println("minimum: " + min);
System.out.println("maximum: " + max);
This prints:
total: 1087
average: 72.46666666666667
minimum: 3
maximum: 212

You can do all the operations in single loop like this. And the average can be moved out of the loop.
int[] numbers = { 10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209 };
int total = 0;
double average = 0;
int highest = Integer.MIN_VALUE;
int lowest = Integer.MAX_VALUE;
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
if (numbers[i] > highest)
highest = numbers[i];
if (numbers[i] < lowest)
lowest = numbers[i];
}
average = total / numbers.length;
System.out.println("Total");
System.out.println(total);
System.out.println("Average");
System.out.println(average);
System.out.println("Highest number");
System.out.println(highest);
System.out.println("Lowest number");
System.out.println(lowest);
}

You can simply merge your second loop with the first one. Note that you should only calculate average at the end of the loop and one of the operands must be cast to double first to avoid the truncation of integer division.
int total = 0;
double average = 0;
int highest = numbers[0];
int lowest = numbers[0];
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
if (numbers[i] > highest)
highest = numbers[i];
if (numbers[i] < lowest)
lowest = numbers[i];
}
average = (double) total / numbers.length;
Demo
Output:
Total
1087
Average
72.46666666666667
Highest number
212
Lowest number
3

Related

How to make methods take in arrays from the main method?

What I need to do is make the main method give an array that the other two methods have. The code works, but the numbers are just in the wrong place.
Everything I've tried has given me an exception and I'm not sure what to do.
public static void main(String[] args) {
arrayTotalAndAverage(null); //not sure what to put in the parenthesis, it was corrected to be null
arrayTwoDimTotalAndAverage(null);
}
public static void arrayTotalAndAverage(int[] array) {
int[] numbers = {10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209}; //I need to move these numbers to the main method and I'm not sure how to leave it, is it "int[] numbers = {}"?
int total = 0;
double average = 0; //is this right?
int highest = numbers[0];
int lowest = numbers[0];
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
average = total / numbers.length;
if (numbers[i] > highest)
highest = numbers[i];
if (numbers[i] < lowest)
lowest = numbers[i];
}
System.out.println("Total");
System.out.println(total);
System.out.println("Average");
System.out.println(average);
System.out.println("Highest number");
System.out.println(highest);
System.out.println("Lowest number");
System.out.println(lowest);
}
public static void arrayTwoDimTotalAndAverage(int[][] array) {
int[][] numbers = { { 11, 17, 24 }, { 49, 57, 78 }, { 677, 173, 923 } };
int total = 0;
double average = 0;
int highest = numbers[0][0];
int lowest = numbers[0][0];
for (int row = 0; row < numbers.length; row++) {
for (int col = 0; col < numbers[row].length; col++) {
total += numbers[row][col];
average = total / numbers.length;
if (numbers[row][col] > highest)
highest = numbers[row][col];
if (numbers[row][col] < lowest)
lowest = numbers[row][col];
}
}
System.out.println("2D Total");
System.out.println(total);
System.out.println("2D Average");
System.out.println(average);
System.out.println("2D Highest number");
System.out.println(highest);
System.out.println("2D Lowest number");
System.out.println(lowest);
}
A simple example of how to send an array and receive them from another place is like this:
We have our array outside, then you pass it as parameter to your method, where you're expecting an int[] parameter, then you can make use of it with parameter variable name inside that method.
For example:
public class ArrayAsParametersExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
printNumbersFromArray(numbers);
}
private static void printNumbersFromArray(int numbersArray[]) {
for (int n : numbersArray) {
System.out.println(n);
}
}
}
You can make your main function look like:
public static void main(String[] args){
int[] numbers = {10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209};
arrayTotalAndAverage(numbers);
}
And do similarly for your other method.
Change arrayTwoDimTotalAndAverage like this.
public static void arrayTwoDimTotalAndAverage(int[][] array) {
int[][] numbers = { { 11, 17, 24 }, { 49, 57, 78 }, { 677, 173, 923 } };
int total = 0;
double average = 0;
int highest = numbers[0][0];
int lowest = numbers[0][0];
int count = 0;
for (int row = 0; row < numbers.length; row++) {
for (int col = 0; col < numbers[row].length; col++) {
total += numbers[row][col];
count += numbers[row].length;
if (numbers[row][col] > highest)
highest = numbers[row][col];
if (numbers[row][col] < lowest)
lowest = numbers[row][col];
}
}
average = total / count;
System.out.println("2D Total");
System.out.println(total);
System.out.println("2D Average");
System.out.println(average);
System.out.println("2D Highest number");
System.out.println(highest);
System.out.println("2D Lowest number");
System.out.println(lowest);
}
Like all Java objects, arrays are passed by value ... but the value is the reference to the array. So, when you assign something to a cell of the array in the called method, you will be assigning to the same array object that the caller sees.
So Instead of defining the array in each method, we can initialize the array in the main method, which we can then pass to the candidate methods as a parameter.
Try this:
public static void main(String[] args) {
int[] numbers = {10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209};
int[][] numbers2 = { { 11, 17, 24 }, { 49, 57, 78 }, { 677, 173, 923 } };
arrayTotalAndAverage(numbers);
arrayTwoDimTotalAndAverage(numbers2);
}
public static void arrayTotalAndAverage(int[] numbers) {
int total = 0;
double average = 0; //is this right?
int highest = numbers[0];
int lowest = numbers[0];
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
average = total / numbers.length;
if (numbers[i] > highest)
highest = numbers[i];
if (numbers[i] < lowest)
lowest = numbers[i];
}
System.out.println("Total");
System.out.println(total);
System.out.println("Average");
System.out.println(average);
System.out.println("Highest number");
System.out.println(highest);
System.out.println("Lowest number");
System.out.println(lowest);
}
public static void arrayTwoDimTotalAndAverage(int[][] numbers) {
int total = 0;
double average = 0;
int highest = numbers[0][0];
int lowest = numbers[0][0];
for (int row = 0; row < numbers.length; row++) {
for (int col = 0; col < numbers[row].length; col++) {
total += numbers[row][col];
average = total / numbers.length;
if (numbers[row][col] > highest)
highest = numbers[row][col];
if (numbers[row][col] < lowest)
lowest = numbers[row][col];
}
}
System.out.println("2D Total");
System.out.println(total);
System.out.println("2D Average");
System.out.println(average);
System.out.println("2D Highest number");
System.out.println(highest);
System.out.println("2D Lowest number");
System.out.println(lowest);
}

Determine which column contains the maximum sum of its elements

I would like to know, how to find out which column in the 2D-array has got the largest sum. How would I approach this?
public static void main(String args[]) {
int[][] array = {
{ 132, 154, 118 },
{ 355, 101, 50 },
{ 432, 143, 365 },
{ 462, 234, 185 }
};
}
You could go with a nested for loop
int maxCol = 0;
int valOfMaxCol = 0;
for(int i = 0; i < 3; i++){
int sum = 0;
for(int j = 0; j < array.length; j++){
sum += array[j][i];
}
if(sum > valOfMaxCol){
valOfMaxCol = sum;
maxCol = i;
}
}
System.out.println("Max Col is " + (maxCol + 1) + " with the value " + valOfMaxCol);

"ArrayIndexOutOfBoundsException" error in java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 7 years ago.
This program is supposed to find Max and Min in an array,
but it send error:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 23
at Mine_EnhancedForLoop.main(Mine_EnhancedForLoop.java:17)"
Does anyone know, what the problem is?
public class Mine_EnhancedForLoop {
public static void main(String[] args) {
int[] array1 = {23, 98, 10, 1, 45, 2, 7, 90};
int max = array1[0];
int min = array1[0];
for (int i : array1){
if (array1[i] > max)
max = array1[i];
else if (array1[i] < min)
min = array1[i];
}
System.out.println("Maximum is: " + max);
System.out.println("Minimum is: " + min);
}
}
In for (int i : array1), i is a value contained in the array, not an index of the array. Therefore array1[i] will throw the exception you got whenever i >= array1.length (which is the case for most of the values in your input array).
If you don't need to know the index of the highest and lowest values, this will work :
for (int i : array1) {
if (i > max)
max = i;
else if (i < min)
min = i;
}
for (int i : array1)
i gives the element of array not the index of array
So in the first iteration
if(array1[23] > max) //gave you ArrayIndexOutOfBoundsException 23
you can do
int[] array1 = {23, 98, 10, 1, 45, 2, 7, 90};
int max = array1[0];
int min = array1[0];
int i=0;
while(i< array1.length){
if (array1[i] > max)
max = array1[i];
else if (array1[i] < min)
min = array1[i];
i++;
}
System.out.println("Maximum is: " + max);
System.out.println("Minimum is: " + min);
Demo
You have to iterate the array elements as:
for (int i=0; i<array1.length; i++){
if (array1[i] > max)
max = array1[i];
else if (array1[i] < min)
min = array1[i];
}
Change the for loop to
for (int i = 0; i < array1.length; i++) {
if (array1[i] > max) {
max = array1[i];
} else if (array1[i] < min)
min = array1[i];
}
}
Because variable i contains 23 when making the comparison here if (array1[i] > max), hence array1[23] gave the exception.
Loop over the array instead:
for (int i = 0; i < array1.length; i++) {
if (array1[i] > max)
max = array1[i];
else if (array1[i] < min)
min = array1[i];
}
Actually it is much easier to use Java 8 streams:
int[] array1 = {23, 98, 10, 1, 45, 2, 7, 90};
System.out.println("Maximum is: " + Arrays.stream(array1).max().getAsInt());
System.out.println("Minimum is: " + Arrays.stream(array1).min().getAsInt());

Output one dimensional array as 2 dimensional in java

I have to output the array with a maximum of 4 array values per line, but I can't figure out how to convert it to a 2 dimensional array. After the dashes is where I am having trouble. If I don't output it as a 2D array, how else would I restrict it to have only 4 values per line?
public class arrayExampleB{
public static void main(String[] args){
int[] x = {22, 12, 28, 4, 30, 59, 17, 82, 1, 99, 47, 2, 8, 20, 80};
System.out.print("Pre-Swapped Array Set (linear): {");
for(int i=0; i<=x.length-1; i++){
if(i<x.length-1){
System.out.print(x[i] + ", ");
}
else{System.out.print(x[i]);}
}
System.out.print("}");
int y = x.length-1;
int temp = x[y];
x[y] = x[1];
x[1] = temp;
int z = x.length-2;
int temp2 = x[z];
x[z] = x[0];
x[0] = temp2;
System.out.print("\nPost-Swapped Array Set (linear): {");
for(int i=0; i<=x.length-1; i++){
if(i<x.length-1){
System.out.print(x[i] + ", ");
}
else{System.out.print(x[i]);}
}
System.out.print("}");
//-------------------------------------------------------------
int d = (x.length / 4) + (x.length % 4);
int i = 0;
int j = 0;
int[][] t = new int[i][j];
System.out.print("\nPre-Swapped Array Set (2D): {");
for(i=0; i <= 4; i++){
for(j=0; j < d; j++){
System.out.print(t[i][j] + " ");
}
System.out.println();
}
System.out.print("}");
}
}
To output a 1d array as 2d with a max of 4 values on a line, use this code:
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
if ((i+1) % 4 == 0)
System.out.println();
}
int[] x = {22, 12, 28, 4, 30, 59, 17, 82, 1, 99, 47, 2, 8, 20, 80};
int[][] t = new int[4][4];
// populate 2D
int k = 0
for(i=0; i <= t.length; i++){
for(j=0; j < t[i].length; j++){
t[i][j] = x[k];
k++l
}
}
// print
for(i=0; i <= t.length; i++){
System.out.print("{");
for(j=0; j < t[i].length; j++){
System.out.print(t[i][j]);
}
System.out.println("}");
}
Without taking too close a look on your code: To output a one dimensional array on several lines on the console consider this:
int[] x = {22, 12, 28, 4, 30, 59, 17, 82, 1, 99, 47, 2, 8, 20, 80};
for(int i = 0; i < x.length; i++)
{
System.out.print(x[i] + ' ');
if( (i+1) % 4 == 0)
System.out.print('\n');
}

How to find a index from a two dimensional array

What I'm trying to do is print the largest number within a two dimensional array and it's index location. I'm able to find the largest number, but I can't seem to figure out how to print it's index location. Anyway, here's what I have so far:
public static void main(String[] args) {
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
double max = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
}
System.out.println(max);
System.out.println(i + j); //No idea what I should be doing here, just trying out everything I can think of
Right now, you should consistently get 2 * arr.length as the final value. That isn't what you are probably looking for. It looks like you want to know the coordinates for the max value. To do this, you'll need to cache the values of the indexes and then use them later:
public static void main(String[] args) {
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int tmpI = 0;
int tmpJ = 0;
double max = arr[0][0];
// there are some changes here. in addition to the caching
for (int i = 0; i < arr.length; i++) {
int[] inner = arr[i];
// caches inner variable so that it does not have to be looked up
// as often, and it also tests based on the inner loop's length in
// case the inner loop has a different length from the outer loop.
for (int j = 0; j < inner.length; j++) {
if (inner[j] > max) {
max = inner[j];
// store the coordinates of max
tmpI = i; tmpJ = j;
}
}
}
System.out.println(max);
// convert to string before outputting:
System.out.println("The (x,y) is: ("+tmpI+","+tmpJ+")");
Be careful with your array dimensions! The second for-statement most of you have is wrong. It should go to up to arr[i].length:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
tmpI = i; tmpJ = j;
}
}
}
Store i, j whenever you update max.
This would be if you wanted a single index into a flatten array:
public static void main (String[] args) throws java.lang.Exception
{
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int[] flattened = new int[6*3]; // based off above
int maxIndex = 0;
double max = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
flattened[i + j] = arr[i][j];
if (arr[i][j] > max) {
max = arr[i][j];
maxIndex = i+j;
}
}
}
System.out.println(max);
System.out.println(flattened [maxIndex]);
}
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int max = arr[0][0];
int maxI = 0, maxJ = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
maxI = i;
maxJ = j;
}
}
}
System.out.println(max);
System.out.println(maxI + "," + maxJ);
You've got a two-dimensional array, therefore you need to know both indexes. Adding them together won't do because you lose which-is-which. How about this:
System.out.println("[" + i + "][" + j + "]");
//C++ code
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> b;
vector<int> c;
int Func(int a[][10],int n)
{
int max;
max=a[0][0];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i][j]>max)
{
max=a[i][j];
b.push_back(i);
c.push_back(j);
}
}
}
b.push_back(0);
c.push_back(0);
return max;
}
void display(int a[][10],int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j]<<"\t";
}
cout<<endl;
}
}
int main()
{
int a[10][10],n;
cin>>n;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
cout<<endl;
display(a,n);
cout<<endl;
cout<<Func(a,n)<<" is the greatest "<<endl;
if(b.size()==1&&c.size()==1)
{
cout<<"Location is (1,1)"<<endl;
}
else
{
b.erase(b.end() - 1);
c.erase(c.end() - 1);
cout<<"Location is "<<"("<<b.back()+1<<","<<c.back()+1<<")"<<endl;
}
return 0;
}
You're just adding the indices i and j together and then printing it to the screen. Since you're running throug the entire loop it's just going to be equal to 2*arr.length-2. What you need to do is store the values of i and j when you encounter a new max value.
For example:
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int max = arr[0][0]; //dunno why you made it double when you're dealing with integers
int max_row=0;
int max_column=0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
max_row=i;
max_column=j;
}
}
System.out.println("The max is: "+max+" at index ["+max_row+"]["+max_column+"]");
Don't sure that you implement effective algorithm, but why you just don't save indices i,j in another variables when you set max.
This is very simple.
if (arr[i][j] > max) {
max = arr[i][j];
maxX = i;
maxY = j;
}
FYI If you want look at "insertion sorting" algorithms if you want better implementation.

Categories