-
Notifications
You must be signed in to change notification settings - Fork 828
Expand file tree
/
Copy pathCars.java
More file actions
59 lines (47 loc) · 1.52 KB
/
Copy pathCars.java
File metadata and controls
59 lines (47 loc) · 1.52 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
package racingcar.domain;
import racingcar.util.RandomNumberGenerator;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Cars {
private static final int RANDOM_MIN = 0;
private static final int RANDOM_MAX = 9;
private final List<Car> cars;
public Cars(List<Car> cars) {
validateNoDuplicateNames(cars);
this.cars = List.copyOf(cars);
}
private void validateNoDuplicateNames(List<Car> cars) {
long uniqueNameCount = cars.stream()
.map(Car::getName)
.distinct()
.count();
if (uniqueNameCount != cars.size()) {
throw new IllegalArgumentException("자동차 이름은 중복될 수 없습니다.");
}
}
public void moveAll() {
for (Car car : cars) {
int random = RandomNumberGenerator.generateInRange(RANDOM_MIN, RANDOM_MAX);
car.move(random);
}
}
public List<Car> getCars() {
return Collections.unmodifiableList(cars);
}
public List<Car> getWinners() {
int maxPosition = findMaxPosition();
return findCarsWithPosition(maxPosition);
}
private int findMaxPosition() {
return cars.stream()
.mapToInt(Car::getPosition)
.max()
.orElse(0);
}
private List<Car> findCarsWithPosition(int position) {
return cars.stream()
.filter(car -> car.getPosition() == position)
.toList();
}
}