Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Created May 17, 2019 18:34
Show Gist options
  • Save jasonwaters/fb8242d4768d40a539a67a78082d9fdf to your computer and use it in GitHub Desktop.
Save jasonwaters/fb8242d4768d40a539a67a78082d9fdf to your computer and use it in GitHub Desktop.
Return an Array of integers by multiplying all elements in given array except the current index integer.
const a = [1,2,3, 2];
 
function multiplify(arr) {
const total = arr.reduce((acc, item) => {
return acc * item;
}, 1);
return arr.map((el) => total/el)
}
console.log(multiplify(a));
@jasonwaters
Copy link
Author

jasonwaters commented May 22, 2019

function productify_easy(arr) {
  const total = arr.reduce((tot, value) => tot * value, 1);
  return arr.map(value => total/value);
}

function productify_l_r(arr) {
  const leftProd =[];
  const rightProd = [];
  
  let tmpProduct = 1;

  for(let i=0;i<arr.length;i++) {
    tmpProduct = i===0 ? 1 : tmpProduct * arr[i-1];
    leftProd[i] = tmpProduct;
  }
  
  tmpProduct=1;
  
  for(let i=arr.length-1;i>=0;i--) {
    tmpProduct = i===arr.length-1 ? 1 : tmpProduct * arr[i+1]
    rightProd[i] = tmpProduct;
  }
  
  return leftProd.map((value, idx) => value * rightProd[idx]);
}

function productify(arr) {
  const left =[];
  const solution = [];
  
  let tmp = 1;

  for(let i=0;i<arr.length;i++) {
    tmp = i===0 ? 1 : tmp * arr[i-1];
    left[i] = tmp;
  }
  
  tmp=1;
  
  for(let i=arr.length-1;i>=0;i--) {
    tmp = i===arr.length-1 ? 1 : tmp * arr[i+1]
    solution[i] = left[i]*tmp;
  }
  
  return solution;
}

//[80, 64, 320, 40, 160]

console.log(productify([4,5,1,8,2]));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment