Created
May 17, 2018 02:23
-
-
Save HeilTec/d0aff148a943e29c9c6c436ce0b5fb5a to your computer and use it in GitHub Desktop.
The Best Time to Party
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// (Impure) Functional javascript kata inspired by | |
// Puzzle 2: The Best Time to Party | |
// MIT 6.S095 Programming for the Puzzled, IAP 2018 | |
// https://youtu.be/a1RaIqkdG0c | |
// Assuming that the list of celebrities can be very large | |
// and the number of hours are limited (small) | |
// This solution only traverses the list once | |
// Celebrities arrival and departure times | |
const celebrities = [ | |
[6, 7], | |
[7, 9], | |
[10, 11], | |
[10, 12], | |
[8, 10], | |
[9, 11], | |
[6, 8] | |
] | |
// inc: increment array element using 0 for empty | |
const inc = mutableArray => | |
index => | |
(mutableArray[index] = (mutableArray[index] || 0) + 1) | |
// count: reducer to count celebrities present at any hour | |
const count = (accAry, [arrival, departure]) => { | |
// console.log(arrive, depart) | |
const incInAry = inc(accAry) | |
for (var t = arrival; t < departure; t++) { | |
incInAry(t) | |
} | |
// console.log(accAry) | |
return accAry | |
} | |
let time | |
const max = (acc, n, i) => | |
(n || 0) > acc | |
? ((time = i), n) | |
: acc | |
console.log('Result') | |
console.log( | |
'There will be ' + | |
celebrities | |
.reduce(count, []) | |
.reduce(max, 0) + | |
' celebrities present') | |
console.log('if you arrive at ' + time) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment