简体   繁体   中英

circular permutation of similar objects

I need to an R code for circular permutation of similar objects which defines this code exactly. The number of circular permutations that can be formed using 'n' objects out of which 'p' are identical and of one kind and 'q' are identical and of another kind.

(n-1)!/p!q!

This is the best code which I found but it is not exactly what I want

library(arrangements)
permutations(x =  c("A","B","C"), freq = c(2,1,1))

output:


    [,1] [,2] [,3] [,4]
 [1,] "A"  "A"  "B"  "C" 
 [2,] "A"  "A"  "C"  "B" 
 [3,] "A"  "B"  "A"  "C" 
 [4,] "A"  "B"  "C"  "A" 
 [5,] "A"  "C"  "A"  "B" 
 [6,] "A"  "C"  "B"  "A" 
 [7,] "B"  "A"  "A"  "C" 
 [8,] "B"  "A"  "C"  "A" 
 [9,] "B"  "C"  "A"  "A" 
[10,] "C"  "A"  "A"  "B"     
[11,] "C"  "A"  "B"  "A" 
[12,] "C"  "B"  "A"  "A"

I do not want "A" "A" are beside each other.

It turns out that a recursive function works well for this problem. The function takes the journey so far, figures out which remaining towns are possible to visit next, and then calls itself for each of these. If there are no remaining towns it reports the route.

# recursive function to visit remaining towns
journey <- function(remaining, visited){
  # possible towns to visit next
  possible <- setdiff(remaining, tail(visited, 1))
  if (length(possible)==0){
    if (length(remaining)==0){
      # report and store journey
      print(visited)
      routei <<- routei + 1
      routes[[routei]] <<- visited
    } else {
      # route failed to visit all towns
    }
  } else {
    # loop through options
    for (i in possible){
      # continue journey
      journey(remaining[-match(i, remaining)], c(visited, i))
    }
  }
}

remaining <- c("A", "A", "B", "B", "C")
visited <- character(0)

routes <- vector("list", length(remaining)^2)
routei <- 0

journey(remaining, visited)
#> [1] "A" "B" "A" "B" "C"
#> [1] "A" "B" "A" "C" "B"
#> [1] "A" "B" "C" "A" "B"
#> [1] "A" "B" "C" "B" "A"
#> [1] "A" "C" "B" "A" "B"
#> [1] "B" "A" "B" "A" "C"
#> [1] "B" "A" "B" "C" "A"
#> [1] "B" "A" "C" "A" "B"
#> [1] "B" "A" "C" "B" "A"
#> [1] "B" "C" "A" "B" "A"
#> [1] "C" "A" "B" "A" "B"
#> [1] "C" "B" "A" "B" "A"

Created on 2019-07-22 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM