Skip to content

Instantly share code, notes, and snippets.

@tshddx
Last active December 8, 2021 22:27
Show Gist options
  • Save tshddx/5e0d7ea0394f2afac4abbf6ce109b339 to your computer and use it in GitHub Desktop.
Save tshddx/5e0d7ea0394f2afac4abbf6ce109b339 to your computer and use it in GitHub Desktop.
Solution to hallway challenge from "Fake coding interview with Dan Abramov"
// From: https://youtu.be/-w-P4u0x8ig?t=3075
function countMeetings(hallway) {
// Let's go over the hallway from left to right and keep track of how many
// people are moving right behind us at that point. Each time we encounter
// someone moving left, we know they will meet everyone who is moving right
// behind us at that point, so we add that number to the meetings count.
let peopleMovingRightBehindUs = 0;
let meetings = 0;
for (const char of hallway) {
if (char === '>') {
peopleMovingRightBehindUs += 1;
} else if (char === '<') {
meetings += peopleMovingRightBehindUs;
} else if (char === '-') {
// Do nothing
} else {
throw `Unexpected character in input`;
}
}
return meetings;
}
const testCases = [
[`<---->---<---<-->`, 4],
[`------`, 0],
[`>>>>>>>>>>>>>>>>>>>>>----<->`, 42],
[`<<----<>---<`, 2],
[`>`, 0],
];
testCases.forEach(([hallway, correctResult], index) => {
const salutes = countMeetings(hallway) * 2;
console.log({ index, expected: correctResult, got: salutes });
});
// Output:
// {index: 0, expected: 4, got: 4}
// {index: 1, expected: 0, got: 0}
// {index: 2, expected: 42, got: 42}
// {index: 3, expected: 2, got: 2}
// {index: 4, expected: 0, got: 0}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment