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

add task solution #429

Open
wants to merge 2 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
23 changes: 23 additions & 0 deletions .github/workflows/test.yml-template
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Test

on:
pull_request:
branches: [ master ]

jobs:
build:

runs-on: ubuntu-latest

strategy:
matrix:
node-version: [20.x]

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
9 changes: 5 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"license": "GPL-3.0",
"devDependencies": {
"@mate-academy/eslint-config": "latest",
"@mate-academy/scripts": "^1.8.6",
"@mate-academy/scripts": "^1.9.12",
"eslint": "^8.57.0",
"eslint-plugin-jest": "^28.6.0",
"eslint-plugin-node": "^11.1.0",
Expand Down
40 changes: 39 additions & 1 deletion src/app.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,41 @@
'use strict';

// Write your code here
const readline = require('node:readline');
const { checkIsValidUserInput } = require('./modules/checkIsValidUserInput.js');
const { generateRandomNumber } = require('./modules/generateRandomNumber.js');
const { getBullsAndCows } = require('./modules/getBullsAndCows.js');

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

const print = (message) => rl.write(message + '\n');

const secretNumber = generateRandomNumber();

// Функція, яка запускає одну спробу гри
function playRound() {
rl.question('Введіть ваше число: ', (guess) => {
const validInput = checkIsValidUserInput(guess);

if (!checkIsValidUserInput(guess)) {
Comment on lines +20 to +22

Choose a reason for hiding this comment

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

The variable validInput is assigned the result of checkIsValidUserInput(guess), but the same function is called again in the if condition on line 22. You can use validInput directly in the condition to avoid redundant function calls.

print('невалідне значення');
playRound();

Choose a reason for hiding this comment

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

Using recursion for handling invalid input can lead to a stack overflow if the user continuously inputs invalid data. Consider using a loop to handle repeated attempts instead of recursion.

}

if (validInput && guess !== secretNumber.toString()) {
const { bulls, cows } = getBullsAndCows(guess, secretNumber);

print(`Бики: ${bulls}, Корови: ${cows}`);
playRound(); // Запускаємо ще один раунд
}

if (guess === secretNumber.toString() && validInput) {
print(`Вітаємо! Ви вгадали число ${secretNumber}!`);
rl.close();
}
});
}

playRound();
15 changes: 14 additions & 1 deletion src/modules/checkIsValidUserInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,20 @@
* @return {boolean} - True if the user input is valid, false otherwise
*/
function checkIsValidUserInput(userInput) {
/* Write your code here */
// Перевірка, що це 4-значне число
if (userInput.length !== 4 || isNaN(+userInput)) {
return false;
}

// Перевірка, що число не починається з 0
if (userInput[0] === '0') {
return false;
}

// Перевірка на дублікати за допомогою Set
const uniqueDigits = new Set(userInput.split(''));

return uniqueDigits.size === 4;
}

module.exports = {
Expand Down
15 changes: 14 additions & 1 deletion src/modules/generateRandomNumber.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,20 @@
* @return {number} A random 4-digit number
*/
function generateRandomNumber() {
/* Write your code here */
const digits = [];

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

// Перевіряємо, що перша цифра не є 0 та цифра ще не додана
if ((digits.length === 0 && digit === '0') || digits.includes(digit)) {
continue;
}

digits.push(digit);
}

return parseInt(digits.join(''), 10);
}

module.exports = {
Expand Down
30 changes: 29 additions & 1 deletion src/modules/getBullsAndCows.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,35 @@
* Example: { bulls: 1, cows: 2 }
*/
function getBullsAndCows(userInput, numberToGuess) {
/* Write your code here */
const userInputStr = userInput.toString();
const numberToGuessStr = numberToGuess.toString();

const result = {
bulls: 0,
cows: 0,
};

const checkedPositions = new Array(4).fill(false);

for (let i = 0; i < 4; i++) {
if (userInputStr[i] === numberToGuessStr[i]) {
result.bulls++;
checkedPositions[i] = true;
}
}

for (let i = 0; i < 4; i++) {
if (userInputStr[i] !== numberToGuessStr[i]) {
const cowIndex = numberToGuessStr.indexOf(userInputStr[i]);

if (cowIndex !== -1 && !checkedPositions[cowIndex]) {
result.cows++;
checkedPositions[cowIndex] = true;
Comment on lines +35 to +39

Choose a reason for hiding this comment

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

The logic for calculating cows is incorrect. The current implementation checks for the presence of a digit in the numberToGuessStr but does not ensure that the cowIndex is not already a bull. This can lead to incorrect cow counts. Consider checking if cowIndex is not equal to i and that checkedPositions[cowIndex] is false before incrementing the cow count.

}
}
}

return result;
}

module.exports = {
Expand Down
Loading