Skip to content

Instantly share code, notes, and snippets.

@swang
Created September 29, 2016 22:17
Show Gist options
  • Select an option

  • Save swang/ef4747e17350072c03adba3ecf8eabbf to your computer and use it in GitHub Desktop.

Select an option

Save swang/ef4747e17350072c03adba3ecf8eabbf to your computer and use it in GitHub Desktop.
Locker Problem
// fill an 100-element array with zero (0 = closed, 1 = open)
let lockers = new Array(100).fill(0)
// iterate 1-100 in outer loop, iterate i-100, jumping to every i-th term
for (let i = 1; i <= 100; i++) {
for (let j = i; j <= 100; j += i) {
// flip switch on locker value
lockers[j - 1] = !lockers[j - 1] ? 1 : 0
}
}
// output where arr[i] is truthy (1) then appends i + 1 to final array
console.log(lockers.reduce((p, c, i, arr) => {
if (arr[i]) { return p.concat(i + 1) }
else { return p }
}, []))
// [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment