-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoogleQ4.java
More file actions
50 lines (43 loc) · 1.67 KB
/
GoogleQ4.java
File metadata and controls
50 lines (43 loc) · 1.67 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
public class GoogleQ4 {
public String getHint(String secret, String guess) {
int cows = 0;
int bulls = 0;
String copyStr = new String(guess);
for (int i = 0; i < secret.length(); i++) {
Character ch = secret.charAt(i);
if (ch == guess.charAt(i)) {
int index = copyStr.indexOf(ch);
copyStr = copyStr.substring(0, i) + "*" + copyStr.substring(i + 1);
bulls++;
} else if (copyStr.contains(Character.toString(ch))) {
boolean found = false;
while (true) {
int index = copyStr.indexOf(ch);
if (index < 0) {
break;
}
if (secret.charAt(index) == copyStr.charAt(index)) {
copyStr = copyStr.substring(0, index) + "*" + copyStr.substring(index + 1);
continue;
}
copyStr = copyStr.substring(0, index) + "*" + copyStr.substring(index + 1);
found = true;
break;
}
if (found) {
cows++;
}
}
}
// Serialize
return String.format("%dA%dB", bulls, cows);
}
public void run() {
// String secret = "1123";
// String guess = "0111";
String secret = "011";
String guess = "110";
String output = getHint(secret, guess);
System.out.println(output);
}
}