-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathExercise08_22.java
55 lines (51 loc) · 1.66 KB
/
Exercise08_22.java
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
package ch_08;
import java.util.*;
/**
* *8.22 (Even number of 1s) Write a program that generates a 6-by-6 two-dimensional
* matrix filled with 0s and 1s, displays the matrix, and checks if every row and
* every column have an even number of 1s.
*
* @author Harry D.
*/
public class Exercise08_22 {
public static void main(String[] args) {
int[][] a = new int[6][6];
fillZeroAndOnes(a);
//Rows check
for (int j = 0; j < a.length; j++) {
int numOnes = 0;
for (int i : a[j]) {
if (i == 1) numOnes++;
}
System.out.print("Row # " + (j + 1) + " ");
if (numOnes % 2 == 0 && numOnes != 0) {
System.out.print(" has an even number of ones. ");
}
System.out.println(Arrays.toString(a[j]));
}
int [] colNums = new int[6];
//Columns check
for (int y = 0; y < 6; y++) {
int numOnes = 0;
for (int x = 0; x < 6; x++) {
colNums[x] = a[x][y];
if (a[x][y] == 1) numOnes++;
}
System.out.print("Column # " + (y + 1) + " ");
if (numOnes % 2 == 0 && numOnes != 0) {
System.out.print("has an even number of ones. ");
}
System.out.println(Arrays.toString(colNums));
}
}
static void fillZeroAndOnes(int[][] arr) {
for (int i = 0; i < arr.length; i += getRandom()) {
for (int j = 0; j < arr[i].length; j += getRandom()) {
arr[i][j] = 1;
}
}
}
static int getRandom() {
return (int) (0.5 + Math.random() * 3);
}
}