Write a program that reads in n2 values from the keyboard and tests to see if they form…
- User
Write a program that reads in n2 values from the keyboard and tests to see if they form a magic square when arranged in a square matrix. You need to test for three conditions: Did the user enter n2 numbers for some n? Do each of the numbers 1, 2, 3….n2 occur exactly once in the user input? When put into a square, are the sums of the rows, columns and diagonals equal to each other?
IF the size of the input is a square, then test whether all numbers between 1 and n2 are present. Then compute the row, column and diagonal sums. Implement a class Square with methods public void add(int i) public boolean isMagic()
- Assistant
- User
don't use arraylist or hash set
- Assistant
- User
don't use .add
- Assistant
- User
don't use ? :
- Assistant
- User
is there an issue in my code public class MyProgram { private int[][] matrix; private int size; private int currentIndex = 0; public Square(int n) { this.size = n; this.matrix = new int[n][n]; } public void initializeMatrix(int[] values) { for (int value : values) { if (currentIndex < size * size) { int row = currentIndex / size; int col = currentIndex % size; matrix[row][col] = value; currentIndex++; } } }
public boolean isMagic() { int nSquared = size * size; int[] numberTracker = new int[nSquared]; int magicSum = size * (nSquared + 1) / 2; int[] rowSums = new int[size]; int[] colSums = new int[size]; int diagSum1 = 0, diagSum2 = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { int value = matrix[i][j]; if (value < 1 || value > nSquared) { return false; } numberTracker[value - 1]++; rowSums[i] += value; colSums[j] += value; if (i == j) { diagSum1 += value; } if (i + j == size - 1) { diagSum2 += value; } } } for (int count : numberTracker) { if (count != 1) { return false; } } if (diagSum1 != magicSum || diagSum2 != magicSum) { return false; } for (int sum : rowSums) { if (sum != magicSum) { return false; } } for (int sum : colSums) { if (sum != magicSum) { return false; } } return true; } public static void main(String[] args) { Square square = new Square(3); int[] inputs = {2, 7, 6, 9, 5, 1, 4, 3, 8}; square.initializeMatrix(inputs); if(square.isMagic()) { System.out.println("The square is a magic square."); } else { System.out.println("The square is not a magic square."); } } - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.