Write a program to form a square Matrix of characters and display the row and column having the max valued characters .
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static void main(String[] args) {
int size = 5;
char[][] matrix = generateRandomMatrix(size);
System.out.println("Matrix:");
displayMatrix(matrix);
int[] maxIndices = findMaxValueIndices(matrix);
int maxRow = maxIndices[0];
int maxCol = maxIndices[1];
System.out.println("\nRow and column with maximum valued character:");
System.out.println("Row: " + maxRow);
System.out.println("Column: " + maxCol);
}
public static char[][] generateRandomMatrix(int size)
{
char[][] matrix = new char[size][size];
Random random = new Random();
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
matrix[i][j] = (char) (random.nextInt(26) + 'A');
}
}
return matrix;
}
public static void displayMatrix(char[][] matrix)
{
int size = matrix.length;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
System.out.print(matrix[i][j] + " " );
}
System.out.println();
}
}
public static int[] findMaxValueIndices(char[][] matrix)
{
int size = matrix.length;
int maxRow = 0;
int maxCol = 0;
int maxValue = matrix[maxRow][maxCol];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (matrix[i][j] > maxValue)
{
maxRow = i;
maxCol = j;
maxValue = matrix[i][j];
}
}
}
return new int[] { maxRow, maxCol };
}
}
Matrix:
L T B G E
R I K G Q
W R L O D
S X V O B
B Y U O G
Row and column with maximum valued character:
Row: 4
Column: 1
No comments:
Post a Comment