more efficient permutation algorithm