Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: finding strings

by CountZero (Bishop)
on Dec 09, 2012 at 14:06 UTC ( #1007980=note: print w/ replies, xml ) Need Help??


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


Comment on Re: finding strings
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (11)
As of 2014-12-27 21:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls