Advertisement
EvlogiHr

Bulls and Cows

Mar 31st, 2014
1,031
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.31 KB | None | 0 0
  1. using System;
  2.  
  3. class Program
  4. {
  5.     static void Main()
  6.     {
  7.         // input
  8.         string guessNum = Console.ReadLine();
  9.         int targetBulls = int.Parse(Console.ReadLine());
  10.         int targetCows = int.Parse(Console.ReadLine());
  11.         bool hasSolution = false;
  12.         bool isFirst = true;
  13.  
  14.         for (int num = 1111; num <= 9999; num++)
  15.         {
  16.             int bulls = 0;
  17.             int cows = 0;
  18.             char[] numStr = num.ToString().ToCharArray();
  19.             bool[] isGuessVisted = new bool[numStr.Length];
  20.             bool[] isNumVisted = new bool[numStr.Length];
  21.             // added another bool array to track the digits that are visited from the number we are checking
  22.  
  23.             if (num.ToString().Contains("0"))
  24.             {
  25.                 continue;
  26.             }
  27.  
  28.             // count bulls and cows
  29.             for (int i = 0; i < guessNum.Length; i++)
  30.             {
  31.                 if (guessNum[i] == numStr[i])
  32.                 {
  33.                     bulls++;
  34.                     isGuessVisted[i] = true; // set that we have visited this digit at index i
  35.                     isNumVisted[i] = true; // set that we have visited this digit at index i
  36.                 }
  37.             }
  38.  
  39.             for (int i = 0; i < guessNum.Length; i++)
  40.             {
  41.                 for (int j = 0; j < numStr.Length; j++)
  42.                 {
  43.                     if (i != j &&
  44.                         !isNumVisted[j] &&
  45.                         !isGuessVisted[i] &&
  46.                         guessNum[i] == numStr[j]) // check if digits are the same
  47.                     {
  48.                         cows++;
  49.                         isGuessVisted[i] = true; // set that we have visited this digit at index i
  50.                         isNumVisted[j] = true; // set that we have visited this digit at index j
  51.                     }
  52.                 }
  53.             }
  54.  
  55.             // compare
  56.             if (bulls == targetBulls && cows == targetCows)
  57.             {
  58.                 hasSolution = true;
  59.                 if (!isFirst)
  60.                 {
  61.                     Console.Write(" ");
  62.                 }
  63.                 Console.Write(num);
  64.                 isFirst = false;
  65.             }
  66.         }
  67.  
  68.         if (!hasSolution)
  69.         {
  70.             Console.WriteLine("No");
  71.         }
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement