Skip to content

Commit

Permalink
add solution
Browse files Browse the repository at this point in the history
  • Loading branch information
adv555 committed Aug 8, 2023
1 parent cfabcaf commit d334c92
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1 +1,39 @@
/* eslint-disable no-console */
'use strict';

const { generateRandomNumber } = require('./generateRandomNumber');
const { calculateBullsAndCows } = require('./calculateBullsAndCows');
const { getUserInput, closeInterface } = require('./getUserInput');

(async () => {
const secretNumber = generateRandomNumber();

console.log('Welcome to Bulls and Cows game!');

let attempts = 0;

while (true) {
const guess = await getUserInput('Enter your guess (4 different digits): ');

console.log(`Your guess: ${guess}`);

if (new Set(guess).size !== 4 || isNaN(guess)) {
console.log('Invalid input. Please enter 4 different digits.');
continue;
}

attempts++;

const result = calculateBullsAndCows(secretNumber, guess);

console.log(`Bulls: ${result.bulls}, Cows: ${result.cows}`);

if (result.bulls === 4) {
console.log(
`Congratulations! You guessed the number in ${attempts} attempts.`
);
closeInterface();
break;
}
}
})();
21 changes: 21 additions & 0 deletions src/calculateBullsAndCows.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

function calculateBullsAndCows(secretNumber, guess) {
let bulls = 0;
let cows = 0;

for (let i = 0; i < secretNumber.length; i++) {
if (secretNumber[i] === guess[i]) {
bulls++;
} else if (secretNumber.includes(guess[i])) {
cows++;
}
}

return {
bulls,
cows,
};
}

module.exports = { calculateBullsAndCows };
17 changes: 17 additions & 0 deletions src/generateRandomNumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

function generateRandomNumber() {
const digits = [];

while (digits.length < 4) {
const randomNumber = Math.floor(Math.random() * 10);

if (!digits.includes(randomNumber)) {
digits.push(randomNumber);
}
}

return digits.join('');
}

module.exports = { generateRandomNumber };
26 changes: 26 additions & 0 deletions src/getUserInput.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/* eslint-disable no-console */
'use strict';

const readline = require('readline');

const terminal = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

function getUserInput(prompt) {
return new Promise((resolve) => {
terminal.question(prompt, (answer) => {
resolve(answer);
});
});
}

function closeInterface() {
terminal.close();
}

module.exports = {
getUserInput,
closeInterface,
};

0 comments on commit d334c92

Please sign in to comment.