0

I want to create a method in JavaScript which can generate an array containing non-random and non-duplicate numbers by using Tree structure.

Assuming the method named permutation(), I just simply use

permutation(3)

and I will get an array which can iterate and each of them is

012 021 120 102 201 210

if I change the number 3 to 5 , it will generate an Array

012345 012354 etc...

and then I figure out I can use tree structure to build this kind of array like this:

root:     0      1      2 
        ↓   ↓  ↓   ↓  ↓   ↓
depth1: 1   2  0   2  1   0
        ↓   ↓  ↓   ↓  ↓   ↓
depth2: 2   1  1   0  0   1

then I just traverse all the nodes to get the result.

It's same when the number is increased

root:           0               1   2   3   4   5   6....
        ↓   ↓   ↓   ↓   ↓   ↓
depth1: 1   2   3   4   5   6

etc....

The question is I don't know how could I construct such a tree in JavaScript? I don't know what kind of these questions named.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Ling
  • 21
  • 2
  • Possible duplicate of [Permutations in JavaScript?](https://stackoverflow.com/questions/9960908/permutations-in-javascript) – adiga Jun 05 '19 at 07:50

1 Answers1

0

You could take the array and get a sub tree for every leftover items.

function createTree(array) {
    return array.map((v, i, a) => array.length === 1
        ? [v]
        : [v, createTree([...a.slice(0, i), ...a.slice(i + 1)])]
    );
}

var result = createTree([0, 1, 2]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392