I'm trying to do a brute-force-like algorithm for printing all the permutation of an array. There's a function that sorts the array, another function generates the permutations, then the permutation list is cleaned for duplicated elements and lastly sorted with the same function from the beginning. The problem is there's something wrong with the array; at least half of the permutations are missing, this doesn't happen with three elements but with five elements i have not even a fourth part of all the permutations I should have. I have no idea what's wrong. Here's a fragment of the code from the get_permutations() function.
def get_permutations(arr) -> list[list]: sorted_arr:list = ascending_sort(arr) size:int = len(arr) n_perm:int = math.factorial(size) i:int = 0 permutations = [] print(f'sorted array: {sorted_arr}') while i < n_perm: if i == 0: print(f'{i+1}: ({arr})') else: for j in range(size): arr[j], arr[j-1] = arr[j-1], arr[j] permutations.append(arr.copy()) i += 1 return permutations
This is the output:
sorted array: [1, 2, 3, 4]1: ([1, 2, 3, 4])[[4, 2, 3, 1], [2, 4, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4], [4, 1, 2, 3], [1, 4, 2, 3], [1, 2, 4, 3], [1, 2, 3, 4], [4, 2, 3, 1], [2, 4, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4], [4, 1, 2, 3], [1, 4, 2, 3], [1, 2, 4, 3], [1, 2, 3, 4], [4, 2, 3, 1], [2, 4, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4], [4, 1, 2, 3], [1, 4, 2, 3], [1, 2, 4, 3], [1, 2, 3, 4], [4, 2, 3, 1], [2, 4, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4], [4, 1, 2, 3], [1, 4, 2, 3], [1, 2, 4, 3], [1, 2, 3, 4], [4, 2, 3, 1], [2, 4, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4], [4, 1, 2, 3], [1, 4, 2, 3], [1, 2, 4, 3], [1, 2, 3, 4], [4, 2, 3, 1], [2, 4, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4], [4, 1, 2, 3], [1, 4, 2, 3], [1, 2, 4, 3], [1, 2, 3, 4], [4, 2, 3, 1], [2, 4, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4], [4, 1, 2, 3], [1, 4, 2, 3], [1, 2, 4, 3], [1, 2, 3, 4], [4, 2, 3, 1], [2, 4, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4]]sorted: [[1, 2, 3, 4], [1, 2, 4, 3], [1, 4, 2, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 3, 1], [3, 1, 2, 4], [3, 1, 4, 2], [3, 4, 1, 2], [4, 1, 2, 3], [4, 2, 3, 1], [4, 3, 1, 2]]sorted_res_len: 12[1, 2, 3, 4][1, 2, 4, 3][1, 4, 2, 3][2, 3, 1, 4][2, 3, 4, 1][2, 4, 3, 1][3, 1, 2, 4][3, 1, 4, 2][3, 4, 1, 2][4, 1, 2, 3][4, 2, 3, 1][4, 3, 1, 2]
I tried to change the variable size in the for loop, but as it loops through the elements, it has to be less than the size. Also, I tried rotate the array like using list slicing but that didn't work either. Maybe I was doing it wrong but I'm clueless about what could be causing the problem.