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 all 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
37 changes: 37 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1 +1,38 @@
/* eslint-disable no-console */
'use strict';

const { WIN_GUESS } = require('./constants');

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 !== WIN_GUESS || !/^\d{4}$/.test(guessedNumber)) {
playGame();

return;
}

const result = calculateBullsAndCows(secretNumber, guessedNumber);

if (result.bulls === WIN_GUESS) {
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();
24 changes: 24 additions & 0 deletions src/bullsAndCowsCalculator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';

const { WIN_GUESS } = require('./constants');

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

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

return {
bulls, cows,
};
}

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

const WIN_GUESS = 4;

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

const { WIN_GUESS } = require('./constants');

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

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

randomNum += digits[randomDigitIndex];

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

return randomNum;
}

module.exports = {
generateRandomNumber,
};
Loading