How do I list all the circular permutations in R where direction does not matter? I have a vector 1:4 for illustration (however, I would like a general solution).
I use
gtools::permutations(n = 4, r = 4)
which gives me a listing of all possible permutations as follows:
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 2 4 3
[3,] 1 3 2 4
[4,] 1 3 4 2
[5,] 1 4 2 3
[6,] 1 4 3 2
[7,] 2 1 3 4
[8,] 2 1 4 3
[9,] 2 3 1 4
[10,] 2 3 4 1
[11,] 2 4 1 3
[12,] 2 4 3 1
[13,] 3 1 2 4
[14,] 3 1 4 2
[15,] 3 2 1 4
[16,] 3 2 4 1
[17,] 3 4 1 2
[18,] 3 4 2 1
[19,] 4 1 2 3
[20,] 4 1 3 2
[21,] 4 2 1 3
[22,] 4 2 3 1
[23,] 4 3 1 2
[24,] 4 3 2 1
However, what I would like is the listing of the six circular permutations. So, I think that this is:
cbind(gtools::permutations(n = 3, r = 3),4)
that gives me:
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 3 2 4
[3,] 2 1 3 4
[4,] 2 3 1 4
[5,] 3 1 2 4
[6,] 3 2 1 4
However, I would like to also ignore the listings which are the same but for order. Example: I do not want to distinguish c(1,2,3,4) from c(4,3,2,1) (i.e. the 1st and the 6th entry), or c(1, 3, 2, 4) and c(2, 1, 3, 4) (i.e. the 2nd and the 4th entry) and c(2, 1, 3, 4) from c(3, 1, 2, 4) (i.e. the 3rd and the 5th entry in the output)? Is it simply a case of taking the first half of the results?
Is there a surer way of doing this? Many thanks for answering my question or providing suggestions.
We can't simply take the first half of results of
permutations(n-1, n-1)and append n. This is easy to see for n = 5.I suggest to use the following approach:
And this is the algorithm we are going to use to construct such set of permutations:
Find all pairs of elements #2 and #n, where #2 is less then #n. This is
combinations(n-1, 2, v = 2:n).For each such combination find all permutations of all the rest n-3 elements. This is
permutations(n - 3, n - 3, v = rest_elements)whererest_elementsis a vector listing all n-3 elements that are left when we remove 1, #2 and #n.Created on 2021-08-28 by the reprex package (v2.0.1)