I'm not that good at js
,but I'll try to show you how to solve the problem and will provide you some code in c++
that is very similar to js
.
At first, you must know the number of elements in the array
this is a js
code here.
var arr=["a","b","c"];
var l=arr.length;
Now here is the main idea:
The number of the all possible permutations, without the repeated elements is 2^l
, l is the number of elements.
For arr
above, the number of the all possible permutations is 2^3=8
, which also equals (111) in binary +1
, the +1
is for the empty set.
If you count from 0 to 7 you will have 8 elements. it's the same if you counted from (000) to (111) in binary.
The result of counting is:
000
001
010
011
100
101
110
111
and if you looked for the zeros and ones(you might say true or false), they would present the number of the all possible permutations without the repetition.(000:choose no element,001:choose the last element,..., 101 choose the first and last element,...,111:choose all elements).
So now you could make a function that would generate the set {"","a","b","c","ab","ac","bc","abc"}
.
Now you will need to find the possible mixes for the elements with more than one element. I don't know what is that in js
, but in c++
I usually use next_permutation.
When you find the binary number, the number of the digits must be as the same as the number of the elements of the array.
//the code of converting the decimal number to binary.
strint tobinary(int l,int n){
int x;
string str="";
//the while statement finds the binary equivalent
while(n!=0){
x=n/2;
n=n%2;
str=(x+'0')+str; //the '0' is equal to 48(the ASCII code of 0)
}
//the while statement adds zeros to the left of the binary number until it's length is equal to the number of the elements.
while(str.length()!=l)
str="0"+str;
return str;
}
you must now define a vector or a dynamic array, and for 2^l
times find the elements that are the opposites of the ones in the string str
.
IF you want to find something like permutations in javascript, see here.
I hope my answer will help you;