Skip to content

Instantly share code, notes, and snippets.

@borensoren
Created November 12, 2012 15:20
Show Gist options
  • Save borensoren/4059934 to your computer and use it in GitHub Desktop.
Save borensoren/4059934 to your computer and use it in GitHub Desktop.
Magic Square verification
import java.util.Scanner;
public class P618
{
public static void main(String[] args)
{
public static boolean equalityCheck(int[] n, int m) //I get the error here
{
/**
checks array for equivalency
@param flag catches != values in array n
**/
boolean flag = true;
//verify all values are equal by checking against first value
for (int i = 0; i < n.length; i++)
{
if ((n[0] != n[i]) || (m[i] != n[0])){flag = false;}
}
return flag;
}
/**public int arraySum(int[] n) //not sure if this is correct, actually this is totally pointless
{
int sum = 0;
for (int i = 0, i < n.length, i++){sum = sum + n[i];}
return sum;
}
**/
public static boolean findNumber(int search, int[][] n)
{
/**
finds a value in a two dimensional array
param @search value to be found
param @flag truth value to be returned
param @n array being searched
**/
boolean flag = false;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (search = n[i][i]){flag = true;}
}
}
}
int[] square = new int[4][4];
Scanner in = new Scanner(System.in);
int[] rowTotals = new int[4];
int[] columnTotals = new int[4];
int counter = 1;
System.out.println("Let's make a magic square! Please enter numbers 1 through 16 in a random order.");
for (int i = 0; i < 4; i++) //row
{
for (int j = 0; j < 4; i++) // column
{
System.out.println("Input value " + counter + ": ");
square[i][j] = in.nextInt();
counter++;
rowTotals[i] = rowTotals[i] + square[i][j];
columnTotals[j] = columnTotals[j] + square[i][j];
}
}
int[] leftRightDiagonal = {square[0][0], square[1][1], square[2][2], square[3][3]};
int[] rightLeftDiagonal = {square[0][3], square[1][2], square[2][1], square[3][0]};
boolean rowColumnCheck = equalityCheck(rowTotals, columnTotals);
boolean diagonalCheck = equalityCheck(leftRightDiagonal, rightLeftDiagonal);
boolean crossCheck = equalityCheck(rowTotals, leftRightDiagonal);
int findThis = 1;
boolean allNumbers = true;
for (int i = 1; i < 17; i++) //checks for all integers 1 through 16
{
boolean check = findNumber(i, square);
if (check == false){allNumbers = false;}
}
if (allNumbers && rowColumnCheck && diagonalCheck && crossCheck){System.out.println("This is a magic square!");}
else{System.out.println("This isn't a magic square.");}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment