Skip to content

Commit

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

const readline = require('readline');
const { generateRandomNumber } = require('./generateRandomNumber.js');
const { calculateBullsAndCows } = require('./calculateBullsAndCows.js');
const { getInput } = require('./getInput.js');

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

while (true) {
const userInput = await getInput();

if (userInput.length !== 4) {
console.log('The number must consist of 4 characters');
}

const result = calculateBullsAndCows(currentNumber, userInput);

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

if (result.bulls === 4) {
console.log('Congratulations! You guessed the number.');

readline.close();
}
}
})();
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(hiddenNumber, guessNumber) {
let bulls = 0;
let cows = 0;

for (const num in hiddenNumber) {
if (hiddenNumber[num] === guessNumber[num]) {
bulls++;
} else if (hiddenNumber.includes(guessNumber[num])) {
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 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let number = '';

for (let i = 0; i < 4; i++) {
const randomIndex = Math.floor(Math.random() * digits.length);
const digit = digits.splice(randomIndex, 1)[0];

number += digit;
}

return number;
}

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

const readline = require('readline');

function getInput() {
return new Promise((resolve) => {
const terminal = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

terminal.question('Please, guess a number. ', (guessNumber) => {
resolve(guessNumber);
});
});
}

module.exports = { getInput };

0 comments on commit 1be197c

Please sign in to comment.