in reply to match diagonal text
I chose to generalize rather than optimize, and I think it lead to an improved solution.
Note that by reversing the lines, we can reuse the left-to-right algorithm to get the right-to-left diagonals. By also reversing the returned list, the line numbers are also made correct.
I first coded this to look for a complete diagonal of all 1 or 2, until I read the "~ 500x50" comment.
Output:#!perl use strict; use warnings; while (<DATA>) { chomp; my @lines = map { [ split '' ] } split ' '; my @diags_LR = extract_diagonals( @lines); my @diags_RL = reverse extract_diagonals(reverse @lines); #print "@diags_LR\n@diags_RL\n"; my @nums = map { $_ + 1 } grep { wanted($diags_LR[$_]) or wanted($diags_RL[$_]) } 0 .. $#diags_LR; print "Diags found in lines: @nums\n data:$_\n" if @nums; } sub wanted { my ($diag) = @_; # return $diag =~ m{ \A ([12]) \1+ \z }msx; # All 1's or all 2's return $diag =~ m{ 1111 | 2222 }msx; # Four 1's or 2's anywhere } sub extract_diagonals { my @lines = @_; my $row_count = scalar @lines; my $column_count = scalar @{$lines[0]}; die unless $column_count > 1 and $row_count > 1; my $diag_length = ($row_count < $column_count) ? $row_count : $column_count; my @diagonals; for my $c ( 0 .. ($column_count - $diag_length) ) { for my $r ( 0 .. ($row_count - $diag_length) ) { my @diag_chars = map { $lines[$r+$_][$c+$_] } 0 .. ($diag_length-1); push @diagonals, join( '', @diag_chars ); } } return @diagonals; } __DATA__ ABCDEFGH IJKLMNOP QRSTUVWX ABCDEF GHIJKL MNOPQR STUVWX ABC DEF GHI JKL MNO PQR STU VWX ABCD EFGH IJKL MNOP QRST UVWX ABCDE FGHIJ KLMNO PQRST UVWXY 220021 000200 020222 020222 100000 010000 001000 000100 102000 010200 001020 000102 102000 010200 001020 000201
Diags found in lines: 1 data:100000 010000 001000 000100 Diags found in lines: 1 3 data:102000 010200 001020 000102
|
|---|