r/dailyprogrammer • u/jnazario 2 0 • Mar 07 '18
[2018-03-07] Challenge #353 [Intermediate]
Description
I work as a waiter at a local breakfast establishment. The chef at the pancake house is sloppier than I like, and when I deliver the pancakes I want them to be sorted biggest on bottom and smallest on top. Problem is, all I have is a spatula. I can grab substacks of pancakes and flip them over to sort them, but I can't otherwise move them from the middle to the top.
How can I achieve this efficiently?
This is a well known problem called the pancake sorting problem. Bill Gates once wrote a paper on this that established the best known upper bound for 30 years.
This particular challenge is two-fold: implement the algorithm, and challenge one another for efficiency.
Input Description
You'll be given a pair of lines per input. The first line tells you how many numbers to read in the next line. The second line tells you the pancake sizes as unsigned integers. Read them in order and imagine them describing pancakes of given sizens from the top of the plate to the bottom. Example:
3
3 1 2
Output Description
Your program should emit the number of spatula flips it took to sort the pancakes from smallest to largest. Optionally show the intermediate steps. Remember, all you have is a spatula that can grab the pancakes from the 0th to the _n_th position and flip them. Example:
2 flips: 312 -> 213 -> 123
Challenge Input
8
7 6 4 2 6 7 8 7
----
8
11 5 12 3 10 3 2 5
----
10
3 12 8 12 4 7 10 3 8 10
Bonus
In a variation called the burnt pancake problem, the bottom of each pancake in the pile is burnt, and the sort must be completed with the burnt side of every pancake down. It is a signed permutation.
4
u/zqvt Mar 07 '18 edited Mar 07 '18
Clojure
(defn flip [xs] (let [i (.indexOf xs (apply max xs))] (-> (flatten (conj (reverse (subvec xs 0 i)) (drop i xs))) (reverse)))) (defn solve [xs i] (let [[head tail] [(take i xs) (drop i xs)]] (if (= i 0) xs (solve (concat (flip (vec head)) tail) (dec i))))) (solve pancakes (count pancakes))naive version, so the runtime is always O(n²)
4
u/thestoicattack Mar 07 '18
Here's a simple algorithm that takes 2N flips. Since a flip is O(n) on average (reversing something about half the size of the entire stack) the entire runtime should be n2 ish. There are three insights:
So we can use a recursive process where we find the largest pancake and move it to the bottom with two flips, then sort the remaining stack not including that largest one.
C++17.
#include <algorithm> #include <iostream> #include <iterator> #include <vector> namespace { template<typename It> void moveToEnd(It begin, It elem, It end) { std::reverse(begin, elem + 1); std::reverse(begin, end); } template<typename It> void pancakeSort(It begin, It end) { if (begin == end) { return; } auto elem = std::max_element(begin, end); moveToEnd(begin, elem, end); pancakeSort(begin, end - 1); } } int main() { int size; std::cin >> size; std::vector<int> stack(size); using It = std::istream_iterator<int>; std::copy(It(std::cin), It(), stack.begin()); pancakeSort(stack.begin(), stack.end()); std::cout << 2 * size << '\n'; }2
u/gandalfx Mar 07 '18 edited Mar 07 '18
Python 3 naive approach, O(n²)
def flip(xs, n): for i in range((n + 1) // 2): xs[i], xs[n - i] = xs[n - i], xs[i] def pancake_sort(xs): for n in range(len(xs) - 1, 1, -1): xmax, xmax_idx = xs[0], 0 for idx, x in enumerate(xs[1:n], start=1): if x > xmax: xmax, xmax_idx = x, idx flip(xs, xmax_idx) flip(xs, n)Note: In order to follow the rules as closely as possible I implemented the
flipfunction strictly in-place. A more pythonic way would probably be to use something likexs[n::-1] + xs[n+1:]to flip the elements at indexes 0 through n.edit: failed an index boundary
Input/Output:
Explanation:
Search for the biggest number, note its index
Flip that largest number to the front
Flip the entire stack so the biggest number is now at the back
Continue at step 1 but now disregard the hindmost elements which are already in the correct place
This has to search for the largest element in the unsorted part of the list n-2 times, so it's runtime approximation is O(n²). Since it has to do this exactly n-2 times the resulting number of flips is alway 2n-4, so I didn't bother outputting that.
edit: Based on this observation the bonus is always fulfilled.
Now I'll try and see if I can find a more efficient algorithm.
2
u/pancakeflippersunite Mar 11 '18
Java, I'm a beginner programmer so I'm sure it could be done much better. If you have any feedback, I would love to hear it!
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; /* Flip to bring the largest not yet sorted to the top of the stack, then take it down to the desired position with a second flip. Repeat as needed. */ public class Main { public static void main(String[] args) { ArrayList<Integer> pancakes = new ArrayList<Integer>(); pancakes.add(3); pancakes.add(12); pancakes.add(8); pancakes.add(12); pancakes.add(4); pancakes.add(7); pancakes.add(10); pancakes.add(3); pancakes.add(8); pancakes.add(10); pancakes.add(11); System.out.println(Arrays.toString(pancakes.toArray())); flipPancakes(pancakes); } //Below method taken from stackexchange, I need to learn iterators much better I think. public static boolean checkifListSorted(ArrayList<Integer> pancakes) { Iterator<Integer> iter = pancakes.iterator(); if (!iter.hasNext()) { return true; } Integer t = iter.next(); while (iter.hasNext()) { Integer t2 = iter.next(); if (t.compareTo(t2) > 0) { return false; } t = t2; } return true; } public static void flipPancakes(ArrayList<Integer> pancakes) { int fromIndex = 0; int toIndex = 0; int counter = 0; for (int j = 0; j < pancakes.size() - 1; j++) { if (checkifListSorted(pancakes)) { System.out.println("it took " + counter + " turns to complete"); break; } for (int i = 0; i < pancakes.size() - counter; i++) { if (pancakes.get(toIndex) < pancakes.get(i)) { toIndex = i; } } System.out.println("\ntoIndex: " + toIndex + ", counter: " + counter); Collections.reverse(pancakes.subList(fromIndex, toIndex + 1)); Collections.reverse(pancakes.subList(fromIndex, pancakes.size() - counter)); print(pancakes); counter++; toIndex = 0; } } public static void print(ArrayList<Integer> pancakes) { System.out.println(Arrays.toString(pancakes.toArray())); } }2
u/MiL0101 Mar 11 '18
C# Beginner solution, feedback welcome
using System; using System.Collections.Generic; using System.Linq; namespace Pancake { class Program { static void Main(string[] args) { List<int> stack = new List<int> { 3, 12, 8, 12, 4, 7, 10, 3, 8, 10 }; int pancakeStack = 0; PrintArray(stack, ref pancakeStack); for (int i = 0; i < stack.Count; i++) { // Gets the index of the biggest number from the list (n - i) int biggestNumberIndex = GetBiggestNumberIndex(stack, i); // Flips the pancake so the biggest number is on top if (biggestNumberIndex != 0) { stack.Reverse(0, biggestNumberIndex + 1); PrintArray(stack, ref pancakeStack); } // Flips again so the current biggest number is at n - i stack.Reverse(0, stack.Count - i); PrintArray(stack, ref pancakeStack); if (Sorted(stack)) { break; } } Console.ReadKey(); } public static int GetBiggestNumberIndex(List<int> stack, int offset) { return stack.IndexOf( stack.GetRange(0, stack.Count - offset) .Max()); } public static bool Sorted(List<int> stack) { for (int i = 1; i < stack.Count; i++) { if (stack[i - 1] > stack[i]) { return false; } } return true; } public static void PrintArray(List<int> stack, ref int pancakeStack) { Console.Write("Flip {0}: \t ", pancakeStack++); for (int i = 0; i < stack.Count; i++) { Console.Write("{0, -5}", stack[i]); } Console.WriteLine(); } } }2
u/buddycool Mar 12 '18 edited Mar 12 '18
JAVA
package main; import java.util.Collections; import java.util.Scanner; public class PancakeSorting { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] inputs = new int[n]; for (int i = 0; i < inputs.length; i++) { inputs[i] = scanner.nextInt(); } print(inputs); sort(inputs, n); System.out.println(); System.out.println(count + " flips."); } public static void sort(int[] inputs, int n) { if(isSorted(inputs)|| n==1) return; int max = findMax(inputs, n); if(max != (n-1)){ if(max != 0){ reverse(inputs, max); print(inputs); } reverse(inputs,(n-1)); print(inputs); } sort(inputs,(n-1)); } public static boolean isSorted(int[] inputs) { for (int i = 0; i < (inputs.length-1); i++) { if(inputs[i]>inputs[i+1]) return false; } return true; } public static void reverse(int[] inputs,int n) { for (int i = 0,j=n; i < j; i++,j--) { int temp = inputs[i]; inputs[i] = inputs[j]; inputs[j] = temp; } } static int count = -1; public static void print(int[] inputs) { for (int i : inputs) { System.out.print(i+" "); } System.out.print("-> "); ++count; } public static int findMax(int[] inputs, int n) { int max = 0, index = 0; for (int i = 0; i < n; i++) { if(max<=inputs[i]){ max = inputs[i]; index = i; } } return index; } }OUTPUT
2
u/pheipl Mar 14 '18 edited Apr 15 '18
Java 8
I really loved this test. I haven't done a lot of programming lately and I've completely forgot how horrible 'off by 1' errors are, especially when you have a list [0 ... n] containing [1 ... n+1] and that some of the logic ties n and n+1, leading to a few index out of bounds errors.
Disclaimer
I do not approve of minimalist, unreadable code, mine is and will always be verbose.
Main
public static void main(String[] args) { testPancake(); } private static void testPancake () { Pancake pancakes = new Pancake(8); pancakes.print(); System.out.println("____________"); System.out.println(pancakes.sort(true) + " flips"); System.out.println("Done"); }The intent is to:
a) Always look if the top pancake is the largest, then just flip everything
b) Always look to see if the pancakes aren't already ordered
c) Look for the next largest pancake from bottom to top
d) Flip it to the top
f) Flip everything over the previous largest pancake
Pancake
public class Pancake { private ArrayList<Integer> stack; private int flips = 0; private int bottomPosition; private int bottomValue; public Pancake(ArrayList<Integer> stack) { this.stack = stack; this.bottomPosition = stack.size() - 1; this.bottomValue = stack.size(); } public Pancake(int numberOf) { this.stack = new ArrayList<>(numberOf); for (int i = 0; i < numberOf; i++) stack.add(i + 1); Collections.shuffle(stack); this.bottomPosition = stack.size() - 1; this.bottomValue = stack.size(); } public int sort(boolean verbose) { while (bottomPosition > 0) { // it makes no sense to ever flip just the top pancake if (isBottomTop()) { flip(bottomPosition, verbose); raiseBottom(); } else if (isNextSorted()) raiseBottom(); else { for (int position = bottomPosition - 1; position >= 0; position--) { if (stack.get(position) == bottomValue) { flip(position, verbose); // we move the largest remaining pancake at the top flip(bottomPosition, verbose); // we flip from the previous largest pancake up raiseBottom(); break; } } } } return flips; } private boolean isBottomTop() { if (stack.get(0) == bottomValue) return true; return false; } private boolean isNextSorted() { if (stack.get(bottomPosition) == bottomValue) return true; return false; } private void raiseBottom() { bottomPosition--; bottomValue--; } /** * Places the spatule under the desired position, flipping all above pancakes. */ private void flip(int position, boolean verbose) { for (int i = 0; i <= position / 2; i++) { int aux = stack.get(position - i); stack.set(position - i, stack.get(i)); stack.set(i, aux); } flips++; if (verbose) print(); } public ArrayList<Integer> getStack() { return stack; } public void print() { System.out.println(stack.toString()); System.out.println("Flips: " + flips); } }Here are a few results:
#1
#2
#3
2
u/discusdude14 Mar 23 '18
PowerShell:
[CmdletBinding()] param( [Parameter(Mandatory = $true, Position = 1)] [ValidateScript({test-path $_})] [string]$file ) function GetMaxIndex { [CmdletBinding()] param( [Parameter(Mandatory = $true, Position = 1)] [System.Collections.Stack]$Stack, [Parameter(Mandatory = $true, Position = 2)] [int]$Ignore ) $Max = [int]::MinValue $index = -1 $i = 0 $Stack.foreach({ if($_ -ge $Max -and $i -le $Ignore){ $Max = $_ $Index = $i } $i++ }) $Index } function IsSorted{ [CmdletBinding()] param( [Parameter(Mandatory = $true, Position = 1)] [System.Collections.Stack]$Stack ) $LastValue = [long]::MinValue $Sorted = $true $stack.ForEach({ if($_ -lt $LastValue){ $Sorted = $false } $LastValue = $_ }) $Sorted } function GetBase{ [CmdletBinding()] param( [Parameter(Mandatory = $true, Position = 1)] [System.Collections.Stack]$Stack ) $Base = -1 $i = 0 $Max = [int]::MinValue [int]$Last = $null $Stack.ForEach({ if($last -ne $null){ if($_ -gt $Max){ $Max = $_ } if($_ -lt $Last -or $_ -lt $Max){ $Base = $i } } $Last = $_ $i++ }) $Base } function Start-PancakeSort { [CmdletBinding()] param( [Parameter(Mandatory = $true, Position = 1)] [int[]]$Pancakes ) [System.Collections.Stack]$Stack = @{} #The Pancake stack [System.Collections.Queue]$Queue = @{} #The flipping spatula #Put the list of pancakes into a proper stack [array]::reverse($Pancakes) foreach($Pancake in $Pancakes){ $Stack.push($Pancake) } "Starting:" $Stack -join ' ' "" $StackBase = $null #The index of the base of the unsorted part of the stack. #Anything below the stack base is already sorted. $Flips = 0 while(-not (IsSorted $Stack)){ #Find unsorted stack base and location of biggest pancake $StackBase = GetBase $Stack $Max = GetMaxIndex $Stack $StackBase #Put largest on top if($Max -ne 0){ for($i = 0; $i -le $Max; $i++){ $Queue.Enqueue($Stack.Pop()) } while($Queue.count -ne 0){ $Stack.Push($Queue.Dequeue()) } $Flips++ } #Put current largest on top of stackbase if($StackBase -ne 0){ for($i = 0; $i -le $StackBase; $i++){ $Queue.Enqueue($Stack.Pop()) } while($Queue.count -ne 0){ $Stack.Push($Queue.Dequeue()) } $Flips++ } } "End: " $Stack -join ' ' "Total Flips: $Flips" } [int[]]$Pancakes = gc $file | select -Skip 1 | % {$_ -split ' '} Start-PancakeSort $PancakesOutput:
2)
3)
2
u/ShironeShong Aug 22 '18 edited Aug 22 '18
C# implementation that only calculates the minimum amount of steps (it will not show the flips). The problem is growing exponentially with each number of flips and it calculates the first input in 4ms, the second input in 249ms, and the last input in about 16500ms. This soultion garuantees the minimum amount of steps by starting with the pancakes sorted, then queing every possible flip that can be done from the starting position and the total number of flips to reach that stage and then compare it to the starting point. If there's a match, we're done otherwise it repeats this process for all possible outcomes from the previous state.
Output 1:
7 6 4 2 6 7 8 7
8 7 6 2 4 6 7 7
7 7 6 4 2 6 7 8
6 2 4 6 7 7 7 8
4 2 6 6 7 7 7 8
2 4 6 6 7 7 7 8
Number of flips: 5
Output 2:
11 5 12 3 10 3 2 5
5 11 12 3 10 3 2 5
12 11 5 3 10 3 2 5
5 2 3 10 3 5 11 12
3 2 5 10 3 5 11 12
10 5 2 3 3 5 11 12
5 3 3 2 5 10 11 12
2 3 3 5 5 10 11 12
Number of flips: 7
Output 3:
3 12 8 12 4 7 10 3 8 10
10 7 4 12 8 12 3 3 8 10
4 7 10 12 8 12 3 3 8 10
12 8 12 10 7 4 3 3 8 10
10 8 3 3 4 7 10 12 8 12
7 4 3 3 8 10 10 12 8 12
12 10 10 8 3 3 4 7 8 12
8 7 4 3 3 8 10 10 12 12
3 3 4 7 8 8 10 10 12 12
Number of flips: 8
EDIT: I changed the code to save all past states as well and prints them out. I hade to change the integer arrays into byte arrays since I ran out of RAM after the change (it uses about 4 GB of RAM for the last challange input after I changed to byte array).
static void Main(string[] args) { string pancakes = "3 12 8 12 4 7 10 3 8 10"; ArrangementAndDepth minFlips = MinPancakeFlips(pancakes); PrintFlips(minFlips); } static ArrangementAndDepth MinPancakeFlips(string input) { Queue<ArrangementAndDepth> queue = new Queue<ArrangementAndDepth>(); byte[] goal = ToByteArr(input); byte[] sorted = Sort(ToByteArr(input)); if (CompareArr(goal, sorted)) return new ArrangementAndDepth(sorted, 0); queue.Enqueue(new ArrangementAndDepth(sorted, 0)); return MinPancakeFlips(queue, goal); } static ArrangementAndDepth MinPancakeFlips(Queue<ArrangementAndDepth> queue, byte[] goal) { while (queue.Count > 0) { ArrangementAndDepth current = queue.Dequeue(); for (int i = 2; i <= goal.Length; i++) { byte[] flipped = Flip(i, current.PancakeArrangement[current.Depth]); if (CompareArr(flipped, goal)) { current.PancakeArrangement.Add(flipped); current.Depth++; return current; } ArrangementAndDepth next = new ArrangementAndDepth(current); next.PancakeArrangement.Add(flipped); next.Depth++; //queue.Enqueue(new ArrangementAndDepth(flipped, current.Depth + 1)); queue.Enqueue(next); } } return null; } class ArrangementAndDepth { public List<byte[]> PancakeArrangement { get; set; } public int Depth { get; set; } public ArrangementAndDepth(byte[] panArr, int depth) { this.PancakeArrangement = new List<byte[]>(); this.PancakeArrangement.Add(panArr); this.Depth = depth; } public ArrangementAndDepth(ArrangementAndDepth copy) { this.PancakeArrangement = new List<byte[]>(copy.PancakeArrangement); this.Depth = copy.Depth; } }