給出以下陣列
[10, 10, 10, 50, 50, 100, 100, 100, 500, 500, 500, 1000, 1000, 1000, 5000]
我現在想回圈輸出這些數字與 0 的所有組合。每個數字可以單獨出現,也可以與陣列中的任何其他數字一起出現(其余數字應為 0)。數字組合在一起時,應保持數字的原始位置。
原始陣列的數字應保留在原位,并且只能替換為零或不替換。
陣列的大小始終保持不變。所以沒有額外添加零。因此,不可能在原始陣列的數字之間插入零以增加陣列的長度。
由于示例輸入有三個 10,因此例如可能有前 10,然后是 0,然后又是 10。
對組合產生的順序沒有要求。
我只想通過以下示例闡明我的想法。
[10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 10, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 10, 10, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 50, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 50, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 10, 50, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 10, 10, 50, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 50, 50, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 10, 10, 50, 50, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 10, 50, 50, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 50, 50, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
在這里進行的最佳方式是什么?
uj5u.com熱心網友回復:
該任務實際上轉化為生成 15 個二進制數字的二進制數,其中 0 表示“生成 0”,而 1 表示“從該位置的輸入復制數字”。
很明顯,有 2 15 種組合,因為這是您可以使用 15 位生成的數字數量。
因此,JavaScript 中的實作可能是:
let input = [10, 10, 10, 50, 50, 100, 100, 100, 500, 500, 500, 1000, 1000, 1000, 5000];
let quit = 20; // For demo purpose, let's stop after 20 outputs...
let count = Math.pow(2, 15); // Total number of combinations
for (let i = 0; i < count; i ) { // For each combination
let combi = []; // Create new empty array
for (let bit = 0, bits = i; bit < 15; bit , bits >>= 1) {
// Depending on bit, either append 0 or the input to the array
combi.push(bits & 1 ? input[bit] : 0);
}
console.log(...combi); // Output all values in the array
if (quit-- < 0) break; // For this demo only
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343078.html
