-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathLadderGame.java
More file actions
55 lines (43 loc) · 1.53 KB
/
LadderGame.java
File metadata and controls
55 lines (43 loc) · 1.53 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
package model;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class LadderGame {
private final Ladder ladder;
private final int positions;
public LadderGame(Ladder ladder, int width) {
this.ladder = ladder;
this.positions = width;
}
public Map<String, String> playAll(List<String> participants, List<String> results) {
Map<String, String> allResults = new LinkedHashMap<>();
for (int i = 0; i < participants.size(); i++) {
int finalPosition = play(i);
allResults.put(participants.get(i), results.get(finalPosition));
}
return allResults;
}
public String getResult(String name, List<String> participants, List<String> results) {
int startIndex = participants.indexOf(name);
int finalPosition = play(startIndex);
return results.get(finalPosition);
}
public int play(int startPosition) {
int currentPosition = startPosition;
List<Line> lines = ladder.lines();
for (Line line : lines) {
currentPosition = moveOnLine(currentPosition, line);
}
return currentPosition;
}
private int moveOnLine(int position, Line line) {
List<Point> points = line.points();
if (position > 0 && points.get(position - 1).isConnected()) {
return position - 1;
}
if (position < points.size() && points.get(position).isConnected()) {
return position + 1;
}
return position;
}
}