Improved lex_permutation function for problem 24.