Skip to content

Instantly share code, notes, and snippets.

@Smakar20
Created August 1, 2017 21:39
Show Gist options
  • Save Smakar20/b45a045556174cfccd629f9075303961 to your computer and use it in GitHub Desktop.
Save Smakar20/b45a045556174cfccd629f9075303961 to your computer and use it in GitHub Desktop.
null created by smakar20 - https://repl.it/JsoE/0
/*Given an array of numbers, replace each number with the product of all the numbers in the array except the number itself *without* using division.*/
//method 1
/*(function(inp){
if(inp.length <= 0) return "not a valid input"
let out = []
for(var i = 0; i < inp.length; i++){
let prod1 = 1;
let prod2 = 1;
for(var j = 0; j < i; j++){
prod1 *= inp[j];
}
console.log("prod1: ", prod1)
if(i != inp.length - 1){
for(var k = i+1; k < inp.length; k++){
prod2 *= inp[k];
}
console.log("prod2: ", prod2);
}
out.push(prod1 * prod2);
}
return out;
}([1,2,3]))*/
//method2
(function(inp){
if(inp.length <= 0) return "not a valid input"
let out = []
let prev = 1
let prod1 = 1
for(var i = 0; i < inp.length; i++){
let prod2 = 1
prod1 *= prev
prev = inp[i]
if(i != inp.length - 1){
for(var k = i+1; k < inp.length; k++){
prod2 *= inp[k]
}
}
out.push(prod1 * prod2)
}
return out;
}([2,3,4]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment