Wednesday, November 11, 2020

Bulls and Cows Game

Problem: Two players are playing the Bulls and Cows game. Game's rules are as follows:

Player 1 write down a secret number and asks Player 2 to guess what the number is. When Player 2 makes a guess, Player 1 provides a hint with the following info:

  1. The number of "bulls", which are digits in the guess that are in the correct position.
  2. The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.

Given the Player 1's secret number and Player 2's guess, return the hint which Player 1 will provide to Player 2. The hint should be formatted as "BullsCountACowsCountB", where BullsCount is the number of bulls and CowsCount is the number of cows. 

Example:

Input: secret = "011", guess = "110"
Output: "1A2B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"011"
  |
"110"


Approach: Using hash it can be solved easily. Approach can be understood by just looking at the code.


Implementation in C#:

        public static string GetHint(string secret, string guess)

        {

            int bulls = 0;

            int cows = 0;

            int[] hash = new int[10];

            for(int i = 0; i < secret.Length; ++i)

            {

                if (i < guess.Length && secret[i] == guess[i])

                {

                    ++bulls;

                }

                ++hash[secret[i] - '0'];

            }

            for (int i = 0; i < guess.Length; ++i)

            {

                if (hash[guess[i] - '0'] > 0)

                {

                    --hash[guess[i] - '0'];

                    ++cows;

                }

            }

            // At this point number of cows will also include number of bulls so subtracting it

            cows -= bulls;

            return $"{bulls}A{cows}B";

        }


Complexity: O(n)

No comments:

Post a Comment