- Related Questions & Answers
- Split Array by part base on N count in JavaScript
- Count rotations of N which are Odd and Even in C++
- Find and replace a part of URL records in MySQL?
- How to find all partitions of a multiset, where each part has distinct elements in JavaScript
- Find if a number is part of AP whose first element and difference are given using C++.
- Count of strings where adjacent characters are of difference one in C++
- Count numbers from range whose prime factors are only 2 and 3 in C++
- HTML5 and Amazon S3 Multi-Part uploads
- Find k numbers which are powers of 2 and have sum N in C++
- How to search and display the pathname part of the href attribute of an area with JavaScript?
- Sorting only a part of an array JavaScript
- Count frequency of k in a matrix of size n where matrix(i, j) = i+j in C++
- Count numbers upto N which are both perfect square and perfect cube in C++
- Sum of first N natural numbers which are divisible by 2 and 7 in C++
- Count pairs (a, b) whose sum of squares is N (a^2 + b^2 = N) in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

We are required to write a JavaScript function that takes in a number. The function should divide the number into chunks according to the following rules −

The number of chunks should be a power−of−two,

Each chunk should also have a power-of-two number of items (where size goes up to a max power of two, so 1, 2, 4, 8, 16, 32, 32 being the max)

Therefore, for example, 8 could be divided into 1 bucket −

[8]

9 could be −

[8, 1]

That works because both numbers are powers of two, and the size of the array is 2 (also a power of two).

Let's try 11 −

[8, 2, 1]

Nope that doesn't work.

Because the size of the array is 3 which is not a power of two, even though it adds to 11.

[4, 4, 2, 1]

That works! It's 4 elements which is a power of two.

The code for this will be −

function permuteCombinations(n, maximum){ const maxPowerOf2 = 1 << maximum; const m = ~~(n / maxPowerOf2); const A = new Array(maximum + 1).fill(0); A[maximum] = m; let num = n − m * maxPowerOf2; let p = 0; let bitCount = 0; while (num){ if (num & 1){ bitCount += 1; A[p] = 1; } num >>= 1; p += 1; } const min = m + bitCount; let target = 1; while (target < min) target *= 2; if (target > n) return −1; if (target == min) return A.map((c, p) => [1 << Number(p), c]); if (target == n) return [n]; target = target − min; let i = m ? maximum : p; while (target && i > 0){ if (!A[i]){ i −= 1; continue; } const max = Math.min(target, A[i]); A[i] −= max; A[i−1] += 2*max; target −= max; i −= 1; } return target ? −1 : A.map((c, p) => [1 << Number(p), c]); }; console.log(permuteCombinations(11, 5));

And the output in the console will be −

[ [ 1, 1 ], [ 2, 1 ], [ 4, 2 ], [ 8, 0 ], [ 16, 0 ], [ 32, 0 ] ]

Advertisements