Repository navigation
Expand file tree
/
Copy pathscoreAfterFlipping.java
More file actions
51 lines (48 loc) · 1.79 KB
/
Copy pathscoreAfterFlipping.java
File metadata and controls
51 lines (48 loc) · 1.79 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
//Question: We have to take a binary matrix and flip its rows or columns so that the score will be maximum.
// eg: [0 0 1] flip first row [1 1 0] flip second column [1 0 0] flip third column [1 0 1]
// [1 0 0] -> [1 0 0] -> [1 1 0] -> [1 1 1] (Ans)
// [1 0 0] [1 0 0] [1 1 0] [1 1 1]
package twoDArray;
public class scoreAfterFlipping {
public static void main(String[] args) {
int [][] arr={{0, 0, 1},{1, 0, 0},{1, 0, 0}};
// ROW FLIPPING
// Checking if there are any '0's int the first column
int pos = 0;
for (int i = 0; i < arr.length; i++) {
int j=0; //(First column)
if(arr[i][j]==0){
pos=i;
}
for (int j2 = 0; j2 < arr[0].length; j2++) {
if(arr[pos][j2]==0){
arr[pos][j2]=1; // Flipping the row whose first element is 0
}else{
arr[pos][j2]=0;
}
}
}
// COLUMN FLIPPING
for(int j=1; j<arr[0].length; j++){
int no_of_zeros=0, no_of_ones=0;
for (int i = 0; i < arr.length; i++) {
if(arr[i][j]==0) no_of_zeros++;
if(arr[i][j]==1) no_of_ones++;
} if(no_of_zeros>no_of_ones){
for (int i = 0; i < arr.length; i++) {
if(arr[i][j]==0){
arr[i][j]=1; // Flipping the columns who have greater number of 0s than 1s
}else{
arr[i][j]=0;
}
}
}
}
// PRINT THE NEW ARRAY
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j]+" ");
}System.out.println();
}
}
}