L
L
Leel Usama2021-11-08 04:27:31
JavaScript
Leel Usama, 2021-11-08 04:27:31

What is the best algorithm to use to find all permutations?

Given number: 9202
It is necessary to make all possible combinations of numbers using the digits of this number.
For example, these are also suitable:
9022
0922
0292
, etc.

What to read what algorithm to use what would be implemented in JS?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dollar, 2021-11-08
@dollar

First, you count the number of "places" and make up an array of possible numbers: 0, 2, 9
Moreover, for each number you also need to remember how much to repeat it. In this example, "2" can be repeated twice.
Further in a loop or recursion:
in the first place it can be 0.2.9
in the second place - it already depends on the first place (if the first is 0, then the second is 2.9, and if the first is 2, then the second is 0.2.9 and etc.)
in third place again choose from the rest.
In this order, you can output all the permutations.
Naturally, I will not give the code, since the question is about the algorithm. It remains to write in the form of program text. Good luck)

W
Wataru, 2021-11-08
@wataru

The comments have already mentioned Narayana's algorithm. It works with repeating elements. It is necessary to find the rightmost element strictly greater than the previous one, change the previous one with the minimum strictly greater than it to the right, and sort the array to the right of this position (you can turn it over).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question