iterative implementation of permutation and better tests