Why it is not printing the magic square is magic? - java

I have to write a program that reads a file containing set of 16 numbers and creates a magic square. A magic square is one where the sum of each row, column, and diagonal is the same. I have to use the sentinel method to control your loop. The sentinel value is -999. When I run the code it shows that all are not magic square. When I run it it looks like the following.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
NOT a magic square
1 15 14 4
12 6 7 9
8 10 11 5
13 3 2 16
NOT a magic square
30 8 20 11
3 10 21 35
24 25 13 7
12 26 15 16
NOT a magic square
14 8 19 92
37 53 16 27
67 10 54 2
15 62 44 12
NOT a magic square
2 5 6 1
8 5 2 9
4 5 6 7
3 2 7 5
NOT a magic square
The following is the code.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
class square {
public static void main(String[] args) throws IOException {
File data = new File("Lab8Data.txt");
Scanner input = new Scanner(data);
int[][] array = new int[4][4];
int[] rowTotal = new int[4];
int[] columnTotal = new int[4];
for (int row = 0; row < array.length; row++)
array[0][row] = input.nextInt();
while (array[0][0] != -999) {
for (int column = 1; column < array.length; column++)
for (int row = 0; row < 4; row++)
array[column][row] = input.nextInt();
for (int column = 0; column < array.length; column++) {
for (int row = 0; row < array.length; row++)
System.out.print(array[column][row] + " ");
System.out.println();
}
for (int column = 0; column < array.length; column++)
for (int row = 0; row < array.length; row++)
rowTotal[column] += array[column][row];
for (int row = 0; row < array.length; row++)
for (int column = 0; column < array.length; column++)
columnTotal[row] += array[column][row];
int diagonalOne = 0;
for(int row = 0; row < array.length; row++)
diagonalOne = diagonalOne + array[row][row];
int otherDiagonal = 0;
for (int row = 0; row < array.length; row++) {
otherDiagonal = otherDiagonal + array[row][Math.abs(3 - row)];
int rows = rowTotal[0];
boolean rowEqual = true;
for (int r = 0; r < array.length; r++)
if (rowTotal[r] != r)
rowEqual = false;
int col = columnTotal[0];
boolean columnEqual = true;
for (int column = 0; column < array.length; column++)
if (rowTotal[column] != col)
columnEqual = false;
int diagonal = diagonalOne;
boolean diagonalEqual = true;
if (otherDiagonal != diagonal)
diagonalEqual = false;
boolean isMagic = false;
if (rowEqual && columnEqual && diagonalEqual)
if (rows == col && col == diagonal)
isMagic = true;
if (isMagic)
System.out.println("Is a magic square");
else
System.out.println("NOT a magic square");
for (int r = 0; r < 4; r++)
array[0][r] = input.nextInt();
}
}
}
}
This should be a magic square.
1 15 14 4
12 6 7 9
8 10 11 5
13 3 2 16
What should I do to make it print if the square is magic correctly.

I initialize the variables inside the loop, otherwise the totals will not be correct:
while (true) {
int[][] array = new int[4][4];
int[] rowTotal = new int[4];
int[] columnTotal = new int[4];
the first number you read is either the sentinel, or array[0][0]:
int number = input.nextInt();
if (number == -999) {
break;
}
array[0][0] = number;
Now you need to read the remainder of row 0:
for (int column = 1; column < array[0].length; column++) {
array[0][column] = input.nextInt();
}
and then the other rows:
for (int row = 1; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
array[row][column] = input.nextInt();
}
}
Now, the calculations; column totals:
for (int column = 0; column < array.length; column++) {
for (int row = 0; row < array.length; row++) {
columnTotal[column] += array[row][column];
}
}
row totals:
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array.length; column++) {
rowTotal[row] += array[row][column];
}
}
diagonals:
int diagonalOne = 0;
for (int row = 0; row < array.length; row++) {
diagonalOne += array[row][row];
}
int otherDiagonal = 0;
for (int row = 0; row < array.length; row++) {
otherDiagonal += array[row][array.length - row - 1];
}
then the comparisons:
int row = rowTotal[0];
boolean rowEqual = true;
for (int r = 0; r < array.length; r++) {
if (rowTotal[r] != row) {
rowEqual = false;
}
}
int col = columnTotal[0];
boolean columnEqual = true;
for (int column = 0; column < array.length; column++) {
if (columnTotal[column] != col) {
columnEqual = false;
}
}
int diagonal = diagonalOne;
boolean diagonalEqual = true;
if (otherDiagonal != diagonal) {
diagonalEqual = false;
}
boolean isMagic = false;
if (rowEqual && columnEqual && diagonalEqual) {
if (row == col && col == diagonal) {
isMagic = true;
}
}
if (isMagic) {
System.out.println("Is a magic square");
} else {
System.out.println("NOT a magic square");
}
Of course you wouldn't need to store the totals in arrays: you could just compare them as you compute them.
int sum = 0;
for (int row = 0; row < array.length; row++) {
sum += array[row][row];
}
boolean isMagic = true;
int magicNumber = sum;
sum = 0;
for (int row = 0; row < array.length; row++) {
sum += array[row][array.length - row - 1];
}
if (sum != magicNumber) {
isMagic = false;
}
for (int column = 0; column < array.length; column++) {
sum = 0;
for (int row = 0; row < array.length; row++) {
sum += array[row][column];
}
if (sum != magicNumber) {
isMagic = false;
}
}
for (int row = 0; row < array.length; row++) {
sum = 0;
for (int column = 0; column < array.length; column++) {
sum += array[row][column];
}
if (sum != magicNumber) {
isMagic = false;
}
}

public class Foo {
public static void main(String... args) throws IOException {
File file = new File("Lab8Data.txt");
int[][] square = readSquareFromFile(file);
boolean magicSquare = isMagicSquare(square);
System.out.println(magicSquare);
}
private static int[][] readSquareFromFile(File file) {
// TODO read from file
return new int[][] {
{ 1, 15, 14, 4 },
{ 12, 6, 7, 9 },
{ 8, 10, 11, 5 },
{ 13, 3, 2, 16 } };
}
private static boolean isMagicSquare(int[][] square) {
int magicNumber = Arrays.stream(square[0]).sum();
return isRowsMagic(square, magicNumber)
&& isColumnsMagic(square, magicNumber)
&& isDiagonalsMagic(square, magicNumber);
}
private static boolean isRowsMagic(int[][] square, int magicNumber) {
for (int row = 0; row < square.length; row++) {
int sum = 0;
for (int col = 0; col < square[row].length; col++)
sum += square[row][col];
if (sum != magicNumber)
return false;
}
return true;
}
private static boolean isColumnsMagic(int[][] square, int magicNumber) {
for (int col = 0; col < square[0].length; col++) {
int sum = 0;
for (int row = 0; row < square.length; row++)
sum += square[row][col];
if (sum != magicNumber)
return false;
}
return true;
}
private static boolean isDiagonalsMagic(int[][] square, int magicNumber) {
return getLeftDiagonalSum(square) == magicNumber && getRightDiagonalSum(square) == magicNumber;
}
private static int getLeftDiagonalSum(int[][] square) {
int sum = 0;
for (int i = 0; i < square.length; i++)
sum += square[i][i];
return sum;
}
private static int getRightDiagonalSum(int[][] square) {
int sum = 0;
for (int row = 0, col = square.length - 1; row < square.length; row++, col--)
sum += square[row][col];
return sum;
}
}

Related

Printing elements of a 2D array with columns and rows

Im new to java and I am trying to print elements I got from a selection sort algorithm both by columns and by rows.
The expected output for an unsorted matrix can be by rows
486 123 147
927 to 456 (rows) or 258 (columns)
135 (unsorted) 789 369
Thanks in advance! Please no professional solutions since I am a student.
public void sort(boolean byColumn)
{
double[] temp = null;
double placeHolder = 0.0;
int total = 0;
int index = 0;
/* Incrementing the total to use for the length of the temporary array. */
for (int rows = 0; rows < mdArray.length; rows++)
{
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
total++;
}
}
temp = new double[total];
/* This nested for loop converts the indices of mdArray to one long temp array. */
for (int rows = 0; rows < mdArray.length; rows++)
{
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
temp[index] = mdArray[rows][columns];
index++;
}
}
for (int i = 0; i < temp.length; i++) // Sorting the temporary array using selection sort.
{
for (int j = i + 1; j < temp.length; j++)
{
if (temp[j] < temp[i])
{
placeHolder = temp[i];
temp[i] = temp[j];
temp[j] = placeHolder;
}
}
}
index = 0;
if (byColumn) // Sorting the invoking array by column.
{
for (int rows = 0; rows < mdArray.length; rows++) // Puts sorted elements back into mdArray.
{
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
mdArray[rows][columns] = temp[index];
index++;
}
}
for (int rows = 0; rows < mdArray.length; rows++)
{
System.out.println();
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
System.out.print(mdArray[rows][columns] + " ");
}
}
}
else if (!byColumn) // Sorting the invoking by row.
{
for (int columns = 0; columns < mdArray[columns].length; columns++)
{
for (int rows = 0; rows < mdArray.length; rows++)
{
mdArray[columns][rows] = temp[index];
index++;
}
}
for (int rows = 0; rows < mdArray.length; rows++)
{
System.out.println();
for (int columns = 0; columns < mdArray[rows].length; columns++)
{
System.out.print(mdArray[rows][columns] + " ");
}
}
}
else if (byColumn && isRagged()) //
System.out.println("Cannot sort ragged arrays by column.");
}
Hint: if you add comment line to your code, this is definetly means, that it is better to extract code part to the separate method.
In your case, I reccomend to implement two more methods: sortByColumn(int[][] arr) and sortByRow(int[][] arr), because using sort(arr, true) is not so clear at the first sight (what exactly true means).
Public methods for the clients (clear to use):
public static void sortByColumn(int[][] arr) {
sort(arr, true);
}
public static void sortByRow(int[][] arr) {
sort(arr, false);
}
Sort implementation (proctected and not available to the client directly):
prvate static void sort(int[][] arr, boolean byColumn) {
int[] temp = convertToSimpleArray(arr);
selectionSort(temp);
if (byColumn) {
for (int row = 0, i = 0; row < arr.length; row++)
for (int col = 0; col < arr[row].length; col++)
arr[row][col] = temp[i++];
} else {
for (int col = 0, i = 0; i < temp.length; col++)
for (int row = 0; row < arr.length; row++)
if (col < arr[row].length)
arr[row][col] = temp[i++];
}
}
Method for create 1D array from given 2D array:
private static int[] convertToSimpleArray(int[][] arr) {
int total = 0;
for (int row = 0; row < arr.length; row++)
for (int col = 0; col < arr[row].length; col++)
total++;
int[] res = new int[total];
for (int row = 0, i = 0; row < arr.length; row++)
for (int col = 0; col < arr[row].length; col++)
res[i++] = arr[row][col];
return res;
}
Method for sort array with required sort algorithm:
private static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] >= arr[i])
continue;
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
Input:
int[][] arr = {
{ 19, 44, 16, 39, 26 },
{ 42, 6, 30 },
{ 44, 37, 0, 46 },
{ 37, 42, 48, 19, 40 } };
Output:
sortByColumn(arr) provides:
0 6 16 19 19
26 30 37
37 39 40 42
42 44 44 46 48
sortByRow(arr) provides:
0 19 37 42 46
6 26 39
16 30 40 44
19 37 42 44 48

Sudoku count subfield

I am currently working on a SudokuChecker I want to check the subfields [3x3] of the sudoku. The following code does this:
int[][] field = new field[9][9];
int wrongNumbers = 0;
for (int i = 0; i < 9; i += 3) {
for (int j = 0; j < 9; j += 3) {
// Check subfield by using an array
int arr[] = new int[10];
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
arr[field[i + k][j + l]]++;
}
}
for (int k = 1; k < arr.length; k++) {
wrongNumbers += arr[k] > 1 ? arr[k] - 1 : 0;
}
}
}
I want to know are there any improvements for the given code?
(I am not talking about making the 3, 9, etc. constant)
I found a very good answer in Codefights from thucnguyen:
boolean sudoku(int[][] grid) {
for (int i = 0; i <9; i++) {
int row = 0, col = 0, group = 0;
for (int j = 0; j <9; j++) {
// check for row i
row += grid[i][j];
// check for col i
col += grid[j][i];
// check for sub-grid i
group += grid[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3];
}
if (row != 45 || col != 45 || group != 45) return false;
}
return true;
}

Problems with refactoring java code

I am doing my homework right now and have a question about refactoring my code in Java.
I am working on a Sudoku right now and I need to check if the 3x3 boxes are valid or not. To do that I create a one dimensional array with all the numbers of the boxes and later I compare the value of them. It is working right now but it really isn't refactored at all. I would really like to know if there is any way to reduce all this copy paste.
public static boolean validFieldParts() {
int counter = 0;
boolean isValid = false;
int[] copyArray1 = new int[field.length];
int[] copyArray2 = new int[field.length];
int[] copyArray3 = new int[field.length];
int[] copyArray4 = new int[field.length];
int[] copyArray5 = new int[field.length];
int[] copyArray6 = new int[field.length];
int[] copyArray7 = new int[field.length];
int[] copyArray8 = new int[field.length];
int[] copyArray9 = new int[field.length];
// copy the array
// 1 große Feld
for (int i = 0; i < field.length / 3; i++) {
for (int j = 0; j < field[i].length / 3; j++) {
copyArray1[i * 3 + j] = field[i][j];
}
}
// 2 große Feld
for (int i = 0; i < field.length / 3; i++) {
for (int j = 3; j < 6; j++) {
copyArray2[i * 3 + j - 3] = field[i][j];
}
}
// 3 große Feld
for (int i = 0; i < field.length / 3; i++) {
for (int j = 6; j < 9; j++) {
copyArray3[i * 3 + j - 6] = field[i][j];
}
}
// 4 große Feld
for (int i = 3; i < 6; i++) {
for (int j = 0; j < field[i].length / 3; j++) {
copyArray4[(i - 3) * 3 + j] = field[i][j];
}
}
// 5 große Feld
for (int i = 3; i < 6; i++) {
for (int j = 3; j < 6; j++) {
copyArray5[(i - 3) * 3 + j - 3] = field[i][j];
}
}
// 6 große Feld
for (int i = 3; i < 6; i++) {
for (int j = 6; j < 9; j++) {
copyArray6[(i - 3) * 3 + j - 6] = field[i][j];
}
}
// 7 große Feld
for (int i = 6; i < 9; i++) {
for (int j = 0; j < field[i].length / 3; j++) {
copyArray7[(i - 6) * 3 + j] = field[i][j];
}
}
// 8 große Feld
for (int i = 6; i < 9; i++) {
for (int j = 3; j < 6; j++) {
copyArray8[(i - 6) * 3 + j - 3] = field[i][j];
}
}
// 9 große Feld
for (int i = 6; i < 9; i++) {
for (int j = 6; j < 9; j++) {
copyArray9[(i - 6) * 3 + j - 6] = field[i][j];
}
}
Arrays.sort(copyArray1);
Arrays.sort(copyArray2);
Arrays.sort(copyArray3);
Arrays.sort(copyArray4);
Arrays.sort(copyArray5);
Arrays.sort(copyArray6);
Arrays.sort(copyArray7);
Arrays.sort(copyArray8);
Arrays.sort(copyArray9);
for (int i = 1; i < copyArray1.length; i++) {
if (copyArray1[i] == copyArray1[i - 1])
counter++;
else
continue;
}
for (int i = 1; i < copyArray2.length; i++) {
if (copyArray2[i] == copyArray2[i - 1])
counter++;
else
continue;
}
for (int i = 1; i < copyArray3.length; i++) {
if (copyArray3[i] == copyArray3[i - 1])
counter++;
else
continue;
}
for (int i = 1; i < copyArray4.length; i++) {
if (copyArray4[i] == copyArray4[i - 1])
counter++;
else
continue;
}
for (int i = 1; i < copyArray5.length; i++) {
if (copyArray5[i] == copyArray5[i - 1])
counter++;
else
continue;
}
for (int i = 1; i < copyArray6.length; i++) {
if (copyArray6[i] == copyArray6[i - 1])
counter++;
else
continue;
}
for (int i = 1; i < copyArray7.length; i++) {
if (copyArray7[i] == copyArray7[i - 1])
counter++;
else
continue;
}
for (int i = 1; i < copyArray8.length; i++) {
if (copyArray8[i] == copyArray8[i - 1])
counter++;
else
continue;
}
for (int i = 1; i < copyArray9.length; i++) {
if (copyArray9[i] == copyArray9[i - 1])
counter++;
else
continue;
}
if (counter > 0)
isValid = false;
else
isValid = true;
return isValid;
}
Instead of using 9 different arrays and 9 different loops to represent each section of 9, I would have another nested for loop that iterates over each cluster using the same array.
//Iterate over each 'block'
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
//Iterate over each cell in the block
for (int i = row*3; i < (row+1)*3; i++) {
for (int j = col*3; j < (col+1)*3; j++) {
copyArray[(i - 3) * 3 + j - 3] = field[i][j];
}
}
//Sort array and do duplication check here - return false if dupe found
}
}
return true
This would cut down on the length of your code, although it may not be more efficient.
Instead of using a counter flag, it would be much faster to instead return false whenever you would have incremented the counter, and to return true at the end. This would prevent unnecessary code from running
Here a complete refactoring. Here the improuvements:
Created two new methods: createCopy and isValid
Deleted unused variables counter and isValid
Substituted 9 arrays with one two size array.
The code as not been tested, please take a bit careful attention on method createCopy in particular.
// Creates each block of 9 digits copying digits from field
// row, col are the block position, starting from upper left 0, 0 to
// last block 2, 2
public static int[] createCopy(int[] field, int row, int col) {
int[] copy = new int[9];
for (int i = 3 * row; i < 3 * row + 3; i++) {
for (int j = 3 * col; j < 3 * col + 3; j++) {
copy[(i - 3 * row) * 3 + j - 3 * col] = field[i][j];
}
}
return copy;
}
// Check if one block is valid
private static boolean isValid(int[] copyArray) {
Arrays.sort(copyArray);
for (int i = 1; i < copyArray.length; i++) {
if (copyArray[i] == copyArray[i - 1]) {
// Exit immediately if not valid
return false;
}
}
return true;
}
// Create blocks, then validate them
// At first not valid block return false
public static boolean validFieldParts() {
int[][] copyArrays = new int[3][3];
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
copyArrays[row][col] = createCopy(field, row, col);
}
}
for (int[] copyArray : copyArrays) {
if (!isValid(copyArray)) {
// Exit immediately if not valid
return false;
}
}
return true;
}

Calculate sum of rows above and below a point, and also sum of columns left and right a point

Hey guys I am doing a question where I have to find a point in a Matrix A of N x M rows such that
the sum of rows above the point is equal to the sum of row
Consider this example
/**
* A[0][0] = 2 A[0][1] = 7 A[0][2] = 5
* A[1][0] = 3 A[1][1] = 1 A[1][2] = 1
* A[2][0] = 2 A[2][1] = 1 A[2][2] = -7
* A[3][0] = 0 A[3][1] = 2 A[3][2] = 1
* A[4][0] = 1 A[4][1] = 6 A[4][2] = 8
* #param matrix
* #return
*/
In this example the if we look at the point A[1][1], it can be said that the row above (sum = 14) is equal to the sum of rows below the point.
Can anyone help me on this?
I have so far gotten this far. But I know this is a sucky approach.
public int solution(int[][] matrix) {
int rows = matrix[0].length;
int columns = matrix.length;
int sumabove = 0;
int sumbelow = 0;
for( int i = 1; i < rows; i++ ) {
for (int j = 0; j < columns; j++) {
sumabove += matrix[i - 1][j];
sumbelow += matrix[i + 1][j];
}
}
return 0;
}
The idea is to calculate sum for every row (int[] rowsSum) and sum for all rows (totalRowsSum). And then to iterate through rows, comparing sum of previous rows (currentSum) with sum of next rows (totalRowsSum - currentSum - rowsSum[i]).
Code example.
public static int solution(int[][] matrix)
{
int foundRowNumber = -1;
int rows = matrix.length;
int columns = matrix[0].length;
int[] rowsSum = new int[rows];
int totalRowsSum = 0;
for (int i = 0; i < rows; i++)
{
int rowSum = 0;
for (int j = 0; j < columns; j++)
{
rowSum += matrix[i][j];
}
rowsSum[i] = rowSum;
totalRowsSum += rowSum;
}
int currentSum = 0;
for (int i = 0; i < rows; i ++)
{
if (currentSum == totalRowsSum - currentSum - rowsSum[i])
{
foundRowNumber = i;
break;
}
currentSum += rowsSum[i];
}
return foundRowNumber;
}
i'd say:
1st: get the sum of the whole matrix
2nd: divide by 2 and store in a var (mid)
3rd: loop it to go down a row each time and it will get the sum of that row and subtract it from the total sum, if it is smaller than the remaining then keeps going, if the remaining number is smaller then (mid) then you went over the middle and you start checking the columns for the row you are in and before in another loop using the same concept
something like this (pseudo code):
int sum = matrix.sum();
int mid = sum/2;
int topsum = 0;
int botsum = sum;
int counter=0;
bool fail = false;
while(topsum!=botsum && !fail) //either break when both top and bottom are same or if there is no middle gorund
{
int rowsum; //use loop to get the sum of the row
for(int i=0; i>colLength(); i++) rowsum=+ matrix[counter][i];
topsum =+ rowsum;
botsum=-rowsum;
counter++;
if(botsum>mid) //if you go over the middle
{
botsum=-rowsum; //take it back before last addition acction
counter --; //go back to the last row;
//loop
//here you will start checking columns to get to the middle.
}
}
this was made so that it would get you the cell and not row, but you can change it to your liking.
Ok I was able to do make a solution. But I think I made a mess of the complexity. I was supposed to do in a linear complexity. Anyways my solution is
public class MainClass {
static int matrix[][] = {{2, 7, 5}, {3, 1, 1}, {2, 1, -7}, {0, 2, 1}, {1, 6, 8}};
public static void main(String[] args) {
System.out.print(solution(matrix));
}
/**
* A[0][0] = 2 A[0][1] = 7 A[0][2] = 5
* A[1][0] = 3 A[1][1] = 1 A[1][2] = 1
* A[2][0] = 2 A[2][1] = 1 A[2][2] = -7
* A[3][0] = 0 A[3][1] = 2 A[3][2] = 1
* A[4][0] = 1 A[4][1] = 6 A[4][2] = 8
* #param matrix
* #return
*/
public static int solution(int[][] matrix) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumRowsAbove = 0;
int sumRowsBelow = 0;
int sumColLeft = 0;
int sumColRight = 0;
int equilibrium = 0;
for( int i = 0; i < rows; i++ ) {
for (int j = 0; j < columns; j++) {
sumRowsBelow = getSumRowsBelow(i);
sumRowsAbove = getSumAbove(i);
sumColLeft = getSumColumnLeft(j);
sumColRight = getSumColumnRight(j);
if(sumRowsAbove == sumRowsBelow && sumColLeft == sumColRight) {
equilibrium++;
}
int x = 2;
x+=2;
}
}
return equilibrium;
}
public static int getSumRowsBelow(int rowNum) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for( int i = rowNum; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if((i+1) < rows){
sumBelow += matrix[i + 1][j];
}
}
}
return sumBelow;
}
public static int getSumColumnRight(int column) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for (int j = column; j <= columns; j++) {
for( int i = 0; i < rows; i++) {
if((j+1) < columns){
sumBelow += matrix[i][j + 1];
}
}
}
return sumBelow;
}
public static int getSumColumnLeft(int column) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for (int j = column; j >= 0; j--) {
for( int i = 0; i < rows; i++) {
if((j-1) >= 0){
sumBelow += matrix[i][j - 1];
}
}
}
return sumBelow;
}
public static int getSumAbove(int rowNum) {
int columns = matrix[0].length;
int rows = matrix.length;
int sumBelow = 0;
for( int i = rowNum; i >= 0; i--) {
for (int j = 0; j < columns; j++) {
if((i-1) >= 0){
sumBelow += matrix[i - 1][j];
}
}
}
return sumBelow;
}
}
This is a codility question regarding find the number of points (equilibriums) such the sum of elements in rows above the selected point is equal to the sum of rows below the point. And also sum of columns from the left of the selected point is equal to the sum of columns to the right of the point.

Add Matrices in Java

I need to write a short program on how to add two matrices.. The first matrix should look like this:
1 2 3 4 5 6 7 8 9 10
11 12 13.......19 20
21................30
31................40
41................50
etc..
91...............100
But I don't really come to a solution how to increment the first array.. :S
Here is what I got so far:
package uebung05;
public class MatrixAddition
{
public static void main(String[] argv)
{
int firstArray[][] = new int[10][10];
int secondArray[][] = new int[10][10];
int ergArray[][] = new int[10][10];
System.out.println("Matrix 1\n----------------------------");
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
// Increment Array here???
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nMatrix 2\n----------------------------");
// Dekrementieren der zweiten Matrix
for(int row = 0; row < secondArray.length; row++)
{
for(int column = 0; column < secondArray[row].length; column++)
{
// Array mit Werten befüllen
secondArray[row][column] = column + 1;
System.out.print(secondArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nAddition beider Matrizen\n----------------------------");
// Addition firstArray & secondArray
for(int row = 0; row < ergArray.length; row++)
{
for(int column = 0; column < ergArray[row].length; column++)
{
// Addition
ergArray[row][column] = firstArray[row][column] +
secondArray[row][column];
System.out.print(ergArray[row][column] + " ");
}
System.out.println();
}
}
}
Method to add the first and second matrices together:
public static int[][] matrixAdd(int[][] A, int[][] B)
{
// Check if matrices have contents
if ((A.length < 0) || (A[0].length < 0)) return B;
if ((B.length < 0) || (B[0].length < 0)) return A;
// create new matrix to store added values in
int[][] C = new int[A.length][A[0].length];
for (int i = 0; i < A.length; i++)
{
for (int j = 0; j < A[i].length; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}
But I don't really come to a solution how to increment the first array.
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
firstArray[row][column] = 1+ row*10 + column;
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
Sum two matrices in the new one and return:
public int[][] addMatrixes(int[][] src1, int[][] src2){
int[][] dst = new int[src1.length][src1[0].length];
for(int i=0;i<src1.length;i++){
for(int j=0;j<src1[0].length;j++){
dst[i][j] = src1[i][j] + src2[i][j];
}
}
return dst;
}
Not very generic, but you can define your first matrix with only one easy loop :
int dim = 10;
int size = dim*dim;
int firstArray[][] = new int[dim][dim];
int row, column;
for (int index = 0; index < size; index++ ){
row = index/dim;
column = index%dim;
firstArray[row][column]=row*10+column+1;
System.out.print(String.valueOf(firstArray[row][column])+"\t");
if (column == 9){ System.out.println("");}
}

Categories

Resources