I have an array of 2 different values and they need to be distributed evenly.
For example:
array = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2]
and the result I want is:
array = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
But also if the ratio is not 1:1 it should be distributed as evenly as possible:
array = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2]
result = [1, 1, 2, 1, 1, 2, 1, 1, 1, 2]
or
array = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2]
result = [1, 1, 1, 1, 1, 2, 1, 1, 1, 1]
What would be the best way to get this working?
I have tried the following, but it only works for my first example:
evenDistribute(array1, array2) {
const longest = array1.length > array2.length ? array1 : array2;
const shortest = array1.length > array2.length ? array2 : array1;
const ratio = Math.floor(longest.length / shortest.length);
const results = [];
for (let i = 0; i < shortest.length; i++) {
for (let j = 0; j < ratio; j++) {
results.push(longest[i * ratio + j]);
}
results.push(shortest[i]);
}
// Grab any that are left over
for (let i = longest.length - (longest.length % shortest.length); i < longest.length; i++) {
results.push(longest[i]);
}
return results;
}