Skip to content
Advertisement

Permutation without repetition, efficient way

JavaScript

As “combinations with replacement” does, this function only produces the combination. I want permutation of each combination without repetition. For example

JavaScript

When I tried to do this by

JavaScript

Time complexity was exponential, and made repititions When I tested with one list sum_n_combs[0], which is [0, 0, 0, 0, 0, 14] produced 720 permutations when I only want 6 of them(14 at each different place).

How can I make permutation without repetition for each combination in an efficient way?

Advertisement

Answer

You could separate this in two steps:

  1. generate partitions of the targeted sum
  2. generate distinct permutations of each partition

Recursive generators will allow you to get the results efficiently without trial/error filtering and without storing everything in memory:

JavaScript

output:

JavaScript

PARTITIONS…

JavaScript

PERMUTED PARTITIONS (DISTINCT):

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement