Sum of individual rows and columns in user-specified matrix in Java - java

This assignment involves a 'matrix.txt' file that is to be imported into the program. This file can have a matrix of any size. The prof has furnished a working program to properly import this file, and has set the task of the students to determine if this file is a Magic Square. I know this means getting the sum of each row and each column and then comparing the values to see if they are equal. My problem is that I do not know how to specify a single rows' value that does not have to be immediately printed out, thereby losing the value when the loop repeats. I would like a way that will store each value so they can be checked for equality after the loop has iterated over all the possible rows and columns. since I have no idea what the size of the array will be, I cannot 'hard code' values, and would have to use stuff like:
sum = 0;
for (i = 0; i < matrix.length; i++)
{
for (j = 0; j < matrix[i].length; j++)
I am looking for a way to individualize the values of each row and column so I can compare them later. Then I would print out "The matrix is a magic square", or "The matrix is not a magic square"

Would some code like this work?
boolean isMagicSquard = true;
int sum = -1;
for (int i = 0; i < matrix.length; i++){
// Calculate the sum for each row
int rowsum = 0;
for (int j = 0; j < matrix[i].length; j++){
rowsum += matrix[j][i];
}
if (sum == -1){
sum = rowsum;
}else if (sum != rowsum){ // If the sum differs from the
// first-row sum, it is no magic squaree
isMagicSquard = false; break;
}
}
// The same code with rows and column swaped
for (int i = 0; i < matrix[0].length; i++){
int columnsum = 0;
for (int j = 0; j < matrix.length; j++){
columnsum += matrix[i][j];
}
if (sum != columnsum ){
isMagicSquard = false; break;
}
}
System.out.println(isMagicSquare);

Related

Find sum of every subarray in 2D array

I'm trying to find the sum of every subarray in a 2D array in Java and store them in a new array. This includes the sums of columns and rows. So far, all I can get down is code that can print out the sum of columns and rows.
I don't care about the complexity. In fact, I want to know the most brute force, obvious answer even if it is O(n^4). I am going to be comparing the subarray sums to a given value to see if that sum exists in the rectangular 2D array.
What I have:
public static void outputArray(int[][] array) {
for (int i = 0; i < array.length; i++){
int sum=0;
for (int j = 0; j < array[0].length; j++){
sum += array[i][j];
}
System.out.println("Print the sum of rows =" + sum);
}
int colSum=0;
for(int col=0;col<array[0].length;col++){
for(int row=0;row<array.length;row++){
colSum+=array[row][col];
}
System.out.println("Sum is "+colSum);
colSum = 0;
}
}
If u don't care about complexity && don't want to store the value then u can do it 0(n^6).
public static void outputArray(int[][] array) {
for(int i = 0; i < array.length; i++){
for(int j = 0; j< array[i].length; j++){
for(int k = i; k < array.length; k++){
for(int l = j; l < array[i].length; l++){
System.out.print("["+i+","+j+"]--->"+"["+k+","+l+"]");
int sum = 0;
for(int x = i; x <= k; x++){
for(int y = j; y<= l; y++){
sum+=array[x][y];
}
}
System.out.println("--->"+sum);
}
}
}
}
}
If u do some optimize like store prefix some then u can do it 0(n^4). With more optimization its possible to solve O(n^3).

java: 2D-Array with more rows than columns giving back: ArrayIndexOutOfBoundsException: 6

I have a 2D-Array which has more rows than columns. In this array I am summing up all values from one column, row by row and giving back the result.
Until there everything works fine, but after the last for loop I am getting the
Exception: java.lang.ArrayIndexOutOfBoundsException: 6
From other threads I only got the message that this means the number of rows and columns is uneven. In my case unfortunatly this needs to be an option.
See my code below:
double max = 0;
int machine = 0;
for(int c = 0; c < excelMatrix.length-1; c++){
double sum = 0;
for(int r = 0; excelMatrix.length-1; r++){
sum += excelMatrix[r][c];
}
if(max < sum){
max = sum;
machine = c;
}
}
The code works right until the end, but gives back the Exception after the last for-loop of r.
Usually when you loop through 2D array you use the following code:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.println(array[i][j]);
}
}
as 2D array is just array of arrays and each of them can have different size. Your condition
for(int r = 0; excelMatrix.length-1; r++)
looks strange. Does it compile?
You switch indexes r with c inside the loop!
sum += excelMatrix[c][r];
Proper code will be:
double max = 0;
int machine = 0;
for(int c = 0; c < excelMatrix.length; c++){
double sum = 0;
for(int r = 0; excelMatrix[c].length; r++){
sum += excelMatrix[c][r];
}
if(max < sum){
max = sum;
machine = c;
}
}
The proper code would be:
double max = 0;
int machine = 0;
int excelMatrix[][] =new int[][]{{1,2,3},{4,5,6}};
//System.out.println(excelMatrix.length);
//System.out.println(excelMatrix[0].length);
for(int c = 0; c <= excelMatrix[0].length-1; c++){
double sum = 0;
for(int r = 0; r<=excelMatrix.length-1; r++){
sum += excelMatrix[r][c];
}
if(max < sum){
max = sum;
machine = c;
}
}
System.out.println(max);
Above code will calculate sum from all columns and store maximum value from all sum by column to max variable.

Display a two dimensional array in java

I have an x by y board of numbers stored in a two dimensional array in java that I would like to print out to the user in a nice formatted manner. Would there be an easy way to do this in java?
Here is how I build my board:
board = new int[TotRow][TotCol];
You might prefer the one line, because it's easy, Arrays.deepToString(Object[]) the Javadoc says (in part),
This method is designed for converting multidimensional arrays to strings.
System.out.println(Arrays.deepToString(board));
If you want the number to be padded properly as well use String.format(),
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
System.out.print(String.format("%3d", board[i][j]) + "\t");
}
System.out.println();
}
Notice that I have used %3d for formatting, you can use format as required by you
You can print the board two dimensional array like this
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + "\t");
}
System.out.println();
}
Since I don't like relying on tabs, I'd like to mention some approaches that don't rely on them.
If you know that all of the numbers in the table are nonnegative numbers of, say, 4 digits or less, you can use String.format in a manner similar to Nitin's answer:
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
System.out.print(String.format("%4d ", board[i][j]));
}
System.out.println();
}
The %4d means to format the number using a width of 4 characters, and pad with blanks on the left if the number takes fewer than 4 characters to print. Thus, if there aren't any 5-digit or longer numbers, each print will print exactly 5 characters--a 4-character field for the number, and a space after the number. This will make everything line up, as long as none of the numbers is too large. If you do get a number that takes more than 4 characters, the formatting will get messed up.
Here's a way to adjust the column width so that it's just large enough to hold all the values in the table, and works fine if there are negative numbers:
int maxWidth = 0;
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
maxWidth = Math.max(maxWidth, Integer.toString(board[i][j]).length());
}
}
String format = "%" + maxWidth + "d ";
for (int i = 0; i < TotRow; i++) {
for (int j = 0; j < TotCol; j++) {
System.out.print(String.format(format, board[i][j]));
}
System.out.println();
}
Note: not tested
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(board[i][j] + "\t");
}
System.out.println();
}
You basically just use a nested loop.
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}

how to find prime number in 2d array and copy these numbers to another array

i have a code that create 2d array by asking user to enter the input than the system check if the elements are prime or not and if they are prime the system will copy them to an 1d array.
i can create the 2d array but i am stuck in the checking on the prime number and copied to a second array
this is the code
package question6;
import java.util.Scanner;
public class MtrixPrime {
public static void main(String[] args) {
int rows;
int cols;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of row");
rows = sc.nextInt();
System.out.println("Enter number of column");
cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
int[] array = new int[rows];
System.out.println("Enter numbers in the matrix");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if(matrix[i][j] % matrix[i][j] ==0 && matrix[i][j] %1 == 0){
////here i am stuck can anyone help me ??
array[i * j];
}
matrix[i][j] = sc.nextInt();
}
}
for(int row = 0 ;row<matrix.length; row++){
for(int col = 0 ; col< matrix.length; col++){
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
I know it's old post but this might help others.
Used isPrime a boolean flag to save the state of matrix[i][j] value.
If reminder is 0 isPrime will hold false state of matrix[i][j].
Everything is similar like finding prime number of single number. Just have to use 3 for loops for matrix index, before that I have taken matrix values separately.
here's the code.
public static void main(String[] args) {
int rows, cols, remainder;
boolean isPrime = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of row and colums : ");
rows = sc.nextInt();
cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
System.out.println("Enter numbers in the matrix");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = sc.nextInt();
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
for (int k = 2; k <= matrix[i][j] / 2; k++) {
remainder = matrix[i][j] % k;
if (remainder == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(matrix[i][j] + " is a Prime number");
} else
System.out.println(matrix[i][j] + " is not a Prime number");
}
}
}
One tricky thing to look out for is that since you don't know how many primes you're going to get, and you're using regular arrays, you need a 1d array at least the total size of your 2d array, or you should just use an ArrayList. If you're set on using a primitive array, you could just add a counter that increases every time you find a new prime, and use that counter value as your index. This however would leave you with zeros on the back end of your array. If you want your index to correspond to the multi-dimensional array index, you multiply the row index by the number of members in the row, and then add the column index in order to get a 1d index as shown below. This would leave you with zeros inbetween elements in your array. Having zeros shouldn't necessarily be a bad thing since it isn't prime, but its still way easier in my mind to use an ArrayList.
int[][] nums2d = {{0,1,2},{3,4,5},{6,7,8}};
int[] nums1d = new int[9];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int index = i * 3 + j;
nums1d[index] = nums2d[i][j];
}
}

sum of columns in a 2 dimensional array

static double [][] initialArray = {{7.432, 8.541, 23.398, 3.981}, {721.859, 6.9211, 29.7505, 53.6483}, {87.901, 455.72, 91.567, 57.988}};
public double[] columnSum(double [][] array){
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[i].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: "+sum);
index++;
}
return temp;
}
public static void main(String[] args) {
arrayq test = new arrayq();
test.columnSum(initialArray);
}
I want to get the sum of all the columns, but I keep getting an outofbounds exception. This is the output I get:
Index is: 0 Sum is: 817.192
Index is: 1 Sum is: 471.18210000000005
Index is: 2 Sum is: 144.7155
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at NewExam.arrayq.columnSum(arrayq.java:11)
Your outer for loop condition is giving you problems. Here's your loop: -
for (int i = 0; i < array[i].length; i++)
Now, when i reaches the value 3, you are trying to access array[3].length. This will throw you IndexOutOfBounds exception.
Since the size of every internal arrays are same, you can change your loop to: -
for (int i = 0; i < array[0].length; i++)
Or, even better, just store the array[0].length in some variable before hand. But that will not make much of a difference.
I would also suggest you to use a better way to calculate the sum of columns. Avoid iterating over rows first. Keep the iteration a normal one probably like this: -
public double[] columnSum(double [][] array){
int size = array[0].length; // Replace it with the size of maximum length inner array
double temp[] = new double[size];
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
temp[j] += array[i][j]; // Note that, I am adding to `temp[j]`.
}
}
System.out.println(Arrays.toString(temp));
return temp; // Note you are not using this return value in the calling method
}
So, you can see that how your problem is highly simplified. What I did is, rather than assigning the value to the array, I added the new value of array[i][j] to the existing value of temp[j]. So, gradually, the value of array[i][j] for all i's (rows) gets summed up in temp[j]. This way you don't have to use confusing iteration. So, just add the above code to your method, and remove the old one.
This method will also work fine, even if you have jagged-array, i.e., you inner arrays are not of same size. But just remember to define the size of temp array carefully.
Also note that, I have used Arrays.toString(temp) method to print the array.
Problem with your code is when it tries to fetch arr[3].length as there does not exist simple solution like sum = sum+arr[i][j] where i refers to row and j refers to column.
int row = arr.length;
int col = arr[0].length;
for(int j = 0; j < cols; j++)
{
int sum = 0;
for(int i = 0; i < rows; i++)
{
sum = sum + input[i][j];
}
}
for (int i = 0; i < array[i].length; i++)
for(int i=0;i<size;i++)
i & size must never be change in the loop
So close. The problem is that you are using array[i].length in your for loop. I changed it from array[i].length to array[0].length and your problem is gone. You need j there but you don't actually HAVE it yet.
You COULD do something like this although there isn't really any point if you know how you are going to get your array. Differently sized lists still would break the code for calculating sum though, you'd have to change that as well.
for (int i = 0, j = 0; i < initialArray[j].length; i++) {
for (; j < initialArray.length; j++) {
System.out.println(i + " " + j);
}
j = 0;
}
And here is your modified program.
public class Main {
static double[][] initialArray = { { 7.432, 8.541, 23.398, 3.981 }, { 721.859, 6.9211, 29.7505, 53.6483 }, { 87.901, 455.72, 91.567, 57.988 } };
public double[] columnSum(double[][] array) {
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[0].length; i++) {
double sum = 0;
for (int j = 0; j < array.length; j++) {
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: " + sum);
index++;
}
return temp;
}
public static void main(String[] args) {
new Main().columnSum(initialArray);
}
}
for index = 3, i is also equal with 3 and you have array[i].length in your code, but array have 3 item so you get Exception on array[3].length expression
try it
public double[] columnSum(double [][] array){
double temp[] = new double[array[0].length];
for (int i = 0; i < array[0].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[i] = sum;
System.out.println("Index is: " + i + " Sum is: "+sum);
}
return temp;
}

Categories

Resources