Rebase Tommy McGuire's each_permutation patch

Closes #5127