创建幻方(java)

lx0bsm1f  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(255)

我有点纠结于这个方阵编码项目该怎么办。
每当我尝试输入任何值时,结果总是正确的,方阵就是一个幻方。例如,事实证明:

16 03 02 13
05 10 11 08
09 06 07 12
04 15 14 01

但当我输入如下值时:

03 04 16 02
05 01 02 10
05 08 07 12
03 14 13 09

这应该返回假,但它仍然返回真说,这是一个魔方。
要求是我需要所有的方法
“public void add(int i,int row,int col)”:将整数添加到指定位置的矩阵中。
公众的
“public boolean allinrange”:确定矩阵中的所有值是否在适当的范围内
“public boolean allunique”:确定矩阵中的所有值是否只出现一次
“public boolean ismagic”:确定矩阵是否表示幻方。这意味着:
用户为某些数字n输入了n^2个数字
数字仅介于1和n^2之间(包括1和n^2)
每个数字在矩阵中正好出现一次
每行、每列和两条对角线中的元素之和相等
公共类平方矩阵{

private int[][] array; 

public SquareMatrix(int size) 
{ 
  array = new int[size][size]; 
}

public void add(int i, int row, int column) {array[row][column] = i;} 

//Just checks if the #of rows & columns are between 1-n^2
public boolean allInRange()
{
  int n = array.length;

  for (int row = 0; row < n; row++)
  {
    for (int col = 0; col < array[row].length; col++)
    {
      if (array[row][col] < 1 || array[row][col] > n*n)
        return false; 
    }
  }

  return true;
}

public boolean allUnique()
{
  for (int i =0; i < array.length - 1; i++)
  {
    for (int j = i + 1; j < array.length; j++)
    {
      if(array[i]==array[j])
        return false;
    }
  }
  return true;
}

//Supposed to call the other methods (allInRange & allUnique)
public boolean isMagic()
{

  for(int[] row : array)
  {
    for (int num : row)
    {
      if (num == 0)
        return false;
    }
  }

  boolean range = allInRange();
  if (range == true)
    return true;
  if (range == false)
    return false;

  boolean unique = allUnique();
  if (unique == true)
    return true;
  if (unique == false)
    return false;

  int sumRow;
  int sumCol;
  int sum1 = 0;
  int sum2 = 0;

  //Sum of Left to Right Diaganol
  for (int i = 0; i < array.length; i++)
  {
    sum1 += array[i][i];
  }

  //sum of right to left diaganol
  for (int j = 0; j < array.length; j++)
  {
    sum2 += array[j][array.length-1-j];
  }

  if (sum1 != sum2)
    return false;

  //Sum of Rows
  for (int row = 0; row < array.length; row++)
  {
    sumRow = 0;
    for (int col = 0; col < array[row].length; col++)
      sumRow += array[row][col];

    if (sumRow != sum1)
      return false;
  }

  //Sum of Col
  for (int i = 0; i < array.length; i++)
  {
    sumCol = 0;
    for (int j = 0; j < array.length; j++)
      sumCol = array[j][i];

    if (sumCol != sum1)
      return false;

  }

  return true;    
}

public String toString()
{
  int n = array.length;

  String lol = "";

  for (int[] row : array)
  {
    for (int num : row)
    {
      String hi = String.format("%0"+(n*n+"").length()+"d",num);

      lol += hi + " ";
    }
    lol += "\n";
  }
  return lol;
}

}
这是我的驾驶课

import javax.swing.*;

public class SquareMatrixDriver { 

  public static void main(String[] args) { //My favorite line in history  

    JFrame bot = new JFrame(); //We can use JFrame to read the inputs 

    do 
    {
      //We have to make sure that it is a valid input or else I am doomed
      int size = 0;
      do 
      {
        size = Integer.parseInt(JOptionPane.showInputDialog(bot, "Enter the size of the matrix."));
        if (size < 1) 
        {
          JOptionPane.showMessageDialog(bot, "Invalid size! Enter a number greater than 0.");
        }
      } 
      while(size < 1);

      SquareMatrix matrix = new SquareMatrix(size);

      for (int i=0; i<size; i++) 
      {
        //Gets thhe User's Input

        String[] stringInput;
        do 
        {
          stringInput = JOptionPane.showInputDialog(bot, "Enter the row number" + (i + 1) + ", with " + size + " elements, split by commas.").split(",");
          if (stringInput.length != size) 
          { //In this code we basically enter the numbers with commas
            JOptionPane.showMessageDialog(bot, "Invalid size! " + stringInput.length + " elements entered but " + size + " required.");
          }
        } 
        while(stringInput.length != size);

        int[] intInput = new int[size];
        for (int o=0; o<size; o++) 
        { 

        }

        for (int o=0; o<size; o++) 
        {
          matrix.add(Integer.parseInt(stringInput[o]), i, o); //Here we would put everything into the Matrix
        }
      }

      JOptionPane.showMessageDialog(bot, "The matrix is " + (matrix.isMagic()? "very" : "not") + " correct"); //This line will output if the Matrix works or doesnt work 

      JOptionPane.showMessageDialog(bot, matrix); // Enters out the final output
    } while (JOptionPane.showConfirmDialog(bot, "Do you wish to exit?", "Exit", JOptionPane.YES_NO_OPTION) == 1); //Asks the User if they would like to exit the program
  }
}
gzjq41n4

gzjq41n41#

我可以通过目视检查发现的错误:
allunique()是完全错误的,您必须检查每个数字在矩阵中是否只出现一次,但是您比较的是完全不同的行数组,检查唯一性的最佳方法通常是使用哈希集,但是由于这里有一个非常明确的数字范围(从1到n2),因此可以使用任意n2布尔数组。扫描方阵并测试/设置数组中的相应元素(如果已设置),返回false。

public boolean allUnique() {
  int n=array.length;
  boolean[] set=new boolean[n*n];
  for (int i=0; i < n; i++) {
    for (int j=0;j < n; j++) {
      //Here assuming that you already sucessfully called allInRange, 
      //otherwise we must check bounds to avoid an index out of bounds exception
      if(set[array[i][j]-1]) {
        return false;
      }
      set[array[i][j]-1] = true;
    }
  }
  return true;
}

在方法ismagic()中,所有这部分都是错误和冗余的

boolean range = allInRange();
  if (range == true)
    return true;  //WRONG, this will immediately return with true, without further checks
  if (range == false)
    return false;

  boolean unique = allUnique();
  if (unique == true)
    return true;  //WRONG, same as before
  if (unique == false)
    return false;

把它换成

if (!allInRange()) {
    return false;
}
if (!allUnique()) {
    return false;
}

最后,在ismagic()中,当计算列的和时,缺少加法

sumCol = array[j][i];

必须替换为

sumCol += array[j][i];

相关问题