A
A
Andrey2021-07-12 06:39:33
JavaScript
Andrey, 2021-07-12 06:39:33

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:

  • number 112 - number of combinations - 3 (112, 121, 211),
  • number 1112 - 4 combinations (1112, 1121, 1211, 2111)
  • number 11122 - 9 combinations (11122, 11212, 12112, 21112, 21121 ...)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
lssssssssssl, 2021-07-12
@andreyfilippov3001

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))

Solution: How to make all possible combinations? Sergey Sokolov
Slightly modified for a specific situation

R
Rsa97, 2021-07-12
@Rsa97

(N 1 + N 2 )! / (N 1 ! * N 2 !)

A
Alice, 2021-07-12
@w3bsmes

Hold

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question