Skip to content

Instantly share code, notes, and snippets.

@ultim8k
Created November 24, 2018 00:22
Show Gist options
  • Save ultim8k/4a70ab4fdd46de18686cf1c8ac805547 to your computer and use it in GitHub Desktop.
Save ultim8k/4a70ab4fdd46de18686cf1c8ac805547 to your computer and use it in GitHub Desktop.
Create array of (n) items that their sum is 0
// var n = 6;
// var ppp = new Array(n).fill(0).map((_, i) =>
// n % 2 // if n is odd
// ? i === 0 // if index is 0
// ? 0 // return 0
// : i % 2 // if index is odd
// ? i + 1 // return index + 1
// : - i // return - index
// : i % 2 // if index is odd
// ? - i // return - index
// : i + 1 // return index + 1
// );
// console.log(ppp); // check array
// console.log(ppp.reduce((acc, cur) => acc + cur)); // check array sum of items
const crap = n => new Array(n).fill(0).map((_, i) => n % 2 ? i === 0 ? 0 : i % 2 ? i + 1 : - i : i % 2 ? - i : i + 1);
const test = (n) => (crap(n).length === n) && (crap(n).reduce((acc, cur) => acc + cur) === 0);
console.log(test(1))
console.log(test(2))
console.log(test(3))
console.log(test(4))
console.log(test(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment