Implementing a permutation algorithm