Search code examples
javascriptcombinations

Permutations of an array for specific length no repetitions?


I am trying to list all the combinations for an array of data for a specified length of n values.

The data in question is a horse race, where there are 6 runners and possibility of 3 places. I want to list all the possible combinations for how the horses can come 1st/2nd/3rd.

Not entirely sure what to search but I have come across this SO post which seems to be nearly what I want. I can change the min and max values to 3, but I am not sure how to remove the results where a value is repeated (such as aaa/aab/aac etc since I horse can only come in 1 place).

Thanks


Solution

  • Solution I went with was to first list all possible outcomes for X places (e.g. 12 horses, max 4 places = 20,736) then checked each combination for unique values. If unique value count != array length then filter it out. In the end you are left with 11,880 unique combinations for 4 places (12x11x10x9).