Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
A few weeks ago, TedPride posted an interesting puzzle. kvale provided a hint by linking to Patience Sorting that no one apparently used. bart mentioned yesterday he would like to see an implementation of both the sorting algorithm as well as the way to divine the longest increasing subsequence from the result.

Patience Sorting

Each new card is placed on the left most pile where the top card in that pile is greater than the new card. If no pile meets this criteria, the new card is placed in a new pile to the right of the existing piles. When all cards are exhausted, the number of piles defines the length of the longest increasing subsequence. It is that simple. You only need to add 1 more thing to retrieve the sequence from the piles. <update> As bart points out below, this may be all that is required to find the longest increasing subsequence but the sort still isn't finished. I have added a merge sort to his reply to demonstrate how that is possible.</update>

Longest Increasing Subsequence

After each card is placed, a note is taken of the top card in the previous pile. If it is the left most pile no note is needed. When all the cards are exhausted, starting in the right most pile we can work backwards finding the cards that make up the longest increasing subsequence. The reverse of this is the sequence is what is desired.

The following is a straight forward implementation. I took advantage of the fact that you know the length of the sequence before actually finding it to alleviate the need for reverse as I fill the array.

#!/usr/bin/perl use strict; use warnings; use List::Util 'shuffle'; use constant VAL => 0; use constant PREV => 1; my @list = shuffle(1..20); print "@list\n"; print join " ", Long_Inc_Sub(@list); sub Long_Inc_Sub { my @list = @_; my (@pile, @seq); NUM: for my $num (@list) { for (0 .. $#pile) { if ($num < $pile[$_][-1][VAL]) { my $prev = $_ ? $#{$pile[$_ - 1]} : undef; push @{$pile[$_]}, [$num, $prev]; next NUM; } } my $prev = @pile ? $#{$pile[-1]} : undef; push @pile, [[$num, $prev]]; } my ($prev, $len) = ($#{$pile[-1]}, scalar @pile); while ($len--) { $seq[$len] = $pile[$len][$prev][VAL]; $prev = $pile[$len][$prev][PREV]; } return @seq; }

Things To Consider

Do the algorithms still work if the original list sorted in ascending order is non-continguous (! 1..N)? Do the algorithms still work if the original list contains duplicates? Are there ways to maintain the same speed and decrease the memory consumption? Would there be a benefit in replacing the linear card placement search with a binary one or would the overhead outweigh the benefit. If the answer is "it depends", is there a way to know ahead of time to dispatch the appropriate method?

These and other interesting things to ponder are all left as an exercise for the reader.

Cheers - L~R

In reply to Patience Sorting To Find Longest Increasing Subsequence by Limbic~Region

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others romping around the Monastery: (10)
    As of 2018-06-18 18:35 GMT
    Find Nodes?
      Voting Booth?
      Should cpanminus be part of the standard Perl release?

      Results (110 votes). Check out past polls.