验证一组数字是否magic square

来源:互联网 发布:php集成环境包 编辑:程序博客网 时间:2024/06/07 21:51

以下是「Core Java for the Impatient」一书第一章的第14道习题及解答。
题目:

Write a program that reads a two-dimensional array of integers and determines whether it is a magic square (that is, whether the sum of all rows, all columns, and the diagonals is the same). Accept lines of input that you break up into individual integers, and stop when the user enters a blank line. For example, with the input

16   3   2  13 5  10  11   8 9   6   7  12 4  15  14   1(Blank line) 

your program should respond affirmatively.

解答:
思路
1. 使用元素是数组的ArrayList组装成square,把square的每一行、每一列、每一对角线都当成一个line来处理
2. 先计算第一行的和,然后依次扫描计算剩余的行、列和对角线的和,只要有不等于第一行和的,就认定不是magic square
代码

import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class Solution14 {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        String line = "";        ArrayList<int[]> square = new ArrayList<>();        while (!"".equals(line = in.nextLine())) {            square.add(processLine(line));        }        in.close();        System.out.println(isMagic(square) ? "is a magic square." : "is not a magic square.");    }    public static int[] processLine(String s) {        String[] splitted = s.trim().split("\\s+");        int[] line = new int[splitted.length];        for (int i = 0; i < line.length; i++) {            line[i] = Integer.parseInt(splitted[i]);        }        return line;    }    public static int addLine(int[] line) {        int sum = 0;        for (int i = 0; i < line.length; i++) {            sum += line[i];        }        return sum;    }    public static boolean isMagic(List<int[]> square) {        int sumOfRow1 = addLine(square.get(0));        int[] diagonal = new int[square.size()];        int[] inverseDiagonal = new int[square.size()];        for (int i = 0; i < square.size(); i++) {            int[] row = square.get(i);            // 每一行的长度相当于列数,行数与列数不想等必然不是magic square            if (row.length != square.size()) {                return false;            }            if (addLine(row) != sumOfRow1) {                return false;            }            // 构造对角线的line            diagonal[i] = row[i];            inverseDiagonal[row.length - 1 - i] = row[row.length - 1 - i];        }        // 构造每一列的line,相当于依次从每一行k取相同位置j的元素        for (int j = 0; j < square.size(); j++) {            int[] column = new int[square.size()];            for (int k = 0; k < square.size(); k++) {                column[k] = square.get(k)[j];            }            if (addLine(column) != sumOfRow1) {                return false;            }        }        if (addLine(diagonal) != sumOfRow1) {            return false;        }        if (addLine(inverseDiagonal) != sumOfRow1) {            return false;        }        return true;    }}
原创粉丝点击