Java - Find the row and column with the max sum - java

As the title says, I want to know a way (in Java) to find which row (in a matrix/2D Array) and column has the highest sum of its numbers.
There might be an easy solution but I'm struggling to find it.
I currently have the first part of the program but I can't seem to find a solution to the second part, which is finding the row and column with the highest sum.
Desired output
I'm a beginner at this so any kind of advice would be appreciated.
This is the first part of my code:
import javax.swing.JOptionPane;
public class summat{
public static void main(String[] args){
int mat[][] = new int [3][3];
int num, sumop, sumw, i, j, mayop = 0, mayw = 0;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
String input = JOptionPane.showInputDialog(null, "Products sold by the operator " + (i+1) + " in week " + (j+1) + ".");
mat[i][j] = Integer.parseInt(input);
}
}
/*Sum of individual rows*/
for(i=0;i<3;i++){
sumop = 0;
for(j=0;j<3;j++){
sumop = sumop + mat[i][j];
}
JOptionPane.showMessageDialog(null, "The operator " + (i+1) + " sold " + sumop + " units.");
}
/*Sum of individual columns*/
for(j=0;j<3;j++){
sumw = 0;
for(i=0;i<3;i++){
sumw = sumw + mat[i][j];
}
JOptionPane.showMessageDialog(null, "In week " + (j+1) + " the company sold " + sumw + " units.");
}
}
}

public static void method(int[] arr, int row, int col) {
// converting array to matrix
int index = 0;
int mat[][] = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
mat[i][j] = arr[index];
index++;
}
}
// calculating sum of each row and adding to arraylist
ArrayList<Integer> rsum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int r = 0;
for (int j = 0; j < col; j++) {
r = r + mat[i][j];
}
rsum.add(r);
}
// calculating sum of each col and adding to arraylist
ArrayList<Integer> csum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int sum = 0;
for (int j = 0; j < col; j++) {
sum = sum + mat[j][i];
}
csum.add(sum);
}
System.out.println(
"Maximum row sum is " + Collections.max(rsum) + " at row " + rsum.indexOf(Collections.max(rsum)));
System.out.println(
"Maximum col sum is " + Collections.max(csum) + " at col " + csum.indexOf(Collections.max(csum)));
}
public static void method(int[][] mat, int row, int col) {
// calculating sum of each row and adding to arraylist
ArrayList<Integer> rsum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int r = 0;
for (int j = 0; j < col; j++) {
r = r + mat[i][j];
}
rsum.add(r);
}
// calculating sum of each col and adding to arraylist
ArrayList<Integer> csum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int sum = 0;
for (int j = 0; j < col; j++) {
sum = sum + mat[j][i];
}
csum.add(sum);
}
System.out.println(
"Maximum row sum is " + Collections.max(rsum) + " at row " + rsum.indexOf(Collections.max(rsum)));
System.out.println(
"Maximum col sum is " + Collections.max(csum) + " at col " + csum.indexOf(Collections.max(csum)));
}

You can use the following logic and implement it as desired.
// Row calculation
int rowSum = 0, maxRowSum = Integer.MIN_VALUE, maxRowIndex = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
rowSum = rowSum + mat[i][j];
}
if (maxRowSum < rowSum) {
maxRowSum = rowSum;
maxRowIndex = i;
}
rowSum = 0; // resetting before next iteration
}
// Column calculation
int colSum = 0, maxColSum = Integer.MIN_VALUE, maxColIndex = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
colSum = colSum + mat[j][i];
}
if (maxColSum < colSum) {
maxColSum = colSum;
maxColIndex = i;
}
colSum = 0; // resetting before next iteration
}
System.out.println("Row " + maxRowIndex + " has highest sum = " +maxRowSum);
System.out.println("Col " + maxColIndex + " has highest sum = " +maxColSum);
Here we use two additional variables maxRowSum to store the highest sum of the row and maxRowIndex to store the index of the highest row. The same applies for column as well.

You can have to integers one for row(maxRow) and one for col(maxCol) to maintain max values:
int maxRow = Integer.MIN_VALUE;
/*Sum of individual rows*/
for(i=0;i<3;i++){
sumop = 0;
for(j=0;j<3;j++){
sumop = sumop + mat[i][j];
}
if(maxRow > sumop)
maxRow = sumop;
JOptionPane.showMessageDialog(null, "The operator " + (i+1) + " sold " + sumop + " units.");
}
int maxCol = Integer.MIN_VALUE;
/*Sum of individual columns*/
for(j=0;j<3;j++){
sumw = 0;
for(i=0;i<3;i++){
sumw = sumw + mat[i][j];
}
if(maxCol > sumw)
maxCol = sumw;
JOptionPane.showMessageDialog(null, "In week " + (j+1) + " the company sold " + sumw + " units.");
}

Here's a method that first computes both row-wise and column-wise sums in one loop (the same one it uses to find max row sum), and a second one to find the max column sum:
//This returns an array with {maxRowIndex, maxColumnIndex}
public static int[] findMax(int[][] mat) {
int[] rowSums = new int[mat.length];
int[] colSums = new int[mat[0].length];
int maxRowValue = Integer.MIN_VALUE;
int maxRowIndex = -1;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
rowSums[i] += mat[i][j];
colSums[j] += mat[i][j];
}
if (rowSums[i] > maxRowValue) {
maxRowIndex = i;
maxRowValue = rowSums[i];
}
// display current row message
JOptionPane.showMessageDialog(null, "The operator " +
(i + 1) + " sold " + rowSums[i] + " units.");
}
int maxColumnValue = Integer.MIN_VALUE;
int maxColumnIndex = -1;
// look for max column:
for (int j = 0; j < mat[0].length; j++) {
if (colSums[j] > maxColumnValue) {
maxColumnValue = colSums[j];
maxColumnIndex = j;
}
// display column message
JOptionPane.showMessageDialog(null, "In week " +
(j + 1) + " the company sold " + colSums[j] + " units.");
}
return new int[] { maxRowIndex, maxColumnIndex };
}
The following test (I had to hard-code matrix values) produces [2, 2]:
public static void main(String[] args) {
int mat[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[] maxValues = findMax(mat);
System.out.println("Max row index: " +
maxValues[0] + ". Max Column index: " + maxValues[1]);
}

Related

Index out of bounds, error in IF line of code

So, this code is supposed to do the following:
Check if the neighboring members in a row of the square matrix and write them if their sum is an even number and also write the members which sum is a odd number. But it sends an error in the first if statement. But it only does the first row and outputs the Index out of bounds. Here is the code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Ucitati broj clanova kvadratne matrice: ");
int n = scan.nextInt();
int niz[][] = new int[n][n];
System.out.println("Ucitati clanove matrice: ");
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
System.out.print("n[" + i + ", " + j + "]" + "=");
niz[i][j] = scan.nextInt();
}
}
System.out.println();
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
System.out.print(niz[i][j] + " ");
}
System.out.println();
}
System.out.println("Susedni clanovi cija je suma parna su: ");
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
if ((niz[i][j] + niz[i][j + 1]) % 2 == 0) {
System.out.print(niz[i][j] + " " + niz[i][j + 1] + "; ");
}
}
}
System.out.println("Susedni clanovi cija je suma neparna su: ");
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
if ((niz[i][j] + niz[i][j + 1]) % 2 != 0) {
System.out.print(niz[i][j] + " " + niz[i][j + 1] + "; ");
}
}
}
}
System.out.println are in Serbian so if u need a translate let me know, but that shouldn't be needed.

Get the major diagonal and sub diagonal for matrix

Am confused about getting the "sub diagonal" for 2D array, I can get the columns , rows and major diagonal, but i don't know how to get sub diagonal, here is what i'v done so far:
int size = input.nextInt();
int[][] list = initiateArr(size);
for (int i = 0; i < list.length; i++) {
for (int j = i ; j < i + 1; j++) {
System.out.print(list[i][j] + " ");
}
}
My attempt for "sub diagonal":
for (int i = 0; i < list.length; i++) {
for (int j = (list.length / 2) + 1; j > list.length - (i + 1) ; j--) {
System.out.print(list[i][j] + " ");
System.out.println("j = " + j);
}
}
How to get sub diagonal?
I can get the major diagonal right as described in the output 1111, the sub diagonal should be 1010.
Here is the answer. Let me know if you have any questions.
public static void main(String args[]) {
int[][] list = {{1,2,3}, {4,5,6},{7,8,9}};
int matrixSize = 3;
System.out.println("Subdiagonal");
for( int i = 0; i < matrixSize ; i ++){
System.out.print( list[i][matrixSize - i -1] + " ");
}
System.out.println("");
System.out.println("Major ");
for( int i = 0; i < matrixSize ; i ++){
System.out.print( list[i][i] + " ");
}
}

Optimal way to creating a multiplication table -java

Hello I am trying to create a java program that output multiplication grid and I want to know if there is way to do it without having a lot of if statement if I had n values. Here is the code
public class MultiplicationGrid {
public static void main(String[] args) {
int num[][] = new int[4][4];
//String size[][] = new String[1][13];
for(int i = 0; i < num.length; ++i) {
for(int j = 0; j < num[i].length;++j) {
num[i][j] = (j+1)*(i+1);
}
}
int count = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
for (int i = 0; i < num.length; ++i) {
for(int j = 0; j < num[i].length; ++j) {
if(count == 0) {
count = num [i][j];
continue;
}
if(count1 == 0) {
count1 = num [i][j];
continue;
}
if(count2 == 0) {
count2 = num [i][j];
continue;
}
if(count3 == 0) {
count3 = num [i][j];
}
System.out.println(count + " " + (count1) + " " + (count2) + " " + (count3));
count = 0;
count1 = 0;
count2 = 0;
count3 = 0;
}
}
}
}
Thanks in advance.
You can define the table size and print the multiplication grid as follows:
public static void main(String[]args) {
final int TABLE_SIZE = 12;
// Declare the rectangular array to store the multiplication table:
int[][] table = new int[TABLE_SIZE][TABLE_SIZE];
// Fill in the array with the multiplication table:
for(int i = 0 ; i < table.length ; ++i) {
for(int j = 0 ; j < table[i].length ; ++j) {
table[i][j] = (i+1)*(j+1);
}
}
// Output the table heading
System.out.print(" :"); // Row name column heading
for(int j = 1 ; j <= table[0].length ; ++j) {
System.out.print((j<10 ? " ": " ") + j);
}
System.out.println("\n-------------------------------------------------------");
// Output the table contents
for(int i = 0 ; i < table.length ; ++i) {
System.out.print("Row" + (i<9 ? " ":" ") + (i+1) + ":");
for(int j = 0; j < table[i].length; ++j) {
System.out.print((table[i][j] < 10 ? " " : table[i][j] < 100 ? " " : " ") + table[i][j]);
}
System.out.println();
}
}

Magic Square Code (java)

I've been having an issue with my Magic Square code. It continually prints "This is a magic square" even when I'm positive it isn't.
You enter 16 integers, and then the code is supposed to run and determine whether the entered integers create a magic square (i.e. the sum of all rows, columns, and diagonals are all equal).
I can't figure out how to make it print false.
import java.util.*;
public class MagicSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner (System.in);
int [] [] square = new int [4][4];
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 4; col++)
{
System.out.println("Input value for row " + (row+1) + " column " + (col+1));
square[row][col] = keyboard.nextInt();
}
}
int [] sumRow = new int [4];
int [] sumCol = new int [4];
int sum = 0;
for (int row = 0; row < 4; row ++)
{
for (int col = 0; col < 4; col ++)
{
sum = sum + square[row][col];
sumRow[row] = sum;
}
System.out.println("sum row " + row + "\n" + sumRow[row]);
sum = 0;
}
sum = 0;
for (int col = 0; col < 4; col ++)
{
for (int row = 0; row < 4; row ++)
{
sum = sum + square[row][col];
sumCol[col] = sum;
}
System.out.println("sum columns " + col + "\n" + sumCol[col]);
sum = 0;
}
int [] sumDiag = new int [4];
sum = 0;
for (int row = 0; row < 4; row++)
{
for (int col = 3; col > -1; col--)
{
sum = sum + square [row][col];
sumDiag[row] = sum;
}
System.out.println("sum diagonal " + row + "\n" + sumDiag[row]);
sum = 0;
}
int [] sumDiag2 = new int [4];
sum = 0;
for (int col = 0; col < 4; col ++)
{
for (int row = 3; row > -1; row --)
{
sum = sum + square[row][col];
sumDiag2[col] = sum;
}
System.out.println("sum diagonal 2 " + col + "\n" + sumDiag2[col]);
}
boolean bool = false;
int k = 0; int j = 1;
do
{
if (sumRow[k] == sumRow[j])
{
k = j;
j += 1;
bool = true;
}
else
{
bool = false;
System.out.println("Not a magic square");
break;
}
} while ((k < 4) && (j >- 1));
k = 0; j = 1;
do
{
if (sumCol[k] == sumRow[j])
{
k = j;
j += 1;
bool = true;
}
else
{
bool = false;
System.out.println("Not a magic square");
break;
}
} while ((k < 4) && (j >= -1));
String TorF = "";
if (bool = true)
{
TorF = "is";
}
else if (bool = false)
{
TorF = "is not";
}
System.out.println("This " + TorF + " a magic square.");
}
}
There is a number of issues in your code, as said in the comments.
First, you only need to verify the main and secondary diagonals.
Second, your code to compare the sums doesn't work for all cases and doesn't compare the diagonals.
Also, the if in the end is just wrong. Do this instead:
if (bool) {
} else {
}
And here is a solution:
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++) {
for (int col = 0; col < order; col ++) {
sumRow[row] += square[row][col];
}
System.out.println("sum row " + row + "\n" + sumRow[row]);
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row ++) {
sumCol[col] += square[row][col];
}
System.out.println("sum columns " + col + "\n" + sumCol[col]);
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
System.out.println("sum diagonal 0 " + "\n" + sumDiag[0]);
for(int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
System.out.println("sum diagonal 1 " + "\n" + sumDiag[1]);
boolean bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
String tOrF = "";
if (bool) {
tOrF = "is";
} else {
tOrF = "is not";
}
System.out.println("This " + tOrF + " a magic square.");
Furthermore, there are some things you could do to optimize this code.

Checking For Repeats

I'm trying to write code that checks for repeat numbers in an array. If numbers repeat within the same row, it should generate another random number to replace the number. This is my class/method that is meant to accomplish this goal:
import java.util.*;
public class NoRepeats
{
public static void clean(int ticks[][])
{
for(int i = 0; i < ticks.length; i++)
{
for(int j = 0; j < ticks[0].length; j++)
{
nums[j] = ticks[i][j];
}
for(int k = 0; k < nums.length; k++)
{
for(int count = k + 1; count < nums.length; count++)
{
int othNums = nums[count];
while(true)
{
if(nums[k] == othNums)
{
System.out.print("\n\n Repeat:" + nums[k] + k + " " + othNums + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
for(int counter = count; counter < nums.length; counter++)
{
int othNums2 = nums[count];
if(nums[k] == othNums2)
{
System.out.print("\n\n Repeat NUM2:" + nums[k] + " " + othNums2 + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
}
}
for(int l = 0; l < k; l++)
{
int othNums3 = nums[l];
if(nums[k] == othNums3)
{
System.out.print("\n\n RepeatNUM2: " + nums[k] + " " + othNums3 + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
}
}
}
else
{
break;
}
}
count++;
}
}
for(int q = 0; q < nums.length; q++)
{
ticks[i][q] = nums[q];
}
count = 0;
}
}
public static int nums[] = new int[6];
public static int count = 1;
public static Random rndm = new Random();
public static int numsMatched[] = new int[100];
}
For some reason, there are still matches and I don't know why. Can anyone find what I've done wrong?
You're incrementing count twice and thus skip entries:
for(int count = k + 1; count < nums.length; count++) //<- increment 1
{
int othNums = nums[count];
while(true)
{
//snip
}
count++; //<- increment 2
}
The problem probably originates from the fact that you have a static variable which is also called count and which will be shadowed by the count defined in the loop:
public static int count = 1;
So either remove the second increment or rename one of the variables.

Categories