RobinHankin / permutations

https://robinhankin.github.io/permutations/
5 stars 3 forks source link

pancake sorting problem #21

Open RobinHankin opened 4 years ago

RobinHankin commented 4 years ago

It might be interesting to include some examples of the pancake sorting problem:

https://en.wikipedia.org/wiki/Pancake_sorting

RobinHankin commented 4 years ago
> options("print_word_as_cycle" = F)
> o
    {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}
[1] 4   7   6   9   3   8   5   1   10  2   
> as.word(8:1) * o
    {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}
[1] .   5   8   3   9   .   .   4   10  2   
> 
RobinHankin commented 2 years ago

(writing December 2021) It took me some time to figure out what the significance of the edit 10 May 2020 was. Object o represents a stack of pancakes: 4 on top, then 7 then 6 then 9 etc. I get a spatula and flip the first 8 [which is why the factor is as.word(8:1)). Then the top pancake is number 1, then 5, then 8 etc.

RobinHankin commented 1 year ago

This is a nice example of active vs. passive notation. Here is nice little sequence of flips solving the PSP:

> (start <- as.word(c(1,2,3,6,4,5)))
    {1} {2} {3} {4} {5} {6}
[1] .   .   .   6   4   5  
> options(print_word_as_cycle=FALSE)
> (start <- as.word(c(1,2,3,6,4,5)))
    {1} {2} {3} {4} {5} {6}
[1] .   .   .   6   4   5  
> flip <- function(n){as.word(rev(seq_len(n)))}
> start
    {1} {2} {3} {4} {5} {6}
[1] .   .   .   6   4   5  
> flip(4)*start
    {1} {2} {3} {4} {5} {6}
[1] 6   3   2   1   4   5  
> flip(6)*flip(4)*start
    {1} {2} {3} {4} {5} {6}
[1] 5   4   1   2   3   .  
> flip(5)*flip(6)*flip(4)*start
    {1} {2} {3} {4} {5} {6}
[1] 3   .   1   .   .   .  
> flip(3)*flip(5)*flip(6)*flip(4)*start
    {1} {2} {3} {4} {5} {6}
[1] .   .   .   .   .   .  
>

So we solved it in four flips, viz [4,6,5,3] but this might not be optimal. See how successive flips are written in prefix notation, as per order_of_ops.Rmd.

RobinHankin commented 1 year ago

Pipes allow us to reverse the order of the flips in the idiom:

> f <- function(start,n){as.word(rev(seq_len(n)))*start}
> start  |> f(4) |> f(6) |> f(5) |> f(3)
    {1} {2} {3} {4} {5} {6}
[1] .   .   .   .   . 

Above, we may interpret "|>" as "and then...".