问题
What must be changed in a standard Steinhaus–Johnson–Trotter if values in the initial array are not ordered? For example, my initial array is 312 and I want to generate the following result:
312
321
231
213
123
132
I could introduce an additional array which defines the initial weight of each number, e.g. w[3]=1, w[1]=2, and w[2]=3 and then compare weights instead of values in the algorithm, but is it possible to do without this - I want to apply the algorithm to a problem where this additional array is not convenient? I am looking for solution in C.
回答1:
Just apply the Johnson-Trotter algorithm on an array of indices as normal. Instead of displaying the indices, however, display the items at each respective index in a separate array containing arbitrary elements in an arbitrary order.
As a simple example (not in C, but the idea is the same):
from trotter import Permutations
index_permutations = Permutations(3, [0, 1, 2])
items = [3, 1, 2]
print("Indices -> Items")
for indices in index_permutations:
print("{} -> {}".format(indices, [items[i] for i in indices]))
Output:
Indices -> Items
[0, 1, 2] -> [3, 1, 2]
[0, 2, 1] -> [3, 2, 1]
[2, 0, 1] -> [2, 3, 1]
[2, 1, 0] -> [2, 1, 3]
[1, 2, 0] -> [1, 2, 3]
[1, 0, 2] -> [1, 3, 2]
来源:https://stackoverflow.com/questions/46919309/steinhaus-johnson-trotter-algorithm-with-an-arbitrary-initial-state