Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: Patience Sorting To Find Longest Increasing Subsequence

by demerphq (Chancellor)
on May 08, 2006 at 06:53 UTC ( #547967=note: print w/replies, xml ) Need Help??

in reply to Patience Sorting To Find Longest Increasing Subsequence

This is just a simple implementation of Patience Sorting, finding the LIS using backrefs, and doing the final merge phase to produce a sorted list. I didnt bother with anything special like binsearch or what not.

use strict; use warnings; use List::Util qw(shuffle); use Text::Wrap qw(wrap); sub patience { my ($deck)=@_; my @piles; CARD: foreach my $card (@$deck) { foreach my $pid ( 0..$#piles ) { if ( $card < $piles[$pid][-1][0] ) { push @{$piles[$pid]}, [ $card, $pid ? $piles[$pid-1][-1] : undef ]; next CARD; } } push @piles,[ [ $card, @piles ? $piles[-1][-1] : undef ] ]; } return \@piles } sub lis { my ($piles)= @_; my $iter= $piles->[-1][-1]; my @lis; while ($iter) { push @lis, $iter->[0]; $iter= $iter->[1]; } @lis=reverse @lis; return \@lis } sub inorder { my ($piles)= @_; my @inorder=(pop(@{$piles->[0]})->[0]); while (@$piles) { my $min=0; foreach my $pid (0..$#$piles) { if (@{$piles->[$pid]} && $piles->[$pid][-1][0] < $piles->[$min][-1][0] ){ $min=$pid; } } push @inorder,(pop(@{$piles->[$min]})->[0]); shift @$piles while @$piles && !@{$piles->[0]}; pop @$piles while @$piles && !@{$piles->[-1]}; } return \@inorder } sub print_ary { my ($head,$list)=@_; print wrap($head,"",join ", ",@$list),"\n---\n"; } my @deck= shuffle(1..52); my $piles=patience(\@deck); my $lis=lis($piles); my $inorder=inorder($piles); print_ary("DECK : ",\@deck); print_ary("LIS : ",$lis); print_ary("INORDER: ",$inorder);

Ive been trying to put together a vEB tree implementation to play with, but so far the documentation on it that I've found hasnt been as great as it looks at first glance. Notably ive been going a little barmy working out how you update the "max" property correctly when deleting the maximum element in a tree. Probably i just tried to work on it too long and if i rereview the documentation again it will clarify itself...


Replies are listed 'Best First'.
Re^2: Patience Sorting To Find Longest Increasing Subsequence
by Anonymous Monk on Oct 07, 2009 at 19:04 UTC
    cool thing to do is using if you have word cat means 3 alpha...2^m=2^3=8 so 000= 0 now sub sequences. 001=t 010=a 011=at 100=c 101=at 110=ca 111=cat

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://547967]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2017-07-23 17:12 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (347 votes). Check out past polls.