How to resolve the algorithm Pancake numbers step by step in the D programming language
How to resolve the algorithm Pancake numbers step by step in the D programming language
Table of Contents
Problem Statement
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Pancake numbers step by step in the D programming language
Source code in the d programming language
import std.stdio;
import std.algorithm;
import std.random;
import std.range;
int pancake(int n) {
int gap = 2, sum = 2, adj = -1;
while (sum < n) {
adj++;
gap = 2 * gap - 1;
sum += gap;
}
return n + adj;
}
Range pancakeSort(Range)(Range r) {
foreach_reverse (immutable i; 2 .. r.length + 1) {
immutable maxIndex = i - r[0 .. i].minPos!q{a > b}.length;
if (maxIndex + 1 != i) {
if (maxIndex != 0) {
r[0 .. maxIndex + 1].reverse();
}
r[0 .. i].reverse();
}
}
return r;
}
void main() {
writeln("\nThe maximum number of flips to sort a given number of elements is:\n");
foreach (i; 1..11)
{
auto data = iota(1, i+1).array;
if (i != 1) {
// Protection against the edge case data.lenght == 1 not handled by randomShuffle
// where also data is invariant with regard to pancakeSort
do
data.randomShuffle;
while (data.isSorted);
}
auto sortedData = data.dup;
sortedData.pancakeSort;
writefln("pancake(%2d) = %2d e.g %s -> %s", i, pancake(i), data, sortedData);
}
}
You may also check:How to resolve the algorithm User input/Graphical step by step in the REXX programming language
You may also check:How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Oforth programming language
You may also check:How to resolve the algorithm Jacobi symbol step by step in the XPL0 programming language
You may also check:How to resolve the algorithm User input/Text step by step in the NetRexx programming language
You may also check:How to resolve the algorithm Simple windowed application step by step in the Groovy programming language