Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. class Mastermind {
  2. constructor() {
  3. this.length = 4
  4. this.chars = ['0', '1', '2', '3', '4', '5']
  5. }
  6.  
  7. generate() {
  8. this.key = []
  9. for (var i = 0; i < this.length; i++)
  10. this.key.push(this.chars[(Math.random() * this.chars.length) | 0])
  11. }
  12.  
  13. guess(attempt) {
  14. if (attempt.length != this.length)
  15. return 'INVALID ATTEMPT'
  16.  
  17. let correct = 0, almost = 0, key2 = this.key.slice(0), idx
  18.  
  19. for (var i = 0; i < this.length; i++) {
  20. if (key2[i] === attempt[i])
  21. ++correct
  22. else if ((idx = key2.indexOf(attempt[i])) !== -1
  23. && key2[idx] !== attempt[idx]) {
  24. key2[idx] = ' '
  25. ++almost
  26. }
  27. }
  28.  
  29. if (correct === this.length)
  30. return 'CORRECT'
  31.  
  32. return correct + ' CORRECT, ' + almost + ' ALMOST'
  33. }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement