-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestRowColumn.java
More file actions
98 lines (84 loc) · 2.98 KB
/
LargestRowColumn.java
File metadata and controls
98 lines (84 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.*;
public class LargestRowColumn {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the array size n: ");
int n = 0;
// Ensure input is an integer
if (input.hasNextInt()) {
n = input.nextInt();
} else {
System.out.println("Invalid input. Please enter an integer.");
return;
}
// Create matrix with random 0s and 1s
int[][] matrix = new int[n][n];
Random random = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = random.nextInt(2);
}
}
// Print matrix
System.out.println("The random array is");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]);
}
System.out.println();
}
// Find and print rows with the most 1s
ArrayList<Integer> largestRowIndices = getLargestRowIndices(matrix);
System.out.print("The largest row index: ");
for (int index : largestRowIndices) {
System.out.print(index + " ");
}
System.out.println();
// Find and print columns with the most 1s
ArrayList<Integer> largestColumnIndices = getLargestColumnIndices(matrix);
System.out.print("The largest column index: ");
for (int index : largestColumnIndices) {
System.out.print(index + " ");
}
System.out.println();
input.close();
}
// Method to find rows with the most 1s
private static ArrayList<Integer> getLargestRowIndices(int[][] matrix) {
int maxRowOnes = 0;
ArrayList<Integer> rowIndex = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
int rowOnes = 0;
for (int j = 0; j < matrix[i].length; j++) {
rowOnes += matrix[i][j];
}
if (rowOnes > maxRowOnes) {
maxRowOnes = rowOnes;
rowIndex.clear();
rowIndex.add(i);
} else if (rowOnes == maxRowOnes) {
rowIndex.add(i);
}
}
return rowIndex;
}
// Method to find columns with the most 1s
private static ArrayList<Integer> getLargestColumnIndices(int[][] matrix) {
int maxColumnOnes = 0;
ArrayList<Integer> columnIndex = new ArrayList<>();
for (int j = 0; j < matrix[0].length; j++) {
int columnOnes = 0;
for (int[] ints : matrix) {
columnOnes += ints[j];
}
if (columnOnes > maxColumnOnes) {
maxColumnOnes = columnOnes;
columnIndex.clear();
columnIndex.add(j);
} else if (columnOnes == maxColumnOnes) {
columnIndex.add(j);
}
}
return columnIndex;
}
}