Skip to content

Instantly share code, notes, and snippets.

@Lavrend
Created May 16, 2019 23:03
Show Gist options
  • Save Lavrend/93356605b038418a5c6b6fda18fb9e31 to your computer and use it in GitHub Desktop.
Save Lavrend/93356605b038418a5c6b6fda18fb9e31 to your computer and use it in GitHub Desktop.
Finds the number taken from the mixed array of numbers from 1 to N
// Values for test
const N = 100;
const pos = 34;
const baseArr = Array.from({ length: N }, (v, k) => k + 1);
const removedArr = baseArr.filter(item => item !== pos + 1).sort(() => 0.5 - Math.random());
// -----------------------------------------------------------------------------------------
// Main method
const getRemovedNumber = (arr, maxNumber) => {
const baseSum = (maxNumber * (maxNumber + 1)) / 2;
return baseSum - arr.reduce((memo, val) => memo + val, 0);
};
// Test
console.log(baseArr[pos] === getRemovedNumber(removedArr, N)); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment