forked from JaeHongDev/java-baseball
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalls.java
More file actions
68 lines (55 loc) · 1.88 KB
/
Copy pathBalls.java
File metadata and controls
68 lines (55 loc) · 1.88 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
package baseball.model;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Balls {
public static final int SIZE = 3;
private final List<Ball> balls;
public static Balls from(List<Integer> numbers) {
List<Ball> ballList = IntStream.range(0, numbers.size())
.mapToObj(i -> Ball.from(numbers.get(i), i))
.collect(Collectors.toList());
return new Balls(ballList);
}
public Balls(List<Ball> balls) {
validate(balls);
this.balls = balls;
}
private void validate(List<Ball> balls) {
validateSize(balls);
validateDuplication(balls);
}
private void validateSize(List<Ball> balls) {
if (balls.size() != SIZE) {
throw new IllegalArgumentException();
}
}
private void validateDuplication(List<Ball> balls) {
long uniqueBallsCount = balls.stream()
.map(Ball::getNumber)
.distinct()
.count();
if (uniqueBallsCount != SIZE) {
throw new IllegalArgumentException();
}
}
public GameResult compare(Balls other) {
int ballCount = countFiltered(other, this::ballPredicate);
int strikeCount = countFiltered(other, this::strikePredicate);
return GameResult.of(ballCount, strikeCount);
}
private int countFiltered(Balls other, Predicate<Ball> predicate) {
return (int) other.balls.stream()
.filter(predicate)
.count();
}
private boolean ballPredicate(Ball otherBall) {
return balls.stream()
.anyMatch(ball -> ball.isBall(otherBall));
}
private boolean strikePredicate(Ball otherBall) {
return balls.stream()
.anyMatch(ball -> ball.isStrike(otherBall));
}
}