小能豆

Java array without using method

javascript

Find the plus sign shape by the same digits that are inline with each other (X and Y axis). In this case, the length of the sides of the plus sign do not need to be equal wherein some sides may be longer or shorter than the others. The size of the plus sign is equal to the largest length of its sides. Find the center of the biggest plus (+) sign. If there are more than one biggest plus (+) signs, choose the one with the smaller row instead. If there are still more than one, choose the one with the smaller column. In case with the same number of rows and columns choose the first row.

Sample output:

Enter Number of rows: 5
Enter Number of columns: 5
4 2 5 4 7
4 3 5 2 1
4 5 5 5 5
3 2 5 3 8
2 1 5 1 1
The biggest plus sign’s is at position [2][2]

Trying to find the exact code in java


阅读 79

收藏
2023-11-20

共1个答案

小能豆

Certainly! Below is a Java code snippet that fulfills the described requirements:

import java.util.Scanner;

public class BiggestPlusSign {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter Number of rows: ");
        int rows = scanner.nextInt();

        System.out.print("Enter Number of columns: ");
        int cols = scanner.nextInt();

        int[][] matrix = new int[rows][cols];

        System.out.println("Enter matrix elements:");

        // Input matrix elements
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                matrix[i][j] = scanner.nextInt();
            }
        }

        // Find the biggest plus sign
        int maxSize = 0;
        int centerRow = 0;
        int centerCol = 0;

        for (int i = 1; i < rows - 1; i++) {
            for (int j = 1; j < cols - 1; j++) {
                if (matrix[i][j] == matrix[i - 1][j] && matrix[i][j] == matrix[i + 1][j]
                        && matrix[i][j] == matrix[i][j - 1] && matrix[i][j] == matrix[i][j + 1]) {
                    int currentSize = Math.min(Math.min(i, rows - 1 - i), Math.min(j, cols - 1 - j));
                    if (currentSize > maxSize) {
                        maxSize = currentSize;
                        centerRow = i;
                        centerCol = j;
                    }
                }
            }
        }

        System.out.println("The biggest plus sign’s is at position [" + centerRow + "][" + centerCol + "]");
    }
}

This Java program takes the number of rows and columns as input, then takes the matrix elements. It iterates through the matrix to find the biggest plus sign based on the given conditions and prints the position of its center.

2023-11-20