all permutations Algorithm
The all permutations algorithm, also known as the permutation generation algorithm, is a widely used technique in computer science and mathematics for generating all possible permutations of a given set of elements. Permutations are the various arrangements that can be formed by rearranging the elements within a set in different orders. The algorithm is particularly useful in solving problems that involve combinatorial or exhaustive search, such as the travelling salesman problem, finding anagrams, or solving various puzzles. It is also helpful in understanding and analyzing complex systems and processes.
There are several ways to implement the all permutations algorithm, including recursive, iterative, and backtracking approaches. Recursive methods involve breaking down the problem into smaller sub-problems, while iterative methods use loops to generate the permutations. Backtracking, on the other hand, involves constructing partial permutations and then incrementally extending them, undoing previous steps if necessary, until a complete permutation is achieved. One of the most popular permutation generation algorithms is the Steinhaus–Johnson–Trotter algorithm, which generates permutations in a minimal change or "gray code" order. Other well-known algorithms include Heap's algorithm, which uses an iterative approach, and the Lexicographic Order algorithm, which generates permutations in lexicographically increasing order.
"""
In this problem, we want to determine all possible permutations
of the given sequence. We use backtracking to solve this problem.
Time complexity: O(n! * n),
where n denotes the length of the given sequence.
"""
def generate_all_permutations(sequence):
create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
def create_state_space_tree(sequence, current_sequence, index, index_used):
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly len(sequence) - index children.
It terminates when it reaches the end of the given sequence.
"""
if index == len(sequence):
print(current_sequence)
return
for i in range(len(sequence)):
if not index_used[i]:
current_sequence.append(sequence[i])
index_used[i] = True
create_state_space_tree(sequence, current_sequence, index + 1, index_used)
current_sequence.pop()
index_used[i] = False
"""
remove the comment to take an input from the user
print("Enter the elements")
sequence = list(map(int, input().split()))
"""
sequence = [3, 1, 2, 4]
generate_all_permutations(sequence)
sequence = ["A", "B", "C"]
generate_all_permutations(sequence)