-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCogwheel.java
93 lines (76 loc) · 2.81 KB
/
Cogwheel.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
import java.io.PrintWriter;
import java.security.InvalidParameterException;
import java.util.function.Predicate;
public class Cogwheel<T> {
private CycleList<T> list;
private T starter;
private Cogwheel<T> next;
private StringBuilder sequence;
public Cogwheel(CycleList<T> list) {
this.list = list;
this.starter = this.list.getData();
}
public Cogwheel(int length, CycleList<T> list) {
this(list);
if (length <= 0) throw new InvalidParameterException("The first parameter should be a positive interger.");
Cogwheel<T> save;
StringBuilder str = new StringBuilder();
for (int i = 1; i < length; i++) {
save = this.next;
this.next = new Cogwheel<>(list.copy());
this.next.sequence = new StringBuilder(str.toString());
this.next.next = save;
str.append(this.next.list.getData());
}
this.sequence = new StringBuilder(str);
}
@Override
public String toString() {
Cogwheel current = this;
StringBuilder str = new StringBuilder();
while (current != null) {
str.append(current.list.toString());
str.append("\n");
current = current.next;
}
return str.toString();
}
public StringBuilder getSequence() {
return this.sequence;
}
public StringBuilder getFullSequence() {
StringBuilder str = new StringBuilder(this.list.getData().toString());
str.append(this.getSequence());
return str;
}
public void updateSequence() {
this.sequence = new StringBuilder(this.next.list.getData().toString());
this.sequence.append(this.next.getSequence()); // Saving time
}
public void turn() {
this.list = this.list.getNext();
if (this.next != null && this.list.getData().equals(this.starter)) {
this.next.turn();
this.updateSequence();
}
}
public void action(PrintWriter writer) {
StringBuilder first = this.getFullSequence();
StringBuilder strb = new StringBuilder(first.toString());
do {
writer.println(strb.toString());
this.turn();
strb = this.getFullSequence();
} while(!strb.toString().equals(first.toString()));
}
public StringBuilder action(Predicate<String> pred) {
StringBuilder first = this.getFullSequence();
StringBuilder strb = new StringBuilder(first.toString());
do {
if (pred.test(strb.toString())) return strb;
this.turn();
strb = this.getFullSequence();
} while(!strb.toString().equals(first.toString()));
return null;
}
}