final version of permutation algorithm