Permute all unique enumerations of a vector in R

前端 未结 7 782
忘了有多久
忘了有多久 2020-11-29 06:21

I\'m trying to find a function that will permute all the unique permutations of a vector, while not counting juxtapositions within subsets of the same element type.

7条回答
  •  眼角桃花
    2020-11-29 06:29

    I don't actually know R, but here's how I'd approach the problem:

    Find how many of each element type, i.e.

    4 X 0
    2 X 1
    2 X 3
    2 X 4
    

    Sort by frequency (which the above already is).

    Start with the most frequent value, which takes up 4 of the 10 spots. Determine the unique combinations of 4 values within the 10 available spots. (0,1,2,3),(0,1,2,4),(0,1,2,5),(0,1,2,6) ... (0,1,2,9),(0,1,3,4),(0,1,3,5) ... (6,7,8,9)

    Go to the second most frequent value, it takes up 2 of 6 available spots, and determine it's unique combinations of 2 of 6. (0,1),(0,2),(0,3),(0,4),(0,5),(1,2),(1,3) ... (4,6),(5,6)

    Then 2 of 4: (0,1),(0,2),(0,3),(1,2),(1,3),(2,3)

    And the remaining values, 2 of 2: (0,1)

    Then you need to combine them into each possible combination. Here's some pseudocode (I'm convinced there's a more efficient algorithm for this, but this shouldn't be too bad):

    lookup = (0,1,3,4)
    For each of the above sets of combinations, example: input = ((0,2,4,6),(0,2),(2,3),(0,1))
    newPermutation = (-1,-1,-1,-1,-1,-1,-1,-1,-1,-1)
    for i = 0 to 3
      index = 0
      for j = 0 to 9
        if newPermutation(j) = -1
          if index = input(i)(j)
            newPermutation(j) = lookup(i)
            break
          else
            index = index + 1
    

提交回复
热议问题