Advertisement
zinch

Groovy Permutations

Apr 5th, 2015
507
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 0.70 KB | None | 0 0
  1. def perm(tokens) {
  2.     if (!tokens || tokens.size() == 1) {
  3.         return [tokens];
  4.     }
  5.  
  6.     if (tokens.size() == 2) {
  7.         return [tokens, tokens.reverse()];
  8.     }
  9.  
  10.     def permutations = []
  11.     for (def token : tokens) {
  12.         def tail = tokens.collect() - token;
  13.         def tail_perms = perm(tail)
  14.         for (def p : tail_perms) {
  15.             p.add(0, token)
  16.             permutations += [p]
  17.         }
  18.     }
  19.     return permutations
  20. }
  21.  
  22. assert [['a', 'b'], ['b', 'a']] == perm('ab'.toList())
  23. assert [['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']] == perm('abc'.toList())
  24. assert ['d', 'c', 'b', 'a'] == perm('abcd'.toList())[-1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement