[LeetCode][JavaScript]Bulls and Cows

Bulls and Cows

You are playing the following Bulls and Cows game with your friend: You write a 4-digit secret number and ask your friend to guess it, each time your friend guesses a number, you give a hint, the hint tells your friend how many digits are in the correct positions (called "bulls") and how many digits are in the wrong positions (called "cows"), your friend will use those hints to find out the secret number.

For example:

Secret number:  1807
Friend's guess: 7810
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 01 and 7.)

 

According to Wikipedia: "Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking mind or paper and pencil game for two or more players, predating the similar commercially marketed board game Mastermind. The numerical version of the game is usually played with 4 digits, but can also be played with 3 or any other number of digits."

Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows, in the above example, your function should return 1A3B.

You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

https://leetcode.com/problems/bulls-and-cows/

 

 

 


 

 

 

猜字游戏,位置和数字都对记做A,数字相同位置不对记做B。

对于B的情况,开两个哈希表,分别记录还没对应的数字出现的次数。

在之后的遍历中如果找到了这个数,count--。

 1 /**
 2  * @param {string} secret
 3  * @param {string} guess
 4  * @return {string}
 5  */
 6 var getHint = function(secret, guess) {
 7     var secretDict = {}, guessDict = {}, A = 0, B = 0;
 8     for(var i = 0; i < secret.length; i++){
 9         if(secret[i] === guess[i]){
10             A++;
11         }else{
12              if(!guessDict[secret[i]]){
13                 if(!secretDict[secret[i]]){
14                     secretDict[secret[i]] = 1;
15                 }else{
16                     secretDict[secret[i]]++;
17                 }
18              }else{
19                 guessDict[secret[i]]--;
20                 B++;
21              }
22              if(!secretDict[guess[i]]){
23                 if(!guessDict[guess[i]]){
24                     guessDict[guess[i]] = 1;
25                 }else{
26                     guessDict[guess[i]]++;
27                 }
28              }else{
29                 secretDict[guess[i]]--;
30                 B++;
31              }
32         }
33     }
34     return A + "A" + B + "B";
35 };

 

 

 

 

 

 

 

posted @ 2015-10-31 16:48  `Liok  阅读(524)  评论(0编辑  收藏  举报