This algorithm was created by Landon Kryger to solve the problem of testing if a set of dice is permutation fair. If you have n players and s sides, the standard approach would require you to test every roll and would run in O(sn). This algorithm runs in approximately O(s*n*n!). For small s and n, it's not a very noticeable difference, but for large values like n=5;s=30 the benefit is huge.
This algorithm also works with dice with different number of sides.
1 s = "abcddbaccbadcabddacbdbcadcbadcabbcaddacbbacdabcdacbdbcaddbacdabccabddcba" 2 count = {"" : 1} 3 for c in s: 4 for k in count.keys(): 5 if k.count(c)==0: 6 k2 = k + c 7 count[k2] = count.get(k2,0) + count[k]
count['abc'] += count['ab']
Here is a Perl script implementation of the permutation-fairness checking in action.