我正在嘗試找到一種方法來平均分配 2 個陣列,例如我得到了
let a = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
let b = [0,0,0,0]
function distrubute(a, b){
//I need help with this function
return ?
}
let distributed = distribute()
console.log(distributed)
// [0,1,1,1,1,0,1,1,1,1,0,1,1,1,1,0]
uj5u.com熱心網友回復:
- 確保第一個引數是更大的陣列
- 計算兩個陣列之間的比率
- 迭代它們,如果迭代索引除以 (ratio 1) 余數 -> 從較大的陣列中選擇一個值,否則 -> 從較小的陣列中選擇一個值。
const a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
const b = [0, 0, 0, 0]
function distrubute(a, b) {
if (a.length < b.length) return distribute(b, a);
const distributed = [];
const ratio = a.length / b.length;
let iA = 0,
iB = 0;
while (iA iB < a.length) {
distributed.push((iA iB) % (ratio 1) > 0 ? a[iA ] : b[iB ]);
}
return distributed;
}
const distributed = distrubute(a, b);
console.log(distributed);
uj5u.com熱心網友回復:
愿另一條捷徑
function distribute(a, b) {
const distance = a.length / b.length 1;
return a.flatMap((val, index) => {
if (index % distance === 0) { return b[index / distance]; }
else { return val; }
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/507712.html
標籤:javascript 数学
