Testing a .txt file for a Magic Square Java

此生再无相见时 提交于 2019-11-29 16:07:06

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
}

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.
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!