Created
October 19, 2022 15:00
-
-
Save oliverfoster/91b419c08bc2be41c49c0c144f0b89a4 to your computer and use it in GitHub Desktop.
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 multiplyOut (matrix) { | |
const partLengths = matrix.map(part => part.length) // how large each part is [3, 3, 2] | |
const subPartIndices = '0'.repeat(matrix.length).split('').map(Number) // how far we've gone in each part [0, 0, 0] | |
let isEnded = false | |
const sumsToPerform = [] | |
while (isEnded === false) { | |
sumsToPerform.push(subPartIndices.reduce((sum, subPartIndex, partIndex) => { | |
sum.push(matrix[partIndex][subPartIndex]) | |
return sum | |
}, [])) | |
isEnded = !subPartIndices.some((subPartIndex, partIndex) => { | |
subPartIndex++ | |
if (subPartIndex < partLengths[partIndex]) { | |
subPartIndices[partIndex] = subPartIndex | |
return true | |
} | |
subPartIndices[partIndex] = 0 | |
return false | |
}) | |
} | |
return sumsToPerform | |
} | |
console.log(multiplyOut([[1, 2, 3], [10, 20, 30], [100, 200]])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment