Permutations algorithm from CSC321