-
Notifications
You must be signed in to change notification settings - Fork 830
Expand file tree
/
Copy pathCars.java
More file actions
73 lines (58 loc) · 1.93 KB
/
Copy pathCars.java
File metadata and controls
73 lines (58 loc) · 1.93 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
package racingcar.domain;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static racingcar.constant.ErrorMessage.*;
public class Cars {
private static final int MINIMUMSIZE_CARS_COUNT = 2;
private List<Car> cars;
private final NumberGenerator numberGenerator;
public Cars(String rawNames, NumberGenerator numberGenerator) {
List<String> carNames = parseNames(rawNames);
validateList(carNames);
this.cars = carNames.stream()
.map(name -> new Car(name))
.toList();
this.numberGenerator = numberGenerator;
}
private List<String> parseNames(String rawNames) {
return Arrays.stream(rawNames.split(",")).toList();
}
private void validateList(List<String> names) {
validateMinimumSize(names);
validateDuplicates(names);
}
private void validateMinimumSize(List<String> names) {
if (names.size() < MINIMUMSIZE_CARS_COUNT) {
throw new IllegalArgumentException(ERROR_CAR_COUNT_TOO_SMALL);
}
}
private void validateDuplicates(List<String> names) {
Set<String> uniqueNames = new HashSet<>(names);
if (uniqueNames.size() != names.size()) {
throw new IllegalArgumentException(ERROR_CAR_NAME_DUPLICATE);
}
}
public void moveAllCars() {
for (Car car : cars) {
int randomNumber = numberGenerator.pickNumber();
car.move(randomNumber);
}
}
public List<Car> getCars() {
return cars;
}
public List<Car> findWinners() {
int maxPosition = findMaxPosition();
return cars.stream()
.filter(car -> car.getPosition() == maxPosition)
.toList();
}
private int findMaxPosition() {
return cars.stream()
.mapToInt(Car::getPosition)
.max()
.orElse(0);
}
}