in reply to Re^2: Searching parallel arrays.
in thread Searching parallel arrays.
#!/usr/bin/perl use strict; use warnings; my @aoa = ([100, 204, 312], [102, 313, 409], [205, 206, 315], [207, 21 +0, 314]); my $next = gen_find_contiguous(4, \@aoa); while (my @seq = $next->()) { print "Val: $_->[0]\tArr: $_->[1]\tPos: $_->[2]\n" for @seq; print "\n"; } sub gen_find_contiguous { my ($min, $list) = @_; my @pos = (0) x @$list; return sub { my $found; my @cont; while (! $found) { # Find smallest value keeping track of array and index in +that array my ($arr, $val, $idx); for (grep defined($pos[$_]), 0 .. $#pos) { if (! defined $arr || $list->[$_][$pos[$_]] < $val) { ($arr, $val, $idx) = ($_, $list->[$_][$pos[$_]], $ +pos[$_]); } } # Check to see if we are at the end of all arrays if (! defined $arr) { return @cont >= $min ? @cont : (); } # Add value to cont if empty if (! @cont) { push @cont, [$val, $arr, $idx]; } else { # Add value to cont if it 1 away from prev value if ($val - $cont[-1][0] == 1) { push @cont, [$val, $arr, $idx]; } else { # If @cont >= $min, set found flag if (@cont >= $min) { $found = 1; } # Else start over else { @cont = [$val, $arr, $idx]; } } } # Increment index of array we fetched value from if ! $fou +nd if (! $found) { $pos[$arr] = $idx == $#{$list->[$arr]} ? undef : $idx + 1; } } return @cont; }; }
I didn't use List::Util's reduce() because apparently it can handle multiple return values. The docs (Returns the result of the last call to BLOCK.) should probably be clarified on this point
Cheers - L~R
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Searching parallel arrays.
by BrowserUk (Patriarch) on Dec 09, 2006 at 02:12 UTC | |
by Limbic~Region (Chancellor) on Dec 09, 2006 at 02:42 UTC |