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

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
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.


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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1007980]
[shmem]: I don't know geany, and don't know whether it has support for ctags.
[Lady_Aleena]: ctags?
[shmem]: ctags is a program which (recursively) extracts the symbols from source and stores them in a one-file database. This allows you to query the locations where these symbols (e.g. a subroutine name) are used anywhere in the source code tree...
[shmem]: ...from inside the editor.
[shmem]: apt-get install exuberant-ctags
[Lady_Aleena]: I think I heard vim has a big learning curve.
[shmem]: then in the root of your source tree run: ctags -R
[shmem]: you get a file named tags where all symbols and the places where they are used are listed

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (9)
As of 2017-04-27 12:09 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (505 votes). Check out past polls.