|
| 1 | +/** |
| 2 | + * 843. Guess the Word |
| 3 | + * https://leetcode.com/problems/guess-the-word/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array of unique strings words where words[i] is six letters long. One word of |
| 7 | + * words was chosen as a secret word. |
| 8 | + * |
| 9 | + * You are also given the helper object Master. You may call Master.guess(word) where word is a |
| 10 | + * six-letter-long string, and it must be from words. Master.guess(word) returns: |
| 11 | + * - -1 if word is not from words, or |
| 12 | + * - an integer representing the number of exact matches (value and position) of your guess to |
| 13 | + * the secret word. |
| 14 | + * |
| 15 | + * There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum |
| 16 | + * number of times you can call Master.guess(word). |
| 17 | + * |
| 18 | + * For each test case, you should call Master.guess with the secret word without exceeding the |
| 19 | + * maximum number of allowed guesses. You will get: |
| 20 | + * - "Either you took too many guesses, or you did not find the secret word." if you called |
| 21 | + * Master.guess more than allowedGuesses times or if you did not call Master.guess with the |
| 22 | + * secret word, or |
| 23 | + * - "You guessed the secret word correctly." if you called Master.guess with the secret word |
| 24 | + * with the number of calls to Master.guess less than or equal to allowedGuesses. |
| 25 | + * |
| 26 | + * The test cases are generated such that you can guess the secret word with a reasonable |
| 27 | + * strategy (other than using the bruteforce method). |
| 28 | + */ |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {string[]} words |
| 32 | + * @param {Master} master |
| 33 | + * @return {void} |
| 34 | + */ |
| 35 | +var findSecretWord = function(words, master) { |
| 36 | + for (let attempt = 0; attempt < 30; attempt++) { |
| 37 | + const randomWord = words[Math.floor(Math.random() * words.length)]; |
| 38 | + const matchCount = master.guess(randomWord); |
| 39 | + |
| 40 | + if (matchCount === 6) return; |
| 41 | + |
| 42 | + words = words.filter(word => |
| 43 | + matchCount === -1 |
| 44 | + ? countMatches(word, randomWord) === 0 |
| 45 | + : countMatches(word, randomWord) === matchCount |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + function countMatches(word1, word2) { |
| 50 | + let matches = 0; |
| 51 | + for (let i = 0; i < word1.length; i++) { |
| 52 | + if (word1[i] === word2[i]) matches++; |
| 53 | + } |
| 54 | + return matches; |
| 55 | + } |
| 56 | +}; |
0 commit comments