Advertisement
KennasSticky

MagicSquare

Aug 7th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.Arrays;
  3.  
  4. public class MagicSquare {
  5.     public static void main(String[] args) {
  6.         Scanner scan = new Scanner(System.in);
  7.         int size = scan.nextInt();
  8.         int[][] board = new int[size][size];
  9.  
  10.         // read user input into the board array
  11.         for (int i = 0; i < size;i++){
  12.             for (int j = 0; j < size; j++){
  13.                 board[i][j] = scan.nextInt();
  14.             }
  15.         }
  16.  
  17.         checkSquare(board);
  18.     }
  19.  
  20.     private static void checkSquare(int[][] board){
  21.         int[] xCol = new int[board.length];
  22.         int[] yCol = new int[board.length];
  23.  
  24.         // calculate row and column totals
  25.         for (int i = 0; i < board.length; i++){
  26.             for (int j = 0; j < board.length; j++){
  27.                 xCol[i] += board[i][j];
  28.                 yCol[i] += board[j][i];
  29.             }
  30.         }
  31.        
  32.         if (Arrays.equals(xCol, yCol)){
  33.             System.out.println("MAGIC");
  34.         } else {
  35.             notMagic(board, xCol, yCol);
  36.         }
  37.     }
  38.    
  39.     private static void notMagic(int[][] board, int[] xCol, int[] yCol){
  40.        // TO DO: Determine if the square is ALMOST MAGIC or NOT MAGIC
  41.        
  42.        // PROBLEM: If it is almost magic - how will my algorithm check to find the value that will make it magic.
  43.        int distinctSum = 0;
  44.        int[] boardVal = new int[board.length * 2];
  45.  
  46.        System.arraycopy(xCol, 0, boardVal, 0, xCol.length);
  47.        System.arraycopy(yCol, 0, boardVal, xCol.length, yCol.length);
  48.  
  49.        for (int i = 0; i < xCol.length; i++){
  50.             if (boardVal[i] != boardVal[i + xCol.length]){
  51.                 distinctSum++;
  52.             }
  53.        }
  54.  
  55.        System.out.println(distinctSum == 2 ? "ALMOST MAGIC" : "NOT MAGIC");
  56.     }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement