Skip to content

Commit

Permalink
random number fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan Bilotserkivskiy committed Aug 16, 2023
1 parent d464077 commit 053efbb
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 12 deletions.
21 changes: 10 additions & 11 deletions src/modules/getBullsAndCows.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
'use strict';

const makeValidation = require('./validation').makeValidation;

function getBullsAndCows(guess, randomNumber) {
if (guess.length > 4) {
return 'Your number has more than 4 digits';
}
const validation = makeValidation(guess);

if (guess.length < 4) {
return 'Your number has less than 4 digits';
if (validation) {
return validation;
}

let bulls = 0;
let cows = 0;
const target = randomNumber.split('');
const testLine = [...target];

for (let i = 0; i < guess.length; i++) {
if (guess[i] === testLine[i]) {
if (guess[i] === target[i]) {
bulls++;
testLine[i] = ' ';
target[i] = ' ';
}
}

for (let i = 0; i < guess.length; i++) {
if (testLine.includes(guess[i])) {
if (target.includes(guess[i])) {
cows++;

const cowIndex = testLine.indexOf(guess[i]);
const cowIndex = target.indexOf(guess[i]);

testLine[cowIndex] = ' ';
target[cowIndex] = ' ';
}
}

Expand Down
19 changes: 18 additions & 1 deletion src/modules/getRandomNumber.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
'use strict';

function getRandomNumber() {
return Math.floor(Math.random() * (9999 - 1000) + 1000) + '';
const arrayOfNumbers = Array.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);

let randomNumber = '';

for (let i = 1; i <= 4; i++) {
let randomIndex = Math.floor(Math.random() * arrayOfNumbers.length);

if (i === 1) {
while (randomIndex === 0) {
randomIndex = Math.floor(Math.random() * arrayOfNumbers.length);
}
}

randomNumber += arrayOfNumbers[randomIndex];
arrayOfNumbers.splice(randomIndex, 1);
};

return randomNumber;
};

module.exports.getRandomNumber = getRandomNumber;
30 changes: 30 additions & 0 deletions src/modules/validation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';

function makeValidation(guess) {
if (guess.length > 4) {
return 'Your number has more than 4 digits';
}

if (guess.length < 4) {
return 'Your number has less than 4 digits';
}

let validGuess = true;
const guessArray = guess.split('');

for (let i = 0; i < guessArray.length; i++) {
for (let j = i + 1; j < guessArray.length; j++) {
if (guessArray[j] === guessArray[i]) {
validGuess = false;
}
}
}

if (!validGuess) {
return 'Please pick unique numbers';
}

return false;
}

module.exports.makeValidation = makeValidation;

0 comments on commit 053efbb

Please sign in to comment.