Created
October 3, 2019 10:57
-
-
Save bartwttewaall/34e0c6f85a440de70e498f61e52782c8 to your computer and use it in GitHub Desktop.
An algorithm that divides items from one or more arrays over one or more output arrays, all in a single for-loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function divideEvenly(arrays, numOutputs) { | |
const arraysLength = arrays.length; | |
const totalLength = arrays.reduce((amount, pool) => amount + pool.length, 0); | |
const result = []; | |
let pool, item, column; | |
for (let i = 0; i < totalLength; i++) { | |
pool = arrays[i % arraysLength]; | |
item = pool[Math.floor(i / arraysLength)]; | |
column = Math.floor(i / (totalLength / numOutputs)); | |
if (result.length <= column) result.push([]); | |
result[column].push(item); | |
} | |
return result; | |
} | |
// ---- tests ---- | |
const numbers = [1, 2, 3, 4, 5, 6]; | |
const chars = ['a', 'b', 'c', 'd', 'e', 'f']; | |
const exes = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6']; | |
console.log(divideEvenly([numbers, chars, exes], 3)); | |
// [1, "a", "x1", 2, "b", "x2"] | |
// [3, "c", "x3", 4, "d", "x4"] | |
// [5, "e", "x5", 6, "f", "x6"] | |
console.log(divideEvenly([numbers, chars, exes], 6)); | |
// [1, "a", "x1"] | |
// [2, "b", "x2"] | |
// [3, "c", "x3"] | |
// [4, "d", "x4"] | |
// [5, "e", "x5"] | |
// [6, "f", "x6"] | |
console.log(divideEvenly([numbers], 3)); | |
// [1, 2] | |
// [3, 4] | |
// [5, 6] | |
console.log(divideEvenly([numbers], 2)); | |
// [1, 2, 3] | |
// [4, 5, 6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment