Skip to content

Instantly share code, notes, and snippets.

@manzaloros
Last active October 29, 2020 16:43
Show Gist options
  • Save manzaloros/2145c172e4a9a92aed6ceec58f800021 to your computer and use it in GitHub Desktop.
Save manzaloros/2145c172e4a9a92aed6ceec58f800021 to your computer and use it in GitHub Desktop.
const maxDistToClosest = (seats,
[maxDist, i, j] = [0, 0, 1],
{ length } = seats) => {
const leftSeatOccupied = () => seats[i] === 1;
const rightSeatOccupied = () => seats[j] === 1;
const isEndOfRow = () => (j + 1) === length;
const distanceToEndOfRow = () => j - i;
const distanceBetweenSeats = () => Math.ceil(((j - 1) - i) / 2);
const seatsLeftInRow = () => j < length;
const checkNextRightSeat = () => j += 1;
const checkNextGap = () => i = j++;
const areBetweenOccupiedSeats = () => rightSeatOccupied() && leftSeatOccupied();
while (seatsLeftInRow()) {
while (!rightSeatOccupied() && !isEndOfRow()) {
checkNextRightSeat();
}
maxDist = areBetweenOccupiedSeats()
? Math.max(maxDist, distanceBetweenSeats())
: Math.max(maxDist, distanceToEndOfRow())
checkNextGap();
}
return maxDist;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment