#!/usr/bin/perl use strict; use warnings; my @aoa = ([100, 204, 312], [102, 313, 409], [205, 206, 315], [207, 210, 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 ! $found if (! $found) { $pos[$arr] = $idx == $#{$list->[$arr]} ? undef : $idx + 1; } } return @cont; }; }