K
K
Katsimoto2019-08-06 15:32:41
JavaScript
Katsimoto, 2019-08-06 15:32:41

Complicated generation of permutations (preferably JS, but pseudo-code will do)?

Hello. There are from 1 to 8 arrays, each with 2 to 4 elements (all elements are digits). It is necessary to sort through all these numbers in such a way that all possible variants of a number from 1 to 8 characters are obtained. For example, there are arrays [1, 2, 3], [2, 3, 4], [5, 6], [7, 8, 9]. It is necessary to somehow make it so that all possible variants of the number are obtained, for example, 1359, 2258, etc.
Please tell me which way to dig, which algorithm to use. I thought to implement this after 8 cycles, if let's say there are only 4 arrays, then 5 and then the cycle does not start, but something seems to me that this is quite a collective farm and there should be some kind of elegant option. Knowledge is very weak, but I want to solve the problem.
It is desirable without ready-made solutions, but simply write an algorithm, even in words. Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2019-08-06
@Katsimoto

const parts = [
  [0, 1],
  [0, 1, 2, 3],
  [0, 1, 2],
  [0, 1, 2, 3, 4, 5],
  [0, 1, 2],
  [0, 1, 2, 3],
  [0, 1],
  [0, 1, 2]
];
const result = parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));

console.log(result.map(a => a.join(', ')));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question