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
51 changes: 39 additions & 12 deletions 04week/mastermind.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ let board = [];
let solution = '';
let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];



function printBoard() {
for (let i = 0; i < board.length; i++) {
console.log(board[i]);
Expand All @@ -28,16 +30,45 @@ function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}

function generateHint() {
// your code here
function generateHint(solution, guess) {
let solutionArray = solution.split('');
let guessArray = guess.split('');
let correctLetterLocations = 0;
for (let i=0; i<solutionArray.length; i++) {
if (solutionArray[i] == guessArray[i]){
correctLetterLocations = correctLetterLocations + 1;
solutionArray[i] = null;
}
}
let correctLetters = 0;
for (let j=0; j<solutionArray.length; j++){
let targetIndex = guessArray.indexOf(solutionArray[j]);
if (targetIndex > -1) {
correctLetters = correctLetters + 1;
solutionArray[j] = null;
}
}
return correctLetterLocations+"-" + correctLetters;
//fancier hint generator that the NPM tests won't like:
// return correctLetterLocations+" correct and " + correctLetters + " in the wrong place";
}


function mastermind(guess) {
solution = 'abcd'; // Comment this out to generate a random solution
// your code here
solution = 'abcd';
if (board.length >= 10){
console.log('You ran out of guesses!')
} else {
if (guess != solution) {
let hints = generateHint(solution, guess);
board.push(hints)
} else {
console.log('You guessed it!');
return 'You guessed it!';
}
}
}


function getPrompt() {
rl.question('guess: ', (guess) => {
mastermind(guess);
Expand All @@ -59,19 +90,15 @@ if (typeof describe === 'function') {
assert.equal(mastermind(solution), 'You guessed it!');
});
});

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');
});

});

} else {

generateSolution();
getPrompt();
}
}