2

I didn't want to have to ask, but I can not figure out this assignment, and neither could the TA when I asked for help.

I have to take input from a text file, feed the integers in the file into an array list, and test to see if it is a n x n magic square. n is equal to the square root of the array list's length. If it isn't a perfect square it immediately fails the magic square test.

Anyway I have it almost completed; I just don't seem to understand what my professor is telling/asking us to do in the final step of the magic square test.

All the testing before these final four steps works flawlessly. I'll post my current code after the steps.

  1. Let rowSums and colSums be two arrays of length n with entries all zeros. Also, let sumDiagMajor and sumDiagMinor, representing the sum of the entries along the top-left to bottom-right and top-right to bottom-left diagonals, respectively, of the table.

  2. Let index = 0

  3. Repeat until index = n2 (a) Increment rowSums[row] by ArrayList{index} (b) increment colSums[col] by ArrayList{index} (c) If row = col, then increment sumDiagMajor by ArrayList{index}. (d) If row + col = n−1, then increment sumDiagMinor by ArrayList{index} (e) Increment index by 1

  4. If sumDiagMajor is equal to sumDiagMinor and each entry of rowSums and colSums, the the table is a magic square; otherwise, it is not.

   int rowSums[] = new int[_n];
   int colSums[] = new int[_n];
   int sumDiagMajor = 0;
   int sumDiagMinor = 0;

   int row, col;
   row = col = 0;

   for (int index = 0; index < (n*n); index++)
   {          
       rowSums[row] = rowSums[row] + magicSquare.get(index);
       colSums[col] = colSums[col] + magicSquare.get(index);

       if (row == col)
       {       
           sumDiagMajor = sumDiagMajor + magicSquare.get(index);   
       }

       if ((row + col) == (n - 1))
       {
           sumDiagMinor = sumDiagMinor + magicSquare.get(index);   
       }

   }

   System.out.println(sumDiagMajor);
   System.out.println(sumDiagMinor);

My questions include, am I properly incrementing the arrays rowSums, and rowCols? He never actually states what to do with rows or cols, so is initializing them to zero the best option?

If I did everything correct so far, how can sumDiagMajor ever equal sumDiagMinor because rows will always equal cols, so the second nested if statement will never run. Therefore it will rule out everything test as being a magic square?

Sorry for the long post, but this is very confusing.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
sbowde4
  • 767
  • 1
  • 4
  • 23
  • your `magicsquare[]` is a 1-d array of size n * n . I'd advice to create a 2-d array (matrix) of size n * n. Then, problem is self explanatory. – vish4071 Nov 10 '15 at 07:53
  • I think you misunderstood a part of the assignment. "rows will always equal cols" ... what is meant is the index. When you iterate over colIndex and rowIndex it will be (0,0), (0,1), ... (1,0), (2,0) ... so if row = col means (0,0), (1,1), ... then you shall increment sumDiagMajor by the value inside the Matrix at the respective coordinates. Analog for sumDiagMinor. In your for-Loop, you never Change row and col. That's a bug! – Fildor Nov 10 '15 at 07:55
  • @Fildor, yes. And this is because he has taken the `magicsquare[]` as a 1-d array. So, there are actually no rows/cols, its just indices. – vish4071 Nov 10 '15 at 07:57
  • Step 7) `boolean isMagicSquare = Arrays.equals(rowSums, colSums) && sumDiagMajor == sumDiagMinor` – OneCricketeer Nov 10 '15 at 07:58
  • @vish4071 You are right, I just saw this. Didn't look too deep into his code. I'd adivise to make a helper method `getValue(int row, int col)` that translates 2D coords to the 1-D index and Returns the respective value and not use the index directly. – Fildor Nov 10 '15 at 07:59
  • @vish4071 I should have been more specific. The assignment sheet, and our professor said that we must not use an array that is more than one dimension. We can also only use our main class. – sbowde4 Nov 10 '15 at 08:14

2 Answers2

3

As per your updated requirements. A full example.

public static void main(String[] args) {
    List<Integer> magicSquare = Arrays.asList(2,7,6,9,5,1,4,3,8);

    int n = (int) Math.sqrt(magicSquare.size());
    int rowSums[] = new int[n];
    int colSums[] = new int[n];
    int sumDiagMajor = 0;
    int sumDiagMinor = 0;

    int row = -1;
    int col = -1;

    for (int index = 0; index < n*n; index++) {

        col++;
        if (col % n == 0) {
            row++;
            col = 0;
        }

        rowSums[row] = rowSums[row] + magicSquare.get(index);
        colSums[col] = colSums[col] + magicSquare.get(index);


        if (row == col)
        {
            sumDiagMajor += magicSquare.get(index);
        }

        if ((row + col) == (n - 1))
        {
            sumDiagMinor += magicSquare.get(index);
        }

    }

    boolean isMagicSquare = true;
    for (int i = 0; i < n && isMagicSquare; i++) {
        isMagicSquare = sumDiagMajor == rowSums[i] && sumDiagMajor == colSums[i];
    }
    isMagicSquare = isMagicSquare && sumDiagMajor == sumDiagMinor;

    System.out.println(isMagicSquare); // true
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • This looks extremely promising. I would love to implement it right now, but my laptop battery has died so I am using my work computer. I will get it charged ASAP, and hopefully be able to mark this answer as correct. Thank you! – sbowde4 Nov 10 '15 at 08:22
  • @SamBowden - Welcome! I updated that last step to make sure all the values matched. – OneCricketeer Nov 10 '15 at 08:24
  • Couldn't wait so I installed netbeans on my work pc and ran this, played around with the array as well to see if another scenario returned false. Thank you for helping me understand this. – sbowde4 Nov 10 '15 at 08:29
  • @SamBowden - Eh, you had the gist of it. I needed to look up what a magic square was :) That snippet of incrementing rows and columns becomes second nature after dealing with flattened matrices a bunch – OneCricketeer Nov 10 '15 at 08:32
0

You never change row and col in your for-loop which is a bug. For easier understanding, I suggest using two nested for-loops over rowIndex and colIndex and using a little helper to get the value from the 1-D Array like so:

int getValue(int row, int col){
    return magicSquare.get( row * _n + col );
}

Assuming the 1-D Array is a "flattened" square that is built up like (0,0), (0,1), ... (0,_n), (1, 0) , ... (_n,_n)

To make it clearer: Iterate over the square instead of using the index:

for( int row = 0 ; row < _n ; row++){
    for( int col = 0 ; col < _n ; col++){
       // Your stuff here.
    }
}
Fildor
  • 14,510
  • 4
  • 35
  • 67