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.
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.