Created
December 25, 2022 05:30
-
-
Save thmain/4d41693346c859fd60b108824680cfe9 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 productPuzzle(data) { | |
var len = data.length | |
var left = new Array(len) | |
var right = new Array(len) | |
// prepare the left array | |
left[0] = 1 | |
for(let i = 1; i < len; i++) | |
left[i] = left[i-1] * data[i-1] | |
console.log(left) // [ 1, 1, 2, 6 ] | |
// prepare the right array | |
right[len-1] = 1 | |
for (let j = len-2; j >= 0; j-- ) | |
right[j] = right[j+1] * data[j+1] | |
console.log(right) // [ 24, 12, 4, 1 ] | |
return data.map((el, index) => { | |
return left[index] * right[index] | |
}) | |
} | |
console.log(productPuzzle([1, 2, 3, 4])) // [ 24, 12, 8, 6 ] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment