How to check if every other element is even - java

My code only works for the first index, which just returns 8 true.
If I change the first index (nums[0]) to 9 for example, it skips the 3 and prints 4 true.
How do I make so that it checks the rest of them (every other element that is) so that it works for every other index?
public static boolean solution(int[] nums) {
for(int i = 0; i < nums.length; i++) {
if(i % 2 == 0 && nums[i] % 2 == 0) {
System.out.print(nums[i] + " ");
return true;
}
}
return false;
}
public static void main(String args[]) {
int[] nums = {8,3,4,1,6,5,12,1};
System.out.println(solution(nums));
}

You have one (logical) error in your code, and one part that can be improved:
public static boolean solution(int[] nums) {
for(int i = 0; i < nums.length; i++) {
if(i % 2 == 0 && nums[i] % 2 == 0) {
System.out.print(nums[i] + " ");
return true;
}
}
return false;
}
In your current code, true is returned on the first valid test, which means, you don't test the following cases. Change your code so you'll test them all, and only return during the flow, if you encounter an invalid value.
public static boolean solution(int[] nums) {
for(int i = 0; i < nums.length; i++) {
if(i % 2 == 0 && nums[i] % 2 != 0) {
System.out.print(nums[i] + " ");
return false;
}
}
return true;
}
A second thing you can improve, is not checking for even indices each iteration. Just augment your i value by two instead of one:
public static boolean solution(int[] nums) {
for(int i = 0; i < nums.length; i+=2) {
if( nums[i] % 2 != 0) {
System.out.print(nums[i] + " ");
return false;
}
}
return true;
}

I think what you want to do is check all the even index and look if there are even you can do like this :
public static boolean solution(int[] nums) {
for(int i = 0; i < nums.length; i++) {
if(i % 2 == 0 && nums[i] % 2 != 0) {
System.out.print(nums[i] + " ");
return false;
}
}
return true;
}

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.

how to find if 2 elements of an array contains a certain value

Somehow I managed to find one certain value with the below code but how can I search if an array has value 1 and the right next value is 3
unlucky1([1, 3, 4, 5]) → true
unlucky1([2, 1, 3, 4, 5]) → true
unlucky1([1, 1, 1]) → false
public boolean unlucky1(int[] nums) {
//int[] a = new int[] {1,3};
for(int i: nums)
{
if (i == 1 )
return true;
}
return false;
}
You can use a state machine:
boolean wasOne = false;
for (int i: nums) {
if (i == 3 && wasOne) {
return true;
}
wasOne = i == 1;
}
return false;
The for-each loop hides the iterator (or index here), so you can't get the current value and check the next value at the same time. Use a standard loop. Also, since you don't access any field's - you could make the method static. Like,
public static boolean unlucky1(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == 1 && nums[i + 1] == 3) {
return true;
}
}
return false;
}
And, in Java 8+, you could express that with an IntStream and anyMatch like
public static boolean unlucky1(int[] nums) {
return IntStream.range(0, nums.length - 1)
.anyMatch(i -> nums[i] == 1 && nums[i + 1] == 3);
}
Note the nums.length - 1 in both cases, that is to ensure the nums[i + 1] doesn't exceed the length of the nums array on the conditional check.
Updated because you did not add the next condition - which was
in the first 2 or last 2 positions in the array.
That checker is strict. Follow the instructions carefully. I get (working)
public boolean unlucky1(int[] nums) {
int len = (nums == null) ? 0 : nums.length;
for (int i = 0; i < 2 && i + 1 < len; i++) {
if (nums[i] == 1 && nums[i + 1] == 3) {
return true;
}
}
if (len - 2 <= 0) {
return false;
}
for (int i = len - 2; i + 1 < len; i++) {
if (nums[i] == 1 && nums[i + 1] == 3) {
return true;
}
}
return false;
}
Which you could also implement without loops at all, like
public boolean unlucky1(int[] nums) {
int len = (nums != null) ? nums.length : 0;
if (len < 2) {
return false;
}
if ((nums[0] == 1 && nums[1] == 3) || (nums[1] == 1 && nums[2] == 3)) {
return true;
}
return len > 3 && ((nums[len - 4] == 1 && nums[len - 3] == 3) //
|| (nums[len - 2] == 1 && nums[len - 1] == 3));
}
I swapped the ternary order, but that's not important.
Try with basic for loop:
public boolean unlucky1(int[] nums) {
boolean match = false;
for (int i = 0; nums.length - 1 > i; i++) {
if (1 == nums[i] && 3 == nums[i + 1]) {
match = true;
break;
}
}
return match;
}
try this updated code.
arroding to your question
public boolean unlucky1(int[] nums) {
int count = 0;
for(int i=0;i<nums.length;i++)
{
if (nums[i] == 1 && (i+1)<nums.length && nums[i+1]==3){
if(i<2){
return true;
}
else if(i > nums.length-3){
return true;
}
}
}
return false;
}
OR
public boolean unlucky1(int[] nums) {
int len = nums.length;
if(len<2) return false;
if ((nums[0] == 1 && nums[1]==3)||(len>2 && nums[1] == 1 && nums[2]==3)){
return true;
}
if (nums[len-2] == 1 && nums[len-1]==3){
return true;
}
return false;
}

Counting number of unique adjacent pairs of same elements in an array

My function does not return the correct answer. My task is to count the two numbers in an array that are the same and next to each other here is a sample:
array_1 = {1,2,2,3,4,4,2}; ans = 2
array_2 = {2,2,3,4,4}; ans = 2
array_3 = {1,1,1,1,1,1,1}; ans = 1
array_4 = {1,2,3,4,2}; ans = 0
Here is my function. Observed output is given as comments.
public class countClampsTest
{
public static void main(String[] args)
{
int array_1[] = {1,2,2,3,4,4,2}; // expected result: 2
int array_2[] = {2,2,3,4,4}; // expected result: 2
int array_3[] = {1,1,1,1,1,1,1}; // expected result: 1
int array_4[] = {1,2,3,4,2}; // expected result: 0
System.out.println(countClamps(array_1)); // Returns 2
System.out.println(countClamps(array_2)); // Returns 1
System.out.println(countClamps(array_3)); // Returns 1
System.out.println(countClamps(array_4)); // Returns 0
}
static int countClamps(int[] arr) {
int result = 0;
int nextNext = 0;
for (int current = 0; current < arr.length - 1; current++) {
for (int next = current; next <= current + 1; next++) {
nextNext = next + 1;
if(nextNext >= arr.length) {
nextNext = arr.length -1;
}
if (arr[current] == arr[next] && current != next) {
if(arr[next] != arr[nextNext]) {
result++;
} else if(arr[next] == arr[nextNext] && arr.length % 2 == 0) {
result = 1;
}
}
}
}
return result;
}
}
I see a few issues in your code.
In the test:
if (arr[current] == arr[next] && current != next) {
you compare current with next; you could obtain the same result by starting the next loop at current+1 instead of current:
for (int next = current+1; next <= current + 1; next++) {
nextNext = next + 1;
...
if (arr[current] == arr[next]) {
...
}
}
which makes the loop redundant: it's only executed once, so the code above is equivalent to:
int next = current+1;
nextNext = next + 1;
...
if (arr[current] == arr[next]) {
...
}
Now in your inner test:
if(arr[next] != arr[nextNext]) {
result++;
} else if(arr[next] == arr[nextNext] && arr.length % 2 == 0) {
result = 1;
}
You can see that the first part of the second condition is always true, so it's equivalent to:
if(arr[next] != arr[nextNext]) {
result++;
} else if(arr.length % 2 == 0) {
result = 1;
}
The remaining condition means that you reset result to 1 if the array has an even number of elements (why?).
at the end of the array, result will not be incremented if the last two elements are equal, which is why you don't get the correct result in the second case.
Here is my solution:
static int countClamps(int[] arr) {
int result = 0;
for (int i = 1; i < arr.length; ++i) {
if (arr[i] == arr[i-1]
&& (i == arr.length-1 || arr[i] != arr[i+1])) {
++result;
}
}
return result;
}
A possible solution is: Stop you loop still one iteration earlier: use current < arr.length - 2 (this will cause nextNext to be within the array always). After your outer loop, just compare the last two elements of the array. If they are equal, add 1 to result. Done.
Except if the array has length 0 or 1, you will need to treat that specially.
I've added an extra boolean to keep track of already counted duplicates after each other.
static int countClamps(int[] arr) {
int result = 0;
int prev = 0;
boolean same = false;
for(int i = 0; i < arr.length; i++) {
if (i == 0) {
prev = arr[i];
} else {
if (arr[i] == prev) {
if (!same) {
result++;
same = true;
}
} else {
prev = arr[i];
same = false;
}
}
}
return result;
}
Once you've found a pair skip an index in loop.
public static int pairs(int[] list){
int pairs = 0;
for(int x = 1; x < list.length; x++){
if(list[x] == list[x-1]){
pairs++;
x=x+1;}
}
return pairs;
}

Solution of twoTwo riddle on codingBat in Java

The question is about Solving this problem from codingBat in Java.
Problem Statement:
Given an array of ints, return true if every 2 that appears in the array is next to another 2.
twoTwo({4, 2, 2, 3}) → true
twoTwo({2, 2, 4}) → true
twoTwo({2, 2, 4, 2}) → false
First of all going by the problem statement that every 2 that appears in the array is next to another 2. then
do you think as suggested the outcome for the first inputs shown above
should be true?
twoTwo({4, 2, 2, 3}) → true
Because as I see it it the first 2 itself that appears in the array is next to 4 not 2
am I confused or it's a wrongly stated question? I had to grapple with the problem to somehow get the right code to crack the problem as below but it seems a hotch potch:
public boolean twoTwo(int[] nums) {
if(nums.length==0)
{
return true;
}
if(nums.length==1)
{
return !(nums[0]==2);
}
if((nums.length==2))
{
if((nums[1]==2)&&(nums[0]==2))
return true;
else
return false;
}
for(int i=0;i+2<nums.length;i++)
{
if((nums[i]!=2)&&(nums[i+1]==2)&&(nums[i+2]!=2))
return false;
}
if((nums[nums.length-2]!=2)&&(nums[nums.length-1]==2))
return false;
return true;
}
Any efficient alternate solutions are welcome.
Thanks!
Here's how I would do it. It's a bit easier to follow I think:
public boolean twoTwo(int[] nums)
{
for (int i=0; i<nums.length; i++)
{
if (nums[i] != 2)
continue;
if (i >= 1 && nums[i-1] == 2)
continue;
if (i < (nums.length-1) && nums[i+1] == 2)
continue;
return false;
}
return true;
}
The solution I got to the problem is below:
public boolean twoTwo(int[] nums) {
final int length = nums.length;
for (int i = 0; i < length;){
int count = 0; // Used to count following 2's
while(i < length && nums[i++] == 2){
count++;
}
if(count == 1){ // No adjacent 2's! Set doesn't work.
return false;
}
}
return true; // Didn't come across a lone 2
}
The way that I handle this, is that I count all the adjacent 2's. If the count is not 1, we are good. This means that there was either no 2 at that index, or a group of 2's was present. This holds, since we traverse the array in a single direction.
A good thing about this solution is that it will work for an array of any size. Note that it would have a linear complexity, even though 2 loops are present. They both just traverse using the same index value, only ever sweeping over the array once.
If at any time we find a 2, then check the following only to find there are 0 following 2's (denoted by count), we return false.
public boolean twoTwo(int[] nums) {
for (int i=0; i<nums.length; i++) {
if(nums[i] == 2) { //If current number is 2
if (
// if prev or next is not 2 return true
!(i-1>=0 && nums[i-1] == 2) &&
!(i+1<nums.length && nums[i+1] == 2)
) { return false; }
}
}
return true;
}
For the sake of simplicity and clean code, this code forces the check
i-1>=0 and i+1<nums.length in every iteration.
This can be avoided by iterating from (1...nums.length-1) and checking the edge cases separately.
I know this is an old question, but I came up with a new solution. Short, and with no complicated conditionals.
public boolean twoTwo(int[] nums) {
int position = -2;
boolean result = true;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 2) {
result = position == i - 1;
position = i;
}
}
return result;
}
Next to means either before or after. Loop through each number and check the values before and after to see if there's an adjacent 2. The special cases are when you're checking the 1st and last element because there won't be an element before or after to check.
public boolean twoTwo(int[] nums) {
if(nums.length == 1 && nums[0] == 2)
return false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 2) {
if(i == 0) { // check the next element
if(nums[i+1] != 2)
return false;
}
else if(i == (nums.length - 1)) { // check the previous element
if(nums[i-1] != 2)
return false;
}
else { // check both
if(nums[i+1] != 2 && nums[i-1] != 2)
return false;
}
}
}
return true;
}
Here is mine solution to two two's problem. I think my solution is clear i.e. understandable.
package codingbat.array2;
public class TwoTwo
{
public static void main(String[] args)
{
}
public boolean twoTwo(int[] nums)
{
boolean twoTwo = true;
for (int i = 0; i < nums.length; i++)
{
if (2 == nums[i])
{
if (i > 0 && 2 == nums[i - 1]
|| nums.length > i+1 && 2 == nums[i+1])
{
twoTwo = true;
i++;
}
else
{
twoTwo = false;
break;
}
}
}
return twoTwo;
}
}
public boolean twoTwo(int[] nums) {
for(int i = 0 ; i < nums.length; i++ ) {
int count = 0;
if(nums[i] == 2 ) {
while(i+1 < nums.length && nums[i+1] == 2 ) {
count ++;
i++;
}
if (count == 0 ) {
return false;
}
}
}
return true;
}
public boolean twoTwo(int[] nums) {
for(int i = 0;i<nums.length;i++)
if(nums[i]==2 && !isTwoBeforeOrAfter(nums,i))
return false;
return true;
}
private boolean isTwoBeforeOrAfter(int[] nums,int i){
return i+1<nums.length && nums[i+1]==2 || i-1>=0 && nums[i-1]==2;
}
public boolean twoTwo(int[] nums) {
float two = 0;
double count = 0;
for (int i = 0; i < nums.length; i++) {
if (i < nums.length - 2 && nums[i] == 2 && nums[i + 1] == 2 && nums[i + 2] == 2) {
return true;
}
if (i < nums.length - 1 && nums[i] == 2 && nums[i + 1] == 2) {
count++; //count the pair
}
if (nums[i] == 2) {
two++;
}
}
return ((count * 2) == two);
//each pair contain 2 ,two"s .so pair*2=total two counts
//count
}
public boolean twoTwo(int[] nums) {
boolean two = false;
boolean result = true;
for (int i=0; i<nums.length; i++) {
if (nums[i] == 2) {
if (two) {
result = true;
} else {
result = false;
}
two = true;
} else {
two = false;
}
}
return result;
}
Here's my solution. Enjoy.
public boolean twoTwo(int[] nums)
{
//If the length is 2 or more
if (nums.length >= 2)
{
//If the last char is a 2, but the one before it is not a char, we return false;
if (nums[nums.length - 1] == 2 && nums[nums.length - 2] != 2)
{
return false;
}
//If larger than three, we create a for loop to test if we have any 2s that are alone.
if (nums.length >= 3)
{
for (int i = 1; i < nums.length-1; i++)
{
//If we find a two that is alone, we return false;
if ((nums[i] == 2) && (nums[i-1] != 2 && nums[i+1] != 2))
{
return false;
}
}
}
//If we don't return false, we return true;
return true;
}
//If we have less than two characters, we return true if the length is 0, or \
//One the one number there is not a 2.
else
{
return ((nums.length == 0) || !(nums[0] == 2));
}
}
public boolean twoTwo(int[] nums) {
int len = nums.length;
Boolean check = false;
int count = 0;
for(int i=0; i<len ; i++){
if(nums[i]==2){
count++;
if((i<len-1 && nums[i+1]==2) || (i>0 && nums[i-1]==2)) check = true;
else check = false;
}
}
if(count==0) check = true;
return check;
}
public boolean twoTwo(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++)
if (nums[i] == 2) count++;
else if (count == 1) return false;
else count = 0;
return count != 1;
}
Every time we encounter a 2, we increase the counter of consecutive 2s.
When it's not a 2 — but the counter indicates that there was a single 2 before it —, we know we've found a lonely 2.
Otherwise the search continues, resetting the 2-counter.
easy to understand)
static boolean twoTwo(int[] nums) {
int len = nums.length;
boolean result = true;
boolean found = false;
for(int i=0; i<len; i++){
//if it not 2, no meaning to go true other if-s
if(nums[i] !=2) {found = false; continue;}
// if current element is 2 and found is true(last element is 2)
if(nums[i] ==2 && found) result = true;
// if current element is 2, but last element not
if(nums[i] ==2 && !found){
found = true;
result = false;
}
}
return result;
}
This might be easier to follow if the other suggestions confuse you..
public boolean twoTwo(int[] nums) {
int len = nums.length;
if(len == 0) return true; // no 2's to worry about
if(len == 1) return nums[0] != 2; // make sure it's not a single 2
for(int i = 1; i < len -1; i++){ // loop for each except edge cases
if(nums[i] == 2 && nums[i-1] != 2 && nums[i+1] != 2) return false; // check surrounding
}
if(nums[len - 1] == 2) return nums[len - 2] == 2; //if last num is 2 check for 2 before it
return true; // made it here it's true
}
that one was tough for me... here's mine:
public boolean twoTwo(int[] nums) {
boolean two = false, res = true;
for (int i : nums) {
if (i == 2) {
if (two)
res = true;
else {
two = true;
res = false;
}
} else {
two = false;
}
}
return res;
}
One more alternative. Here is the main idea:
Convert array into String. Add a character different from "2" at the beginning and end of the string, to avoid going out of bounds.
Look for standalone "2" - if element of the string is equal to 2, check whether chars immediately before and after are also equal to "2". If they are it means that not all "2" are adjacent, and therefore method returns false.
public boolean twoTwo(int[] nums) {
// convert array to string
String text = "";
for (int i = 0; i < nums.length; i++) {
text += String.valueOf(nums[i]);
}
text = " " + text + " ";
// find standalone "2"
for (int i = 1; i < text.length() - 1; i++) {
if (text.charAt(i) == '2' && text.charAt(i - 1) != '2' && text.charAt(i + 1)
!= '2') {
return false;
}
}
return true;
}

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