Rock Paper Scissors

To solve this problem recursively, think of the game as a tree and you want to traverse all possible solutions depth-first.  That means going all the way down one branch first before moving back up to evaluate the previous level(s).

Screen Shot 2017-12-10 at 6.19.47 PM

Recursive Solution:

var rockPaperScissors = function(n) {
  var output = [];
  var choices = ['rock', 'paper', 'scissors'];
  n = n || 3;

  var makeCombo = function(movesPlayed, roundsLeft) {
    if (roundsLeft === 0){
      output.push(movesPlayed);
    } else {
       for (var i = 0; i < choices.length; i++) {
         makeCombo(movesPlayed.concat(choices[i]), roundsLeft - 1);
       }
    }
  }
  makeCombo([], n);
  return output;
};

 

Order of execution: 

1. makeCombo([], 3)
2. makeCombo([‘rock’], 2);
3. makeCombo([‘rock rock’], 1);
4. makeCombo([‘rock paper’], 1);
5. makeCombo([‘rock scissors’], 1);
6. makeCombo([‘rock rock rock’], 0);
7. push [‘rock rock rock’] to output
8. makeCombo([‘rock rock paper’], 0);
9. push [‘rock rock paper’] to output
10. makeCombo([‘rock rock scissors’], 0);
11. push [‘rock rock scissors’] to output

12. makeCombo([‘paper’], 2);

..

…. makeCombo([‘scissors’], 2);

 

 

 

Rock Paper Scissors