public IGuessResult CompareToSecret(string secret, string guess) { //TODO: A stricter validation can be put here. I don't validate for repeating syllabus for instance if (secret.Length != guess.Length) { throw new ArgumentException("The guess is invalid. Its length doesn't match the secrets length."); } int bulls = 0; for (int i = 0; i < secret.Length; i++) { if (secret[i] == guess[i]) { bulls++; } } //I will implement it so that it works with repeating symbols //Couldn't hurt //Calculating cows var secretSymbols = new Dictionary <char, int>(); for (int i = 0; i < secret.Length; i++) { if (secretSymbols.ContainsKey(secret[i])) { secretSymbols[secret[i]]++; } else { secretSymbols[secret[i]] = 1; } } for (int i = 0; i < guess.Length; i++) { if (secretSymbols.ContainsKey(guess[i]) && secretSymbols[guess[i]] > 0) { secretSymbols[guess[i]]--; } } var cows = secret.Length - secretSymbols.Values.Sum() - bulls; var isGaveOver = bulls == secret.Length; var result = new GuessResult { BullCount = bulls, CowCount = cows, HasWon = isGaveOver, GameResult = GameResult.NotFinished }; return(result); }
public IGuessResult CompareToSecret(string secret, string guess) { //TODO: A stricter validation can be put here. I don't validate for repeating syllabus for instance if (secret.Length != guess.Length) { throw new ArgumentException("The guess is invalid. Its length doesn't match the secrets length."); } int bulls = 0; for (int i = 0; i < secret.Length; i++) { if (secret[i] == guess[i]) { bulls++; } } //I will implement it so that it works with repeating symbols //Couldn't hurt //Calculating cows var secretSymbols = new Dictionary<char, int>(); for (int i = 0; i < secret.Length; i++) { if (secretSymbols.ContainsKey(secret[i])) { secretSymbols[secret[i]]++; } else { secretSymbols[secret[i]] = 1; } } for (int i = 0; i < guess.Length; i++) { if (secretSymbols.ContainsKey(guess[i]) && secretSymbols[guess[i]] > 0) { secretSymbols[guess[i]]--; } } var cows = secret.Length - secretSymbols.Values.Sum() - bulls; var isGaveOver = bulls == secret.Length; var result = new GuessResult { BullCount = bulls, CowCount = cows, HasWon = isGaveOver, GameResult = GameResult.NotFinished }; return result; }