I'm trying to find a way to distribute 2 arrays equally for example I got
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,1,1,1,1]
// this one has to be true:
console.log(distributed.length === a.length b.length)
CodePudding user response:
- make sure the first parameter is the bigger array
- calculate ratio between two arrays
- iterate them both, if the iteration index is divided by (ratio 1) with remainder -> pick a value from the bigger array, else -> pick a value from the smaller array.
Original question answer:
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);
Edited question answer:
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 b.length) {
distributed.push((iA iB) % (ratio 1) > 0 ? a[iA ] : b[iB ]);
}
return distributed;
}
const distributed = distrubute(a, b);
console.log(distributed);
CodePudding user response:
May another short way
function distribute(a, b) {
const distance = a.length / b.length 1;
return a.map((val, index) => {
if (index % distance === 0) { return b[index / distance]; }
else { return val; }
});
}
// 0,1,1,1,1,0,1,1,1,1,0,1,1,1,1,0
function distribute(a, b) {
const distance = a.length / b.length;
return a.flatMap((val, index) => {
if (index % distance === 0) { return [b[index / distance], val]; }
else { return val; }
});
}
// 0,1,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1