gpt4 book ai didi

java - 为 Magic Square Java 测试 .txt 文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:42:02 25 4
gpt4 key购买 nike

我不想问,但我想不通这个作业,当我寻求帮助时,助教也想不通。

我必须从一个文本文件中获取输入,将文件中的整数输入到一个数组列表中,然后测试它是否是一个 n x n 幻方。 n 等于数组列表长度的平方根。如果它不是一个完美的正方形,它会立即无法通过魔方测试。

无论如何我已经快完成了;我似乎不明白我的教授在魔方测试的最后一步告诉/要求我们做什么。

最后四个步骤之前的所有测试都完美无缺。我将在完成这些步骤后发布我当前的代码。

  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);

我的问题包括,我是否正确递增了数组 rowSums 和 rowCols?他从未真正说明如何处理行或列,那么将它们初始化为零是最佳选择吗?

如果到目前为止我所做的一切都是正确的,sumDiagMajor 怎么会等于 sumDiagMinor,因为行总是等于 cols,所以第二个嵌套的 if 语句将永远不会运行。因此它会排除所有测试都是幻方吗?

抱歉发了这么长的帖子,但这很困惑。

最佳答案

根据您更新后的要求。一个完整的例子。

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
}

关于java - 为 Magic Square Java 测试 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33625056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com