Created
March 3, 2024 06:28
-
-
Save leyanlo/f34de115302f96b02faaac028bee73c8 to your computer and use it in GitHub Desktop.
Pancake Flipper
This file contains hidden or 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
// pancakes are sorted if they are ordered from 1 to N | |
function isSorted(pancakes) { | |
return pancakes.every((p, i) => p === i + 1); | |
} | |
function flip(pancakes) { | |
const instructions = ['']; | |
while (!isSorted(pancakes)) { | |
const maxUnsorted = pancakes.findLastIndex((p, i) => p !== i + 1) + 1; | |
const flipCount = pancakes.indexOf(maxUnsorted) + 1; | |
if (flipCount > 1) { | |
pancakes.splice(0, flipCount, ...pancakes.slice(0, flipCount).reverse()); | |
instructions.push(`Flip ${flipCount} pancakes: ${pancakes.join(', ')}`); | |
} | |
pancakes.splice( | |
0, | |
maxUnsorted, | |
...pancakes.slice(0, maxUnsorted).reverse() | |
); | |
instructions.push(`Flip ${maxUnsorted} pancakes: ${pancakes.join(', ')}`); | |
} | |
return instructions.map((instr, i) => instr && `${i}. ${instr}`).join('\n'); | |
} | |
test('flip', () => { | |
expect(flip([3, 1, 4, 5, 9, 2, 6, 8, 7])).toBe(` | |
1. Flip 5 pancakes: 9, 5, 4, 1, 3, 2, 6, 8, 7 | |
2. Flip 9 pancakes: 7, 8, 6, 2, 3, 1, 4, 5, 9 | |
3. Flip 2 pancakes: 8, 7, 6, 2, 3, 1, 4, 5, 9 | |
4. Flip 8 pancakes: 5, 4, 1, 3, 2, 6, 7, 8, 9 | |
5. Flip 5 pancakes: 2, 3, 1, 4, 5, 6, 7, 8, 9 | |
6. Flip 2 pancakes: 3, 2, 1, 4, 5, 6, 7, 8, 9 | |
7. Flip 3 pancakes: 1, 2, 3, 4, 5, 6, 7, 8, 9`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment