Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Patience Sorting To Find Longest Increasing Subsequence

by demerphq (Chancellor)
on May 08, 2006 at 06:53 UTC ( [id://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...

---
$world=~s/war/peace/g

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 binary..search.. 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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://547967]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-04-20 06:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found