-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathboardPathWithLadders.java
93 lines (70 loc) Β· 1.7 KB
/
boardPathWithLadders.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
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
package Lecture13;
public class boardPathWithLadders {
public static void main(String[] args) {
int boardLen = 10;
boolean[] primes = new boolean[boardLen+1];
for (int position = 0; position < primes.length; position++) {
if (checkPrime(position)) {
primes[position] = true;
}
}
int[] ladders = makeLadder(boardLen, primes);
System.out.println("ladder is : ");
display(ladders);
int current = 0;
String result = "";
System.out.println("\nall possible board paths: ");
boardPath(ladders, current, boardLen, result);
}
public static boolean checkPrime(int index) {
if (index < 2) {
return false;
}
for (int pos = 2; pos <= index / 2; pos++) {
if (index % pos == 0) {
return false;
}
}
return true;
}
public static int[] makeLadder(int n, boolean[] primes) {
int[] ladder = new int[n + 1];
int front = 0, back = ladder.length - 1;
// two pointer approach
while (front < back) {
while (primes[front] != true) {
front++;
}
while (primes[back] != true) {
back--;
}
ladder[front] = back;
ladder[back] = front;
front++;
back--;
}
return ladder;
}
public static void boardPath(int[] ladder, int curr, int end, String result) {
if (curr == end) {
System.out.println(result);
return;
}
if (curr > end) {
return;
}
if (ladder[curr] != 0 && curr < ladder[curr]) {
boardPath(ladder, ladder[curr], end, result + ladder[curr]);
} else {
for (int dice = 1; dice <= 6; dice++) {
boardPath(ladder, curr + dice, end, result + dice);
}
}
}
public static void display(int[] list) {
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.println();
}
}