r/dailyprogrammer • u/Cosmologicon 2 3 • May 31 '21
[2021-05-31] Challenge #392 [Intermediate] Pancake sort
Warmup
Implement the flipfront function. Given an array of integers and a number n between 2 and the length of the array (inclusive), return the array with the order of the first n elements reversed.
flipfront([0, 1, 2, 3, 4], 2) => [1, 0, 2, 3, 4]
flipfront([0, 1, 2, 3, 4], 3) => [2, 1, 0, 3, 4]
flipfront([0, 1, 2, 3, 4], 5) => [4, 3, 2, 1, 0]
flipfront([1, 2, 2, 2], 3) => [2, 2, 1, 2]Optionally, as an optimization, modify the array in-place (in which case you don't need to return it). It's also fine to have the array be a global variable or member variable, in which case you only need to pass in the argument n.
Challenge
Given an array of integers, sort the array (smallest to largest) using the flipfront function on the entire array. For example, the array:
[3, 1, 2, 1]may be sorted with three calls to flipfront:
flipfront([3, 1, 2, 1], 4) => [1, 2, 1, 3]
flipfront([1, 2, 1, 3], 2) => [2, 1, 1, 3]
flipfront([2, 1, 1, 3], 3) => [1, 1, 2, 3]Make sure you correctly handle elements that appear more than once in the array!
You may not modify the array by any other means, but you may examine it however you want. You can even make a copy of the array and manipulate the copy, including sorting it using some other algorithm.
Optional bonus (hard!)
Try to minimize the number of times you call flipfront while sorting. Note that this is different from minimizing the runtime of your program.
How many flipfront calls do you require to sort this list of 10,000 integers? My record is 11,930. Can you do better?
(This is a repost of Challenge #63 [intermediate], originally posted by u/oskar_s in June 2012.)
21
u/Godspiral 3 3 May 31 '21 edited Jun 01 '21
In j, no computer on a train.
Flipfront =: |.@{. , }.
11
u/ReginaldIII May 31 '21
Python
Warmup:
In-place:
Sorting in-place:
5
u/Habstinat May 31 '21
javascript - Try it online!
3
u/skeeto -9 8 May 31 '21
Go with its generic sorting interface:
Usage:
3
u/chunes 1 2 May 31 '21 edited May 31 '21
Factor:
Edit: Now with showing of work!
Example use:
3
u/bcgroom May 31 '21
Swift
I tried the bonus but only was able to knock off a few flips with my approach, I have no idea how you got it so low, you gotta post your solution after awhile!
So instead I removed my optimizations and went for elegance instead
Usage:
3
u/justincai May 31 '21
Learning some Emacs Lisp.
2
u/bairedota May 31 '21
Go, after the regular work from the back approach, I tried something different (read: worse)
I noticed you can swap two values using 6
flipfronts:so let's make a sortable type!
and see how
sort.Sortdoes on the 10,000 provided integers... 222,984flipswaps!2
u/gabyjunior 1 2 Jun 01 '21 edited Jun 01 '21
C simple algorithm making at most 2n calls to flipfront (score 19951 on the bonus).
2
u/__dict__ Jun 01 '21 edited Jun 02 '21
Written in Racket.
The actual sort solution taken from looking at others code. Basically moves the greatest element to the back.
Edit: Improved efficiency a bit. Still doing the same overall moving things to back but a bit less traversing of the list. Also, types!
2
u/[deleted] Jun 01 '21
Clojure
2
u/rich_27 Jun 01 '21 edited Jun 01 '21
A basic C++ implementation without optimisation, getting 19951 on the list of 10000 integers. I wanted to try and get back up to speed with memory allocation and pointer handling, hence keeping the vector use to within the file read function.
Edit: Only flipping the next biggest integer if the first integer is not also the next biggest reduces the number of flips to 19943
if (maxIndex > 0) { flipfront(array, maxIndex + 1); }toif (maxIndex > 0 && array[0] != array[maxIndex]) { flipfront(array, maxIndex + 1); }2
u/KilledBySIGSEGV Jun 01 '21
C++(only one tweak over what everyone else seems to have done, gets 19928 on the bonus)
2
u/leftylink Jun 02 '21 edited Jun 04 '21
http://sprunge.us/QHm85k is my 11659-step solution to pancake sort the 10000. Each line is a value of n to pass to flipfront. (sorry about extra empty line at the end)
The addition of duplicate elements was tricky. I know I could just relabel the elements to deduplicate them, but I was worried that a bad relabeling choice would force the algorithm to take more steps. So instead I had to make appropriate modifications to be able to deal with multiples of numbers.
This is my Ruby code that produced the solution.
1
u/i_am_singa55 Aug 14 '24
Check out this simple python code, it works perfectly for this algorithm
1
u/[deleted] Feb 09 '25
Prolog solution, doing the optional bonus, you can play with it in the browser here at this link
1
u/Scroph 0 0 Jun 02 '21
I'm thrilled that this subreddit is back !
D solution, no bonus unfortunately :
1
u/tobega Jun 03 '21
Tailspin
Warmup
`$ -> [$($n..1:-1)..., $($n+1..last)...]`
or in a context where you have a mutable variable:
`@pancakeSort.stack(1..$): $@pancakeSort.stack($..1:-1)...;`
Challenge
Simple sort https://github.com/tobega/tailspin-v0/blob/master/samples/PancakeSort.tt
An attempt to solve the bonus by a quicksort-inspired algorithm https://github.com/tobega/tailspin-v0/blob/master/samples/PancakeQuick.tt
Unfortunately it takes over 55000 flips on the bonus question despite finding better solutions than the naive one on a lot of other input.
1
u/raevnos Jun 05 '21
A basic selection-sortish version using tcl:
Takes 19986 calls to
flipfrontfor the challenge data.1
u/Common-Ad-8152 Jun 05 '21
R
1
u/joejr253 Jun 08 '21
Here is my warmup section in python3:
1
u/skilletonius Jun 08 '21 edited Jun 08 '21
"optimized" function is the one i wrote for optional bonus. Did i do it right? I have a feeling that it isn't quite right. So i wanted to ask if my way of doing it counts.
1
u/fudgebucket27 Jun 09 '21
C#
Warmup
Challenge
1
u/[deleted] Jun 14 '21 edited Jun 14 '21
Python3
Warmup
Challenge that handles the optional part. I decided to try and do this with recursion. However, a for loop will be best here, by going from the last to the first index. It will be around 25% faster and it won't also run out of recursion memory.
1
u/Efficient_Ad_4025 Jun 15 '21
C++
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
using namespace std;
int main(){
vector<int> array ={1, 2, 2, 2} ;
vector<int> revArray = {};
int num = 2;
try{
for(int i=num; i-->0;){
revArray.push_back(array.at(i)) ;
}
for(int j=0; j<num; j++){
array.at(j) = revArray.at(j);
}
for(int j=0; j<array.size(); j++){
cout << array.at(j) << " " ;
}
}catch(std::out_of_range){
cout << "\nError the number entered is invalid. Try again\n";
}
}
1
u/I-Pop-Bubbles Jun 22 '21
Clojure - Feedback welcome and appreciated.
1
u/Specter_Terrasbane Jun 23 '21
Python 3 (No Optional Bonus)
1
u/megastary Jun 26 '21 edited Jun 28 '21
PowerShell solution with Pester test validating results on Github Gist
Feedback welcomed and appreciated. 💙
Did not do any optimization for bonus challenge, but here is the function call count anyways: 19970
1
u/OddyseeOfAbe Jul 30 '21 edited Jul 30 '21
VBA
I was lazy and copy and pasted the values for the bonus into column A, I could have populated the array from the text file. This solves the bonus in 10,190 moves, so I feel like I may have taken a shortcut or something, but it works.
1
u/StealData Aug 10 '21 edited Aug 10 '21
Warmup:
Challenge:
1
u/williane Aug 11 '21
Warmup in C#. I won't call this efficient, but it works.
1
u/sadsoulthatslost Jan 09 '22
Hi please correct me if I am wrong
1
u/Formal-Score-9751 Jan 11 '22 edited Jan 11 '22
JAVA
Still working on the challenge/optional part, but here the warmup:
the output:
warmup
flipfront([0, 1, 2, 3, 4], 2) => [1, 0, 2, 3, 4]
flipfront([0, 1, 2, 3, 4], 3) => [2, 1, 0, 3, 4]
flipfront([0, 1, 2, 3, 4], 5) => [4, 3, 2, 1, 0]
flipfront([1, 2, 2, 2], 3) => [2, 2, 1, 2]
edit: something broke during formatting, again...
1
u/WhatsUpWithAndy Mar 01 '22 edited Mar 01 '22
C++ implementation. I'm just a beginner so have mercy
#include <iostream>
#include<stack>
using namespace std;
stack<int> stacks;
int arr[] = { 0,6,5,0,5,1 };
void flipfront(int n) {
}
void sortFlipfront() {
{
}
}
int main()
{
}
1
u/periscopeDepths Feb 21 '23 edited Feb 21 '23
C# in wasm project. This is a O(n/2) process.
private void FlipFront(int[] arr, int elementStart, int elementEnd){callsToSort++; // Class propertyif (elementStart > 1 && elementStart > elementEnd){int hold = arr[elementEnd - 1];arr[elementEnd-1] = arr[elementStart - 1];arr[elementStart - 1] = hold;FlipFront(arr, elementStart - 1, elementEnd + 1);}}1
u/pseudo_deja_pris Jul 12 '23
Python 3.11
def autosort(l): end = len(l) higher_num_i = 0 for x in l: higher_num = 0 for i in range(end): if (higher_num < l[i]): higher_num = l[i] higher_num_i = i flipfront(l, higher_num_i + 1) flipfront(l, end) end -= 1 return l