Answer the question
In order to leave comments, you need to log in
js. How to count the number of combinations of digits in a number?
I have a number that can only contain two digits - 1 and 2 (The number of ones and twos can be different).
How can I find the number of all combinations of this number, excluding duplicates?
For example:
Answer the question
In order to leave comments, you need to log in
function nextLexInPlace(arr) {
let i, a = -1, b = -1;
for( i = 0; i < arr.length-1; i++) if(arr[i] < arr[1+i]) a = i;
if( !~a) return; // no more permutations
for( i = a + 1; i < arr.length; i++) if(arr[a] < arr[i]) b = i;
swap(arr, a, b);
a++;
b = arr.length - 1;
while( a < b) swap(arr, a++, b--);
return true;
}
function swap( arr, a, b) {
let xx = arr[a];
arr[a] = arr[b];
arr[b] = xx;
}
function allMutations( source ) {
let result = [], arr = Array.from(String(source)).slice();
result.push( arr.sort().slice());
while( nextLexInPlace(arr)) result.push(arr.slice());
return result.join('..').replace(/,/g,'')
}
console.log(allMutations(112))
console.log(allMutations(1112))
console.log(allMutations(11122))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question