Skip to content

Commit 4f7a638

Browse files
refactor 299
1 parent 6558a8a commit 4f7a638

File tree

1 file changed

+25
-18
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+25
-18
lines changed
Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
package com.fishercoder.solutions;
22

3-
/**You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
3+
/**
4+
* 299. Bulls and Cows
5+
*
6+
* You are playing the following Bulls and Cows game with your friend:
7+
* You write down a number and ask your friend to guess what the number is.
8+
* Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in
9+
* both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows").
10+
* Your friend will use successive guesses and hints to eventually derive the secret number.
411
512
For example:
613
@@ -16,24 +23,24 @@
1623
In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return "1A1B".
1724
You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.*/
1825
public class _299 {
19-
20-
public String getHint(String secret, String guess) {
21-
int[] secretCows = new int[10];
22-
int[] guessCows = new int[10];
23-
int bulls = 0;
24-
for (int i = 0; i < secret.length(); i++) {
25-
if (guess.charAt(i) == secret.charAt(i)) {
26-
bulls++;
27-
} else {
28-
secretCows[Character.getNumericValue(secret.charAt(i))]++;
29-
guessCows[Character.getNumericValue(guess.charAt(i))]++;
26+
public static class Solution1 {
27+
public String getHint(String secret, String guess) {
28+
int[] secretCows = new int[10];
29+
int[] guessCows = new int[10];
30+
int bulls = 0;
31+
for (int i = 0; i < secret.length(); i++) {
32+
if (guess.charAt(i) == secret.charAt(i)) {
33+
bulls++;
34+
} else {
35+
secretCows[Character.getNumericValue(secret.charAt(i))]++;
36+
guessCows[Character.getNumericValue(guess.charAt(i))]++;
37+
}
3038
}
39+
int cows = 0;
40+
for (int i = 0; i < 11; i++) {
41+
cows += Math.min(secretCows[i], guessCows[i]);
42+
}
43+
return bulls + "A" + cows + "B";
3144
}
32-
int cows = 0;
33-
for (int i = 0; i < 11; i++) {
34-
cows += Math.min(secretCows[i], guessCows[i]);
35-
}
36-
return bulls + "A" + cows + "B";
3745
}
38-
3946
}

0 commit comments

Comments
 (0)