Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.Arrays;
- public class MagicSquare {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- int size = scan.nextInt();
- int[][] board = new int[size][size];
- // read user input into the board array
- for (int i = 0; i < size;i++){
- for (int j = 0; j < size; j++){
- board[i][j] = scan.nextInt();
- }
- }
- checkSquare(board);
- }
- private static void checkSquare(int[][] board){
- int[] xCol = new int[board.length];
- int[] yCol = new int[board.length];
- // calculate row and column totals
- for (int i = 0; i < board.length; i++){
- for (int j = 0; j < board.length; j++){
- xCol[i] += board[i][j];
- yCol[i] += board[j][i];
- }
- }
- if (Arrays.equals(xCol, yCol)){
- System.out.println("MAGIC");
- } else {
- notMagic(board, xCol, yCol);
- }
- }
- private static void notMagic(int[][] board, int[] xCol, int[] yCol){
- // TO DO: Determine if the square is ALMOST MAGIC or NOT MAGIC
- // PROBLEM: If it is almost magic - how will my algorithm check to find the value that will make it magic.
- int distinctSum = 0;
- int[] boardVal = new int[board.length * 2];
- System.arraycopy(xCol, 0, boardVal, 0, xCol.length);
- System.arraycopy(yCol, 0, boardVal, xCol.length, yCol.length);
- for (int i = 0; i < xCol.length; i++){
- if (boardVal[i] != boardVal[i + xCol.length]){
- distinctSum++;
- }
- }
- System.out.println(distinctSum == 2 ? "ALMOST MAGIC" : "NOT MAGIC");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement