Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: match diagonal text

by Util (Priest)
on Sep 22, 2011 at 15:14 UTC ( #927393=note: print w/ replies, xml ) Need Help??


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.

#!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
Output:
Diags found in lines: 1 data:100000 010000 001000 000100 Diags found in lines: 1 3 data:102000 010200 001020 000102


Comment on Re: match diagonal text
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://927393]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2014-07-11 09:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (223 votes), past polls