Pancake numbers

From Rosetta Code
Revision as of 15:08, 28 October 2020 by Nigel Galloway (talk | contribs) (Realize in F#)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Pancake numbers is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

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 rumination. 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.

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).

F#

<lang fsharp> // Pancake numbers. Nigel Galloway: Octber 28th., 2020 let pKake z=let n=[for n in 1..z-1->Array.ofList([n.. -1..0]@[n+1..z-1])]

           let e=let rec fG n g=match g with 0->n |_->fG (n*g) (g-1) in fG 1 z
           let rec fN i g l=match (Set.count g)-e with 0->i
                                                      |_->let l=l|>List.collect(fun g->[for n in n->List.permute(fun g->n.[g]) g])|>Set.ofList
                                                          fN (i+1) (Set.union g l) (Set.difference l g|>Set.toList)
           fN 0 (set1..z) 1..z

[1..9]|>List.iter(fun n->printf "%d->%d " n (pKake n)); printfn "" </lang>

Output:
1->0 2->1 3->3 4->4 5->5 6->7 7->8 8->9 9->10