-
Notifications
You must be signed in to change notification settings - Fork 708
/
Copy pathLadder.java
87 lines (65 loc) · 2.68 KB
/
Ladder.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
package ladder.domain;
import java.util.Objects;
import java.util.stream.IntStream;
public class Ladder {
private final Participants participants;
private final Lines lines;
public Ladder(final Participants participants, final Lines lines) {
validateOrThrow(participants, lines);
this.participants = participants;
this.lines = lines;
}
public Participants getParticipants() {
return new Participants(participants);
}
public int getHeight() {
return this.lines.height();
}
public Lines getLines() {
return this.lines;
}
public Line getLine(final int index) {
return this.lines.getLines()
.get(index);
}
public int getLastVerticalLineIndex(final Participant participant) {
return this.getLastVerticalLineIndex(this.participants.indexOf(participant));
}
private int getLastVerticalLineIndex(final int firstVerticalLineIndex) {
return IntStream.range(0, this.lines.height())
.reduce(firstVerticalLineIndex, (curVerticalLineIndex, curLineHeight) -> {
if (canMoveLeft(curVerticalLineIndex, curLineHeight)) {
return curVerticalLineIndex - 1;
}
if (canMoveRight(curVerticalLineIndex, curLineHeight)) {
return curVerticalLineIndex + 1;
}
return curVerticalLineIndex;
});
}
private boolean canMoveLeft(final int verticalLineIndex, final int curLineHeight) {
if (isFirstVerticalLineIndex(verticalLineIndex)) {
return false;
}
return this.lines.getLine(curLineHeight)
.isConnected(verticalLineIndex - 1);
}
private boolean canMoveRight(final int verticalLineIndex, final int curLineHeight) {
if (isLastVerticalLineIndex(verticalLineIndex)) {
return false;
}
return this.lines.getLine(curLineHeight)
.isConnected(verticalLineIndex);
}
private boolean isFirstVerticalLineIndex(final int verticalLineIndex) {
return verticalLineIndex == 0;
}
private boolean isLastVerticalLineIndex(final int verticalLineIndex) {
return verticalLineIndex == this.lines.width();
}
private void validateOrThrow(final Participants participants, final Lines lines) {
if (Objects.isNull(participants) || Objects.isNull(lines)) {
throw new IllegalArgumentException("참가자나 사다리 라인은 null이 될 수 없습니다.");
}
}
}