JSFiddle - React, Tailwind, and code Playground
HTML
<div id="output">
</div>
JavaScript
const flip = (list, start) => {
// Reverses the list from 0 to start.
return list.slice(0, start+1).reverse().concat(list.slice(start+1));
};
const print = (str = '') => {
document.getElementById('output').innerHTML += str + '<br>';
};
const pancake = list => {
if (list.length > 1) {
// Pancake sort the list.
let largestIndex = 0;
// Find the index of the largest value, we will flip the stack at this point.
for (let i=0; i<list.length; i++) {
largestIndex = list[i] > list[largestIndex] ? i : largestIndex;
}
// Insert the spatula at the largest index.
let stack = list.slice(largestIndex);
// Flip the stack, moving the largest pancake to the top.
stack = flip(stack, stack.length - 1);
// Get the bottom portion of the list, below the stack and re-combine.
let newList = list.slice(0, largestIndex).concat(stack);
// Finally, flip the entire list, moving the latest pancake to the bottom.
newList = flip(newList, newList.length - 1);
// Continue from the next pancake layer up.
return [newList[0]].concat(pancake(newList.slice(1)));
}
else {
return list;
}
};
const list1 = [5, 2, 3, 1, 4];
const list2 = Array.from(Array(10).keys()).sort(_ => Math.random() - .5);
const list3 = Array.from(Array(100).keys()).sort(_ => Math.random() - .5);
print(list1);
print();
print('k=0');
print(flip(list1, 0));
print('k=2');
print(flip(list1, 2));
print('k=4');
print(flip(list1, 4));
print(pancake(list1));
print();
print(list2);
print(pancake(list2));
print();
print(list3);
print(pancake(list3));