Newer
Older
import java.util.Random;
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
74
75
76
77
public static final int CODE_LENGTH = 4;
public static char[] COLORS = new char[]{'B','G','O','R','W','Y'};
private final char[] codeWord = new char[CODE_LENGTH];
public Code(Random random){
for (int i = 0; i < CODE_LENGTH; i++) {
codeWord[i] = COLORS[random.nextInt(COLORS.length)];
}
}
public Code(String codeString){
assert(codeString.length() == CODE_LENGTH);
for(int i=0; i<CODE_LENGTH; i++)
codeWord[i] = codeString.charAt(i);
}
@Override
public String toString() {
return new String(codeWord);
}
/**
* return the number of colors of guess that are correctly positioned
*/
public int numberOfColorsWithCorrectPosition(Code guess){
int count = 0;
for(char color : COLORS){
count += numberOfMatches(color, guess);
}
return count;
}
/**
* return the number of colors of guess that are in this codeWord
* but do not have the correct position
*/
public int numberOfColorsWithIncorrectPosition(Code guess){
int count = 0;
for(char color:COLORS){
int nMatchedOccurrences = numberOfMatches(color, guess);
int nUnmatchedOccurrencesCode = numberOfOccurrences(color, this) - nMatchedOccurrences;
int nUnmatchedOccurrencesGuess = numberOfOccurrences(color, guess) - nMatchedOccurrences;
count += Math.min(nUnmatchedOccurrencesCode, nUnmatchedOccurrencesGuess);
}
return count;
}
private int numberOfOccurrences(char color, Code code){
int count = 0;
for (int i = 0; i < CODE_LENGTH; i++) {
if (code.codeWord[i] == color) count++;
}
return count;
}
private int numberOfMatches(char color, Code guess){
int count = 0;
for (int i = 0; i < CODE_LENGTH; i++) {
if ((this.codeWord[i] == guess.codeWord[i]) && (this.codeWord[i] == color)){
count++;
}
}
return count;
}
@Override
public boolean equals(Object o){
if (o == null) return false;
if (!(o instanceof Code)) return false;
return this.toString().equals(o.toString());
}