Skip to content

Instantly share code, notes, and snippets.

@oliverfoster
Created October 19, 2022 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliverfoster/91b419c08bc2be41c49c0c144f0b89a4 to your computer and use it in GitHub Desktop.
Save oliverfoster/91b419c08bc2be41c49c0c144f0b89a4 to your computer and use it in GitHub Desktop.
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