removing a return statement from the loop - java

please i want to removed the returmn statement from the loop and have only one return statement at the end of the loop for the two method.
private boolean productFitsAt(int lOrigin, int wOrigin, int[] product) {
for (int i = wOrigin; i < wOrigin + product[Data.WID]; i++) {
for (int j = lOrigin; j < lOrigin + product[Data.LEN]; j++) {
if (i >= BOX_WIDTH || j >= BOX_LENGHT || BOX[i][j] != EMPTY) {
return false;
}
}
}
return true;
}
private boolean putProductIntoBox(int[] product) {
int[] a = getFreePositionToFit(product);
if (a == null) {
return false;
}
if (maxWeight < product[Data.WT]) {
return false;
}
for (int i = a[0]; i < a[0] + product[Data.WID]; i++) {
for (int j = a[1]; j < a[1] + product[Data.LEN]; j++) {
BOX[i][j] = product[Data.ID];
}
}
maxWeight -= product[Data.WT];
return true;
}

I would label the outer loop and break out of it once the result is assigned false, e.g.:
private boolean productFitsAt(int lOrigin, int wOrigin, int[] product) {
boolean result = true;
outer :for (int i = wOrigin; i < wOrigin + product[Data.WID]; i++) {
for (int j = lOrigin; j < lOrigin + product[Data.LEN]; j++) {
if (i >= BOX_WIDTH || j >= BOX_LENGHT || BOX[i][j] != EMPTY) {
result = false;
break outer;
}
}
}
return result;
}

You can use a boolean variable to store the return value, and return that variable at the end of the method:
private boolean productFitsAt(int lOrigin, int wOrigin, int[] product) {
boolean result = true;
for (int i = wOrigin; i < wOrigin + product[Data.WID] && result; i++) {
for (int j = lOrigin; j < lOrigin + product[Data.LEN] && result; j++) {
if (i >= BOX_WIDTH || j >= BOX_LENGHT || BOX[i][j] != EMPTY) {
result = false;
}
}
}
return result;
}
Note that once you determine the return value is false, you don't want to continue the loops. Since you have nested loops, a break statement won't be enough (since it will only break out of the inner loop), so I added the result variable to the condition of both loops.

You could also convert your nested loop into a nested allMatch or anyMatch statement using Java 8 Streams. Note that when using allMatch you have to invert the conditions:
private boolean productFitsAt(int lOrigin, int wOrigin, int[] product) {
return IntStream.range(wOrigin, wOrigin + product[Data.WID])
.allMatch(i -> IntStream.range(lOrigin, lOrigin + product[Data.LEN])
.allMatch(j -> (i < BOX_WIDTH && j < BOX_LENGTH && BOX[i][j] == EMPTY)));
}

Related

Converted this code from C# to Java, is there anything else that can be simplified in Java?

This is a function that, given an array A consisting of N integers, where A[K] denotes the height of the K-th tree, returns the number of ways of cutting out one tree, so that the remaining trees are aesthetically pleasing. If it is not possible to achieve the desired result, the function should return -1. If it's already aesthetically pleasing without any removal, the function should return 0.
This is the code written in C#.
using System;
namespace activity_problem
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("");
}
}
class Solution
{
public int solution(int[] a)
{
if (isAesthetic(a))
{
return 0;
}
int aestheticPatternCount = 0;
for (int j = 0; j < a.Length; j++)
{
int[] newA = copyArrayWithoutAnElement(a, j);
if (isAesthetic(newA))
{
aestheticPatternCount++;
}
}
if (aestheticPatternCount == 0)
{
return -1;
}
else
{
return aestheticPatternCount;
}
}
private int[] copyArrayWithoutAnElement(int[] array, int indexOfElementToBeRemoved)
{
int arrayLength = array.Length;
int[] newArr = new int[arrayLength - 1];
int tempK = 0;
for (int k = 0; k < arrayLength; k++)
{
if (k != indexOfElementToBeRemoved)
{
newArr[tempK++] = array[k];
}
}
return newArr;
}
private Boolean isAesthetic(int[] array)
{
int newArrayLength = array.Length;
int increasingFlag = 0;
for (int i = 0; i < newArrayLength; i++)
{
if (increasingFlag == 0)
{
if (array[i] < array[i + 1])
{
increasingFlag = 1;
}
else
{
increasingFlag = 2;
}
}
else
{
if (increasingFlag == 1)
{
if (i % 2 == 1 && array[i] > array[i - 1])
{
}
else if (i % 2 == 0 && array[i] < array[i - 1])
{
}
else
{
return false;
}
}
else
{
if (i % 2 == 1 && array[i] < array[i - 1])
{
}
else if (i % 2 == 0 && array[i] > array[i - 1])
{
}
else
{
return false;
}
}
}
}
return true;
}
}
}
Converted into JAVA, is there anything else that could be possibly simplified?
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
int solution = sol.solution(new int[]{1, 2, 3, 4, 5});
System.out.println(solution);
}
public static class Solution {
public int solution(int[] a){
if (isAesthetic(a))
{
return 0;
}
int aestheticPatternCount = 0;
for (int j = 0; j < a.length; j++)
{
int[] newA = copyArrayWithoutAnElement(a, j);
if (isAesthetic(newA))
{
aestheticPatternCount++;
}
}
if (aestheticPatternCount == 0)
{
return -1;
}
else
{
return aestheticPatternCount;
}
}
private int[] copyArrayWithoutAnElement(int[] array, int indexOfElementToBeRemoved)
{
int arrayLength = array.length;
int[] newArr = new int[arrayLength - 1];
int tempK = 0;
for (int k = 0; k < arrayLength; k++)
{
if (k != indexOfElementToBeRemoved)
{
newArr[tempK++] = array[k];
}
}
return newArr;
}
private Boolean isAesthetic(int[] array)
{
int newArrayLength = array.length;
int increasingFlag = 0;
for (int i = 0; i < newArrayLength; i++)
{
if (increasingFlag == 0)
{
if (array[i] < array[i + 1])
{
increasingFlag = 1;
}
else
{
increasingFlag = 2;
}
}
else
{
if (increasingFlag == 1)
{
if (i % 2 == 1 && array[i] > array[i - 1])
{
}
else if (i % 2 == 0 && array[i] < array[i - 1])
{
}
else
{
return false;
}
}
else
{
if (i % 2 == 1 && array[i] < array[i - 1])
{
}
else if (i % 2 == 0 && array[i] > array[i - 1])
{
}
else
{
return false;
}
}
}
}
return true;
}
}
}
I'm currently trying to learn algorithm in Java so any help or input is really appreciated.
For readability:
One thing you can do to simplify the code is remove the empty else-if branches.
Another would be to follow the usual java conventions and have the curly braces on the same line, for example:
if (something) {
// ...
} else if (somethingElse) {
// ...
} else {
// ...
}
For the actual program logic:
Instead of looking to port the code exactly as it is written, you can simplify some parts of it by using the Collections api. For example, if you need an array (and not some kind of List) then you can do all the work with removing elements, etc with a collection (e.g. ArrayList) and convert it to an array at the end.
Also, as noted in the comments there is a lot of comparison going on. If you can simplify that and do less comparing you'll have a better algorithm.
I would suggest starting with some unit tests with cases to validate against both the old code and new code.

Sudoku - How to use HashSet or Set?

I'm trying to code a method which checks for duplicates on my Sudoku board. Currently, my method getFrontier() always returns true, and I've come to learn that it's because it's only checking for one value rather than an array or values. I use the method 3 times in squareCheck(), rowCheck() and columnCheck(). Is there any way to code the method so it would retain the previous value which was input and then check it against the new value?
My current code:
public class validCheck {
public boolean isSolved(int[][][] board)
{
for(int index = 0; index < board.length;index++)
{
for(int r = 0; r < board[0].length; r++)
{
for(int c = 0; c < board[0].length;c++)
{
if(board[index][r][c] == 0)
return false;
}
}
}
return true;
}
public boolean getFrontier(int value)
{
Set<Integer> reserve = new HashSet<>();
for(int n = 1; n < 10; n++)
{
if(value == n && reserve.contains(n))
return false;
else if(value == n) reserve.add(n);
}
return true;
}
public boolean squareCheck(int[][][] board, int index)
{
for(int r = 0; r < board[0].length; r++)
{
for(int c = 0; c < board[0].length; c++)
{
if(!getFrontier(board[index][r][c]))
{
System.out.println("Square error at ["+index + r + c +"]");
return false;
}
}
}
return true;
}
public boolean isValid(int[][][] board)
{
if(isSolved(board))
{
for(int i = 0; i < board.length; i++)
{
for(int r = 0; r < board[0].length;r++)
{
for(int c = 0; c < board[0].length;c++)
{
if(!rowCheck(board,i,r) || !columnCheck(board,i,c) || !squareCheck(board,i))
{
return false;
}
}
}
}
}
return true;
}
public boolean columnCheck(int[][][] board, int index, int col)
{
int target = 0;
if(index <=2)
{
target = index + 6;
}
else if(index > 2 && index < 6)
{
target = index +3;
index = index - 3;
}
else if (index > 5)
{
target = index;
index = index - 6;
}
while(index <= target)
{
for(int r = 0; r < board[0].length;r++)
{
if(!getFrontier(board[index][r][col]))
{
System.out.println("Column error at " + index + r + col);
return false;
}
}
index = index + 3;
}
return true;
}
public boolean rowCheck(int[][][] board, int index, int row)
{
int target = 0;
if(index <= 2)
{
index = 0;
target = 2;
}
else if (index <= 5)
{
index = 3;
target = 5;
}
else if(index <= 8)
{
index = 6;
target = 8;
}
while(index <= target)
{
for(int c = 0; c < board[0].length; c++)
{
if(!getFrontier(board[index][row][c]))
{
System.out.println("Row error at "+index+row+c);
return false;
}
}
index++;
}
return true;
}
}
Usage:
public static void main(String[] args) {
int[][][] solved = {{{5,3,4},{6,7,2},{1,9,8}},
{{6,7,8},{1,9,5},{3,4,2}},
{{9,1,2},{3,4,8},{5,6,7}},
{{8,5,9},{4,2,6},{7,1,3}},
{{7,6,1},{8,5,3},{9,2,4}},
{{4,2,3},{7,9,1},{8,5,6}},
{{9,6,1},{2,8,7},{3,4,5}},
{{5,3,7},{4,1,9},{2,8,6}},
{{2,8,4},{6,3,5},{1,7,9}}};
validCheck checker = new validCheck();
if(checker.isValid(solved))
System.out.println(true);
else System.out.println(false);
}
Any help will be greatly be appreciated!!!
Here is what I would do to find a valid board config in a 2D sudoku board. I would use a HashSet for a row and another for the column, as long as we never encounter repeats and the values contain 1 to the length of the array we know the board is valid.
int [][] board = {{1,2,3},
{2,3,1},
{3,1,2}
};
HashSet<Integer> rowDuplicates = new HashSet<>();
HashSet<Integer> colDuplicates = new HashSet<>();
boolean invalidBoard = false;
for(int i = 0 ; i < board.length; i++)
{
for(int j = 0; j < board[i].length; j++)
{
if(rowDuplicates.contains(board[i][j]) || colDuplicates.contains(board[j][i]))
{
//this board is not valid
invalidBoard = true;
}
else
{
rowDuplicates.add(board[i][j]);
colDuplicates.add(board[j][i]);
}
}
//now check they contain the correct numbers from 1 to the size of the array
if(colDuplicates.size() == rowDuplicates.size())
{
for(int index = 0; index < colDuplicates.size(); index++)
{
if(!(colDuplicates.contains(index + 1) && rowDuplicates.contains(index + 1)))
{
invalidBoard = true;
break;
}
}
}
else
{
invalidBoard = true;
}
colDuplicates.clear();
rowDuplicates.clear();
}
System.out.println("invalid board: " + invalidBoard);
You should be able to expand this to your 3D array but you can see how much easier it is to use HashSets to verify a valid 2D array Sudoku board.

Game Of Life loop error

So I'm currently working on a program based on Conway's Game of Life, and this certain method requires me to update the 2d array to define which cells are alive. I've run my JUnit tests, but when the test for the method runs, it says it's infinitely looping. Any ideas why?
public void update() {
boolean temp ;
for (int i = 0; i < numberOfRows(); i++) {
for (int j = 0; j < numberOfColumns(); j++) {
temp = false;
if (cellAt(i, j)) {
temp = true;
}
if (temp=true) {
if (neighborCount(i, j) < 2 || neighborCount(i, j) > 3) {
society[i][j] = false;
}
} else {
if (neighborCount(i, j) == 3) {
society[i][j] = true;
}
}
}
}
}
Here is the other methods that are used in this one
cellAt():
public boolean cellAt(int row, int col) {
if (society[row][col] == true) {
return true;
} else {
return false;
}
}
neighborCount():
public int neighborCount(int row, int col) {
int counter = 0;
for (int i = ((row + numberOfRows() - 1) % numberOfRows()); i == ((row + 1) % numberOfRows())
|| i == row
|| i == (((row + numberOfRows() - 1)) % numberOfRows())
|| i == numberOfRows(); i++) {
i = i % numberOfRows();
for (int j = (((col + numberOfColumns() - 1)) % numberOfColumns()); j == ((col + 1) % numberOfColumns())
|| j == col
|| j == (((col + numberOfColumns() - 1)) % numberOfColumns())
|| j == numberOfColumns(); j++) {
j = j % numberOfColumns();
if (society[i][j] == true) {
counter++;
}
}
}
return counter;
}
You need to use comparison(==) instead of assignment(=) here:
if (temp=true) {
which will always return true
Change it to
if (temp == true) {
or simply use "Jean-François Savard" suggestion
if(temp)
Figured it out. neighborCount() was just horribly written and the for loops were repeating.

Alternate Solution for maxBlock from CodingBat

Solving this problem from codingBat
Given a string, return the length of the largest "block" in the
string. A block is a run of adjacent chars that are the same.
maxBlock("hoopla") → 2
maxBlock("abbCCCddBBBxx") → 3
maxBlock("") → 0
I was trying to solve it using one for loop as below:
public int maxBlock(String str) {
int maxCounter=1;
int counter=1;
if(str.length()==0)
{
return 0;
}
for(int i=0;i<str.length()-1;i++)
{
if(str.substring(i,i+1).equals(str.substring(i+1,i+2)))
{
counter++;
}
if(counter>maxCounter)
{
maxCounter=counter;
counter=0;
}
}
return maxCounter;
}
It beats all the cases apart from one. Can anybody show a solution with one for loop?
Sorry for mentioning late but you can't use REGEX or anything from collections framework.
I think you get it wrong in certain edge cases:
public int yourMaxBlock(String str) {
int maxCounter = 1;
int counter = 1;
if (str.length() == 0) {
return 0;
}
for (int i = 0; i < str.length() - 1; i++) {
if (str.substring(i, i + 1).equals(str.substring(i + 1, i + 2))) {
counter++;
}
if (counter > maxCounter) {
maxCounter = counter;
counter = 0;
}
}
return maxCounter;
}
public int myMaxBlock(String str) {
int maxCounter = 1;
int counter = 1;
if (str.isEmpty()) {
return 0;
}
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == str.charAt(i)) {
if (++counter > maxCounter) {
maxCounter = counter;
}
} else {
counter = 1;
}
}
return maxCounter;
}
public void test() {
String[] tests = new String[]{
"", "+", "++", "+++,++,++,+", "+,++,+++,++,", "+,++,+++,++++", "+++++,++,+++,++++"
};
for (String s : tests) {
int myMax = myMaxBlock(s);
int yourMax = yourMaxBlock(s);
System.out.println("myMaxBlock(" + s + ") = " + myMax + (myMax != yourMax ? " WRONG! you have " + yourMax : ""));
}
}
prints
myMaxBlock() = 0
myMaxBlock(+) = 1
myMaxBlock(++) = 2
myMaxBlock(+++,++,++,+) = 3
myMaxBlock(+,++,+++,++,) = 3
myMaxBlock(+,++,+++,++++) = 4 WRONG! you have 3
myMaxBlock(+++++,++,+++,++++) = 5 WRONG! you have 4
You can use a Pattern matcher "(.)(\\1)*" that look for repeated char in the String , Here is the code :
public int maxBlock(String str) {
Pattern pattern = Pattern.compile("(.)(\\1)*");
Matcher matcher = pattern.matcher(str);
int max = 0;
while (matcher.find()) {
max = Math.max(max, matcher.group().length());
}
return max;
}
I'm a little late to the party, but here's my CodingBat solution:
public int maxBlock(String str) {
int max = 0;
int count = 1;
char o = ' ';
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == o) {
count++;
if (count > max) { max = count; }
} else {
count = 1;
if (count > max) { max = count; }
}
o = c;
}
return max;
}
Here's a solution based loosely on yours. Note the use of charAt for a neater looking code example.
This starts at the second character of the string and looks backwards to see if we are still encountering the same character. If so, the counter increases. When we finish a string of identical chars, we compare against the max length found thus far and update if necessary.
public static int maxBlock(String str) {
int maxCounter = 1;
int counter = 1;
if (str.length() == 0) {
return 0;
}
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == str.charAt(i)) {
counter++;
} else {
// end of a run
if (counter > maxCounter) {
maxCounter = counter;
}
counter = 1;
}
}
return Math.max(maxCounter, counter);
}
Just use one for loop. I think here is another way.
public int maxBlock(String str) {
int len = str.length();
int temp=(len>0)?1:0;
int r =0;
for(int i=1; i<len; i++){
if(str.charAt(i) == str.charAt(i-1)){
temp++;
}
else{
r = (temp>r)?temp:r;
temp=1;
}
}
r = (temp>r)?temp:r;
return r;
}
public int maxBlock(String str) {
int max = 0;
for(int i = 0 ; i < str.length() ; i ++ ) {
char compareChar = str.charAt(i);
int count = 0;
while (i + 1 < str.length()
&& compareChar == str.charAt(i+1)) {
i++;
count ++;
}
if (max < count + 1) {
max = count + 1;
}
}
return max;
}
Here's my solution. It's simpler than you think.
public int maxBlock(String str)
{
//create a counter to return
int counter = 0;
//create a temporary variable to store a running total.
int temp = 1;
//Start on the first character and test to see if the second
//character equals the first.
for (int i = 1; i < str.length(); i++)
{
//If it does, we increment the temp variable.
if (str.charAt(i) == str.charAt(i-1))
{
temp++;
}
//If it doesn't, we wipe the temp variable and start from one.
else
{
temp = 1;
}
//If the temporary variable exceeds the counter amount, we make
//the counter variable equal to the temp variable.
if (temp > counter)
{
counter = temp;
}
}
//Return the counter.
return counter;
}
public int maxBlock(String str) {
int maxLength = 0;
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i = 0; i< str.length(); i++){
String key = str.substring(i,i+1);
if(i!=0 && str.charAt(i) == str.charAt(i-1) && map.containsKey(key)){
map.put(key, map.get(key)+1);
}
else{
map.put(key,1);
}
}
for(Map.Entry<String,Integer> entry : map.entrySet()){
if(maxLength <entry.getValue()){
maxLength = entry.getValue();
}
}
return maxLength;
}
public int maxBlock(String str) {
int count = 0;
int i = 0;
int maxcount = 0;
if (str.length() == 0) return 0;
while (i < str.length() - 1) {
if (str.charAt(i) == str.charAt(i + 1)) {
count++;
if (count > maxcount) {
maxcount = count;
}
} else count = 0;
i++;
}
return maxcount + 1;
}
public int maxBlock(String str) {
int tcount = 0;
if (str.length() < 1) {
return 0;
}
for (int i = 0; i < str.length(); i++) {
int count = 0;
for (int j = i; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
count++;
} else
break;
}
if (count > tcount) {
tcount = count;
}
i += count - 1;
}
return tcount;
}
this is easier it totally works.
int i = 0;
int j = 0;
while(i < inner.length && j < outer.length) {
if(inner[i] > outer[j]) {
j++;
} else if(inner[i] < outer[j]) {
return false;
} else {
i++;
}
}
if(i != inner.length)
return false;
return true;
}
Here My code for this
public int maxBlock(String str) {
int count = 1;
for(int i=0;i<str.length()-1;i++){
int count2 = 0;
if(str.substring(i,i+1).equals(str.substring(i+1,i+2) )){
for(int j = i ; j < str.length();j++){
if(str.substring(i,i+1).equals(str.substring(j,j+1))){
++count2;
}
else{
break;
}
}
}
if(count2 > count){
count = count2;
}
}
if(str.isEmpty())return 0;
return count;
}

Comparing too many variables in if statement

I wrote a code for my homework which says do inputs create a magic square matrix or don't. In magic square matrix, all of the rows, columns and diagonals sum must be equal. I wrote some functions to calculate the sum of the rows, columns and diagonals. At the end of the code I need to compare them to see they are equal or not. I assigned the results of the functions to different variables and I compared them in if statement at the end of the code. I am wondering is there any smarter way for comparison. I mean in my if statement there are too many variables and too many equality. I believe there is a smarter way for this.
package lab03;
import java.util.Scanner;
public class E7_15 {
public static boolean checkNumbers(int[][] array){
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if (array[i][j] < 1 || array[i][j] > 16){
System.out.println("You entered a wrong value");
return false;
}
}
}
return true;
}
public static int sumRow(int[][] array, int i){
int sum = 0;
for(int j=0; j<array[i].length; j++){
sum += array[i][j];
}
return sum;
}
public static int sumColumn(int[][] array, int j){
int sum = 0;
for(int i=0; i<array[j].length; i++){
sum += array[i][j];
}
return sum;
}
public static int diagonalSumRightToLeft(int[][] array){
int sum = 0;
for(int i=0; i<array.length; i++){
sum += array[i][array.length-1-i];
}
return sum;
}
public static int diagonalSumLeftToRight(int[][] array) {
int sum = 0;
for(int i=0; i<array.length; i++){
sum += array[i][i];
}
return sum;
}
public static void main (String [] args){
int[][] intArray = new int [4][4];
Scanner in = new Scanner(System.in);
for (int i=0; i<4; i++) {
for ( int j=0; j<4; j++) {
System.out.println("!!!Please enter your numbers between 1-16!!!");
System.out.println("Enter your number for row " + (i+1) + " and column " + (j+1) + ": ");
intArray[i][j] = in.nextInt();
}
}
boolean done = checkNumbers(intArray);
int sumLRD = diagonalSumLeftToRight(intArray);
int sumRLD = diagonalSumRightToLeft(intArray);
int r1 = sumRow(intArray, 0);
int r2 = sumRow(intArray, 1);
int r3 = sumRow(intArray, 2);
int r4 = sumRow(intArray, 3);
int c1 = sumColumn(intArray, 0);
int c2 = sumColumn(intArray, 1);
int c3 = sumColumn(intArray, 2);
int c4 = sumColumn(intArray, 3);
if (done == true){
if(sumLRD==sumRLD && sumLRD==r1 && sumLRD==r2 && sumLRD==r3 && sumLRD==r4 &&
sumLRD==c1 && sumLRD==c2 && sumLRD==c3 && sumLRD==c4 && sumRLD==r1 && sumRLD==r2 &&
sumRLD==r3 && sumRLD==r4 && sumRLD==c1 && sumRLD==c2 && sumRLD==c3 &&
sumRLD==c4 && r1==r2 && r1==r3 && r1==r4 && r1==c1 && r1==c2 && r1==c3 && r1==c4 &&
r2==r3 && r2==r4 && r2==c1 && r2==c2 && r2==c3 && r2==c4 && r3==r4 && r3==c1 &&
r3==c2 && r3==c3 && r3==c4 && r4==c1 && r4==c2 && r4==c3 && r4==c4 && c1==c2 &&
c1==c3 && c1==c4 && c2==c3 && c2==c4 && c3==c4){
System.out.println("This is a magic square matrix");
}
else {
System.out.println("This is NOT a magic square matrix");
}
}
if (done == false){
System.out.println("WRONG VALUE! START AGAIN!");
}
in.close();
}
}
It seems like you're trying to see if all those numbers are equal. Just use a loop that compares every variable in the list with the one following it:
public boolean allEqual(int... values) {
for (int i = 0; i < values.length-1; i++) {
if (values[i] != values[i+1]) {
return false;
}
}
return true;
}
Then replace your megacondition with:
if (allEqual(sumLRD, sumRLD, r1, r2, ...)) {
// ...
}
This works because equality is transitive - i.e. if a == b and b == c then a == c. (The same for any number of variables.)
An alternative would be to refactor the whole check into something like:
boolean isMagicSquare(int[][] intArray) {
// check diagonals
int sum = diagonalSumLeftToRight(intArray);
if (sum != diagonalSumRightToLeft(intArray)) {
return false;
}
// check rows and columns
for (int i = 0; i < 4; i++) {
if (sum != sumRow(intArray, i) || sum != sumColumn(intArray, i)) {
return false;
}
}
return true;
}
// ...
if (isMagicSquare(intArray)) {
// ...
}
You could put all your sums in an array and use a function like this one in order to check if all the values are equal:
public static boolean allElementsTheSame(int[] array) {
if (array.length == 0) {
return true;
} else {
int first = array[0];
for (int element : array) {
if (element != first) {
return false;
}
}
return true;
}
}

Categories

Resources