Skip to content

Commit ad13571

Browse files
committed
gray code
1 parent f13ad5b commit ad13571

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

PuzzleCoding/src/GrayCode.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* Created with IntelliJ IDEA.
3+
* Print the N-bit binary reflected Gray code using recursion.
4+
* <p/>
5+
* Gray Code of 3:
6+
* 000
7+
* 001
8+
* 011
9+
* 010
10+
* 110
11+
* 111
12+
* 101
13+
* 100
14+
*/
15+
public class GrayCode {
16+
public static void main(String[] args) {
17+
int N = 3;
18+
grayCode(N, new boolean[N]);
19+
}
20+
21+
public static void grayCode(int n, boolean[] show) {
22+
if (n == 0) {
23+
showCode(show);
24+
} else {
25+
show[n - 1] = false;
26+
grayCode(n - 1, show);
27+
show[n - 1] = true;
28+
yargCode(n - 1, show);
29+
}
30+
31+
}
32+
33+
// append reverse of order n gray code
34+
public static void yargCode(int n, boolean[] show) {
35+
if (n == 0) {
36+
showCode(show);
37+
} else {
38+
show[n - 1] = true;
39+
grayCode(n - 1, show);
40+
show[n - 1] = false;
41+
yargCode(n - 1, show);
42+
}
43+
}
44+
45+
public static void showCode(boolean[] show) {
46+
String code = "";
47+
for (boolean yes : show) {
48+
if (yes)
49+
code = "1" + code;
50+
else
51+
code = "0" + code;
52+
}
53+
System.out.println(code);
54+
// System.out.println(Integer.parseInt(code, 2));
55+
}
56+
57+
}

allSubsets/src/allSubsets.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
public class allSubsets{
55
public static void main(String[] args){
6-
int[] a = {1,2,3,4};
6+
int[] a = {1,2,3};
77
ArrayList<ArrayList<Integer>> allsubsets = new ArrayList<ArrayList<Integer>>();
88
System.out.println("take subset:");
99
allsubsets = genSubsets(a, 0);

0 commit comments

Comments
 (0)