public
Last active

  • Download Gist
wordsearch-degolfed.pl
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
$\="\n"; # "print for ..." at the end puts stuff on new lines :)
$/=""; # paragraph mode.
@word = split//,pop; # Get the search word off of the commandline
($board=<>) =~ tr/ //d;
$width = 1 + index($board, "\n"); # How wide is the board? Find the first newline.
for (1,2) {
# Find the word forwards, southwest, south, and southeast.
for my $stride (0, $width - 2 .. $width) {
$pattern = join "."x $stride, @word;
# If it's in the board, record the start and end match positions.
push @matches, [ $-[0], $+[0] - 1] while $board =~ /$pattern/sg;
}
# Reverse the word, so that on the next iter we find the word backwards,
# northeast, north, and northwest.
@word = reverse @word;
# And reverse the starts and ends. The forward matches will be reversed
# twice (and come out forwards); the backward ones will only be reversed
# once.
@matches = map [ reverse @$_ ], @matches;
}
 
sub pos_to_row_col {
my $pos = shift;
return sprintf "row %d, column %d",
(1 + $pos / $width),
(1 + $pos % $width);
}
 
for my $match (@matches) {
print pos_to_row_col( $match->[0] ) . " --> "
. pos_to_row_col( $match->[1] );
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.