in reply to Longest Increasing Subset

TIMTOWTDI

use Algorithm::Combinatorics qw/combinations/; use strict; use warnings; use constant DEBUG => 0; use constant ALL => 1; local $\ = "\n"; # UPDATE#1 = I was using perl -l to run; if you don't +, you'll want this... my @array = qw(2 6 5 7 4 3 9); my $Fcount = @array; my @answer = (); while( $Fcount ) { my $iter = combinations( \@array, $Fcount ); while( my $p = $iter->next() ) { my $monotonic = 1; my @a = @$p; foreach my $i ( 0.. $#a-1 ) { my $j = $i + 1; $monotonic &&= $a[$j] > $a[$i]; last unless $monotonic; } push @answer, [@a] if $monotonic; $monotonic ||= 0; # not necessary, except it cleans up my debu +g print print "$Fcount: (@a): $monotonic || (@answer)" if DEBUG; last if $monotonic && !ALL; # this could also be 'last if @ans +wer && !ALL;' } --$Fcount; last if @answer && !ALL; } foreach my $p (@answer) { local $, = "\t"; local $" = ","; print scalar(@$p), "(@$p)"; } __END__ 4 (2,6,7,9) 4 (2,5,7,9) 3 (2,6,7) 3 (2,6,9) 3 (2,5,7) 3 (2,5,9) 3 (2,7,9) 3 (2,4,9) 3 (2,3,9) 3 (6,7,9) 3 (5,7,9) 2 (2,6) 2 (2,5) 2 (2,7) 2 (2,4) 2 (2,3) 2 (2,9) 2 (6,7) 2 (6,9) 2 (5,7) 2 (5,9) 2 (7,9) 2 (4,9) 2 (3,9) 1 (2) 1 (6) 1 (5) 1 (7) 1 (4) 1 (3) 1 (9)

change to ALL => 0 to get just the first combination that's increasing.

update: added $\ = "\n";

update 2 (2016-Oct-24): please don't use this code in production; it is highly inefficient. see Re^7: Longest Increasing Subset