weird permutation generation code