http://www.perlmonks.org?node_id=1007980


in reply to finding strings

I think this does the trick:
use Modern::Perl; my %uniq_substrings; my $strings = <DATA>; for ( 1 .. $strings ) { my $string = <DATA>; $uniq_substrings{$_}++ for substrings($string); } my $queries = <DATA>; for ( 1 .. $queries ) { my $query = <DATA>; say +( ( $query > scalar( keys %uniq_substrings ) ) ? 'INVALID' : ( sort keys %uniq_substrings )[ $query - 1 ] ); } sub substrings { my $string = shift; chomp($string); my @substrings; my $maxlength = length $string; for my $start ( 0 .. $maxlength ) { for my $length ( 1 .. $maxlength - $start ) { push @substrings, substr $string, $start, $length; } } return @substrings; } __DATA__ 2 aab aac 3 3 8 23
Output:
aab c INVALID
Update: my code fails on test no. 4 with a time-out error. I'll see if I can speed it up.

Update 2: When I exchange memory for speed (by using an array with the unique substrings, so I would not have to sort the keys again every time), test 4 passes, but now I get (predictably) an "out or memory" error on test 5 and beyond.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

My blog: Imperial Deltronics