Home > Mobile >  Permutations of an array for specific length no repetitions?
Permutations of an array for specific length no repetitions?

Time:08-13

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

CodePudding user response:

This is by no means the most efficient I would imagine, and only works for this scenario, but maybe you can build off of this. There should be 120 combinations if my math is correct (6 x 5 x 4), which is how many combinations this code spits out.

const horses = ["a", "b", "c", "d", "e", "f"];
const combinations = [];

horses.forEach((horse1st) => {
  horses.forEach((horse2nd) => {
    if (horse2nd === horse1st) return;
    horses.forEach((horse3rd) => {
      if (horse3rd === horse1st || horse3rd === horse2nd) return;
      combinations.push([horse1st, horse2nd, horse3rd]);
    });
  });
});

CodePudding user response:

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.

One approach might be to write out the result first.

Then you can examine the result and work out the processes you need to write to derive that result.

Here is the result:

123 124 125 126 -- 132 134 135 136 -- 142 143 145 146 -- 152 153 154 156 -- 162 163 164 165

213 214 215 216 -- 231 234 235 236 -- 241 243 245 246 -- 251 253 254 256 -- 261 263 264 265

312 314 315 316 -- 321 324 325 326 -- 341 342 345 346 -- 351 352 354 356 -- 361 362 364 365

412 413 415 416 -- 421 423 425 426 -- 431 432 435 436 -- 451 452 453 456 -- 461 462 463 465

512 513 514 516 -- 521 523 524 526 -- 531 532 534 536 -- 541 542 543 546 -- 561 562 563 564

612 613 614 615 -- 621 623 624 625 -- 631 632 634 635 -- 641 642 643 645 -- 651 652 653 654

You can see there are six sets.

Each set contains five subsets (ie. 6 - 1)

Each subset contains four permutations. (ie. 6 - 2)

Now work out how you go from six horses and three positions to the above.

  • Related