Skip to content
Open
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
40 changes: 36 additions & 4 deletions 04week/mastermind.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const rl = readline.createInterface({
});

let board = [];
let solution = '';
let solution = 'abcd'; //set global variable #0
let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];

function printBoard() {
Expand All @@ -28,13 +28,45 @@ function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}

function generateHint() {
function generateHint(guess) { //pass in guess to generate hint #2
// your code here
let guessArray = guess.split(''); //create arrays that slit up passed in arguments #2.1
let solutionArray = solution.split(''); //create arrays that slit up passed in arguments #2.1
let correctLetterLocations = 0; //determine correct letter locations #2.2
for (let i = 0; i<solutionArray.length; i++) {
if (solutionArray[i] == guessArray[i]){
correctLetterLocations += 1;
solutionArray[i] = null;
}
}
let correctLetters = 0; //determine correct letters #2.3
for (let n=0; solutionArray.length > n; n++){
let targetIndex = guessArray.indexOf([solutionArray[n]]);
if (targetIndex > -1){
correctLetters += 1;
solutionArray[n] = null;
}
}

let hint = correctLetterLocations + "-" + correctLetters; //determine hint #2.4
console.log(hint);
return hint;
}

function mastermind(guess) {
solution = 'abcd'; // Comment this out to generate a random solution
// your code here
if (guess === solution) { //add guess #3
console.log('You guessed it!') //if guess is equal to solution then return you guessed it #1
} else {
generateHint(solution, guess);
console.log('try again');
board += 1;
}
if (board.length >= 10) { //end game #4
console.log('You ran out! The solution was: ${solution}');
return;
}
}


Expand Down Expand Up @@ -62,10 +94,10 @@ if (typeof describe === 'function') {

describe('#generateHint()', () => {
it('should generate hints', () => {
assert.equal(generateHint('abdc'), '2-2');
assert.equal(generateHint(solution, 'abdc'), '2-2');
});
it('should generate hints if solution has duplicates', () => {
assert.equal(generateHint('aabb'), '1-1');
assert.equal(generateHint(solution, 'aabb'), '1-1');
});

});
Expand Down