-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathBaseballGameNumber.java
More file actions
69 lines (51 loc) · 1.74 KB
/
BaseballGameNumber.java
File metadata and controls
69 lines (51 loc) · 1.74 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
package model;
import java.util.ArrayList;
import java.util.Objects;
public class BaseballGameNumber {
private final ArrayList<Integer> number;
public BaseballGameNumber(ArrayList<Integer> arr) {
this.number = arr;
}
public GameAnswerType compare(BaseballGameNumber other) {
int strikes = calStrikes(other);
int balls = calBalls(strikes, other);
return new GameAnswerType(strikes, balls);
}
private int calStrikes(BaseballGameNumber other) {
int strike = 0;
for (int i = 0; i < this.number.size(); i++) {
if(isStrike(i, other)) {
strike += 1;
}
}
return strike;
}
private int calBalls(int strikes, BaseballGameNumber other) {
return this.calMatchCount(other) - strikes;
}
private boolean isStrike(int index, BaseballGameNumber other) {
return Objects.equals(this.number.get(index), other.number.get(index));
}
private int calMatchCount(BaseballGameNumber other) {
boolean[] originFlags = this.getNumberFlags();
boolean[] otherFlags = other.getNumberFlags();
int matchCount = 0;
for (int i = 0; i < originFlags.length; i++) {
matchCount = getMatchCount(originFlags, i, otherFlags, matchCount);
}
return matchCount;
}
private static int getMatchCount(boolean[] originFlags, int i, boolean[] otherFlags, int matchCount) {
if(originFlags[i] && otherFlags[i]) {
matchCount += 1;
}
return matchCount;
}
private boolean[] getNumberFlags() {
boolean[] flags = new boolean[10];
for (int num : this.number) {
flags[num] = true;
}
return flags;
}
}