Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution #241

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1 +1,36 @@
/* eslint-disable no-console */
'use strict';

const readline = require('readline');
const { generateRandomNumber } = require('./numberGenerator');
const { calculateBullsAndCows } = require('./bullsAndCowsCalculator');

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

const secretNumber = generateRandomNumber();

function playGame() {
rl.question('Enter your guess: ', (guessedNumber) => {
if (guessedNumber.length !== 4 || !/^\d{4}$/.test(guessedNumber)) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4 is a 'magic number', so make sense to move it to the constant
check other places

playGame();

return;
}

const result = calculateBullsAndCows(secretNumber, guessedNumber);

if (result.bulls === 4) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need to add congratulation message

console.log('Congratulations you are win!!!!');
rl.close();
} else {
// eslint-disable-next-line no-console
console.log(`Bulls: ${result.bulls}, Cows: ${result.cows}`);
playGame();
}
});
}

playGame();
22 changes: 22 additions & 0 deletions src/bullsAndCowsCalculator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';

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

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

return {
bulls, cows,
};
}

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

function generateRandomNumber() {
let digits = '0123456789';
let randomNum = '';

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

randomNum += digits[randomDigitIndex];

digits += digits.slice(randomDigitIndex, 1);
}

return randomNum;
}

module.exports = {
generateRandomNumber,
};
Loading