Issue
class Solution {
/**
* @param n the given positive number
* @return the square matrix of order n according to the given pattern
*/
public static int[][] create(int n) {
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {
matrix[i][j] = 1;
}
}
}
return matrix;
}
// Helper method to print the matrix
public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("\n");
}
public static void main(String[] args) {
// Test cases
int[][] result1 = create(5);
printMatrix(result1);
int[][] result2 = create(6);
printMatrix(result2);
int[][] result3 = create(1);
printMatrix(result3);
int[][] result4 = create(2);
printMatrix(result4);
}
}
Hi everyone,
When I test the code above, it outputs like this:
Unexpected Output
1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1
1 1 1 1 1 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
1
1 1
1 1
However, there are some issues in my code for outputting the correct version of the visibility. It should output like this:
Expected Output
1 0 0 0 1
1 1 0 1 1
1 1 1 1 1
1 1 0 1 1
1 0 0 0 1
1 0 0 0 0 1
1 1 0 0 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 1 0 0 1 1
1 0 0 0 0 1
1
1 1
1 1
And to others, it is correctly outputted.
So how can i output it correctly. Any ideas?
I attempted to run the provided code for visibility calculations. I expected the output to accurately represent the visibility matrix for each scenario. However, upon reviewing the results, I noticed discrepancies in the visibility values. The correct visibility matrix for each case should follow a specific pattern, and I am seeking assistance in identifying and correcting the issues in the code that lead to the incorrect output.
My portfolio If you want to contact.
Solution
public static int[][] create(int size) {
int[][] matrix = new int[size][size];
for (int colLo = 0, colHi = size - 1; colLo <= colHi; colLo++, colHi--) {
for (int rowLo = colLo, rowHi = colHi; rowLo <= rowHi; rowLo++, rowHi--) {
matrix[rowLo][colLo] = 1; matrix[rowLo][colHi] = 1;
matrix[rowHi][colLo] = 1; matrix[rowHi][colHi] = 1;
}
}
return matrix;
}
public static void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
if (col > 0)
System.out.print(' ');
System.out.print(matrix[row][col]);
}
System.out.println();
}
}
public static void main(String... args) {
for (int size = 1; size < 7; size++) {
printMatrix(create(size));
System.out.println();
}
}
Output:
1
1 1
1 1
1 0 1
1 1 1
1 0 1
1 0 0 1
1 1 1 1
1 1 1 1
1 0 0 1
1 0 0 0 1
1 1 0 1 1
1 1 1 1 1
1 1 0 1 1
1 0 0 0 1
1 0 0 0 0 1
1 1 0 0 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 1 0 0 1 1
1 0 0 0 0 1
Answered By - Oleg Cherednik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.