in reply to Re: True Brute Force Longest Common Sub Sequence
in thread True Brute Force Longest Common Sub Sequence
If you just want to use brute force then using a hash is really cheating as it is already the begining of optimisation. We need nasty embedded loops to go O(2^n*2^m). I think something like this represents to worst way to do it, first generating all possible subsequences and then testing every case. This does however seem to be the point.
use strict; sub subseqs { my $str = $_[0]; my @seqs = (''); for my $char (split //, $str) { for my $i ( 0..@seqs-1 ) { push @seqs, $seqs[$i].$char; } } return @seqs; } my $s1 = 'abcdefgh'; my $s2 = 'abecdgh'; my $best_len = 0; my $longest; for my $seq1 (subseqs($s1)) { for my $seq2 (subseqs($s2)) { next unless $seq1 eq $seq2; if (length($seq1) > $best_len) { $longest = $seq1; $best_len = length($seq1); } } } print $longest;
Note that there is an edge case when 2 or more common subsequences share the same length only the first will be found.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: True Brute Force Longest Common Sub Sequence
by ikegami (Patriarch) on Nov 25, 2007 at 18:14 UTC | |
by tachyon-II (Chaplain) on Nov 26, 2007 at 00:31 UTC | |
by ikegami (Patriarch) on Nov 26, 2007 at 06:35 UTC | |
by tachyon-II (Chaplain) on Nov 28, 2007 at 00:06 UTC | |
by ikegami (Patriarch) on Nov 28, 2007 at 01:13 UTC | |
|
Re^3: True Brute Force Longest Common Sub Sequence
by ikegami (Patriarch) on Nov 28, 2007 at 01:56 UTC |