-
Notifications
You must be signed in to change notification settings - Fork 738
Expand file tree
/
Copy pathLine.java
More file actions
85 lines (71 loc) · 1.86 KB
/
Line.java
File metadata and controls
85 lines (71 loc) · 1.86 KB
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
package nextstep.ladder.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Line {
private static final int MOVE_LEFT = -1;
private static final int NO_MOVE = 0;
private static final int MOVE_RIGHT = 1;
private final List<Bridge> bridges = new ArrayList<>();
public Line(final Generator generator, final int numberOfPeople) {
while (bridges.size() < numberOfPeople - 1){
final boolean now = generator.generate();
addBridge(Bridge.from(now));
}
}
public int move(final int column) {
int leftMove = checkLeftBridge(column);
int rightMove = checkRightBridge(column);
return leftMove != NO_MOVE ? leftMove : rightMove;
}
private Integer checkRightBridge(int column) {
final Bridge rightBridge = getBridgeAtIndex(column);
if (rightBridge.isBridge()) {
return MOVE_RIGHT;
}
return NO_MOVE;
}
private Integer checkLeftBridge(int column) {
final Bridge leftBridge = getBridgeAtIndex(column - 1);
if (leftBridge.isBridge()) {
return MOVE_LEFT;
}
return NO_MOVE;
}
private void addBridge(final Bridge now) {
if (bridges.isEmpty()) {
bridges.add(now);
return;
}
if (getBridgeAtIndex(bridges.size() - 1).isBridge()) {
bridges.add(Bridge.from(false));
return;
}
bridges.add(now);
}
public List<Bridge> getBridges() {
return bridges;
}
private Bridge getBridgeAtIndex(final int index) {
if (isIndexWithinBounds(index)) {
return bridges.get(index);
}
return Bridge.NON_BRIDGE;
}
private boolean isIndexWithinBounds(int index) {
return index >= 0 && index < bridges.size();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Line line = (Line)o;
return Objects.equals(bridges, line.bridges);
}
@Override
public int hashCode() {
return Objects.hash(bridges);
}
}