diff --git a/src/modules/checkIsValidUserInput.js b/src/modules/checkIsValidUserInput.js index 40979664..47931d82 100644 --- a/src/modules/checkIsValidUserInput.js +++ b/src/modules/checkIsValidUserInput.js @@ -9,7 +9,12 @@ * @return {boolean} - True if the user input is valid, false otherwise */ function checkIsValidUserInput(userInput) { - /* Write your code here */ + const isFourDigits = userInput.length === 4; + const hasUniqueDigits = new Set(userInput.split('')).size === 4; + const isNumber = !isNaN(+userInput); + const doesNotStartWithZero = userInput[0] !== '0'; + + return isFourDigits && hasUniqueDigits && isNumber && doesNotStartWithZero; } module.exports = { diff --git a/src/modules/generateRandomNumber.js b/src/modules/generateRandomNumber.js index 14ad1e2b..c4dd8345 100644 --- a/src/modules/generateRandomNumber.js +++ b/src/modules/generateRandomNumber.js @@ -7,7 +7,24 @@ * @return {number} A random 4-digit number */ function generateRandomNumber() { - /* Write your code here */ + const digits = new Array(4); + + digits[0] = Math.floor(1 + Math.random() * 9); + + const usedDigits = new Set([digits[0]]); + + for (let i = 1; i < 4; i++) { + let randomDigit; + + do { + randomDigit = Math.floor(Math.random() * 10); + } while (usedDigits.has(randomDigit)); + + digits[i] = randomDigit; + usedDigits.add(randomDigit); + } + + return Number(digits.join('')); } module.exports = { diff --git a/src/modules/getBullsAndCows.js b/src/modules/getBullsAndCows.js index 3f0b39a6..f8ee6b06 100644 --- a/src/modules/getBullsAndCows.js +++ b/src/modules/getBullsAndCows.js @@ -13,7 +13,23 @@ * Example: { bulls: 1, cows: 2 } */ function getBullsAndCows(userInput, numberToGuess) { - /* Write your code here */ + const result = { + bulls: 0, + cows: 0, + }; + + const userNumber = userInput.toString(); + const guessNumber = numberToGuess.toString(); + + for (let i = 0; i < userNumber.length; i++) { + if (userNumber[i] === guessNumber[i]) { + result.bulls++; + } else if (guessNumber.includes(userNumber[i])) { + result.cows++; + } + } + + return result; } module.exports = {