in reply to searching for strings

Definitely one of those things that appears on the surface to be trivial, but turns out to be much harder:

Here's one way

#! perl -slw use strict; use Data::Dump qw[ pp ]; my %hash; while( <DATA> ) { chomp; my( $pre, $temp ) = m[(^.+?)(\d+|\D)$]; $temp = $pre . ++$temp; if( exists $hash{ $_ } ) { push @{ $hash{ $_ } }, $_; } elsif( exists $hash{ $temp } ) { push @{ $hash { $temp } }, $_; } else { $hash{ $temp } = [ $_ ]; $hash{ $_ } = [ $_ ]; } } print join ';', @{ $_ } for grep{ @{ $_ } == 2 } values %hash; __DATA__ AAA30 BBC5 SHT12H DAL33B BBC49 AAA31 DAL33A BBC6 SHT12G BBC50

Output:

C:\test>junk DAL33B;DAL33A AAA30;AAA31 BBC49;BBC50 BBC5;BBC6 SHT12H;SHT12G

If you need the doubled-up output, just print them twice with the elements reversed.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^2: searching for strings
by Limbic~Region (Chancellor) on Aug 06, 2007 at 12:48 UTC
    BrowserUk,
    I was trying to think of more edge cases and I think I have found a few steph_bow needs to weigh in on.

    For instance, what if a string is ABC0? Should ABC1 and ABC-1 be checked?

    Also, what if the string is XYZ? Should XYY and XYAA be checked?

    Is the alphabet circular - IOW, should AAA look at AAZ and AAB?

    Cheers - L~R

    Corrected XYZ -> XYAA rather than XYZA
      I have found a few steph_bow needs to weigh in on.

      Agreed. That said, the test set provided is amazingly complete given how concise it is.

      There is nothing accidental about either the choice of sample, or its ordering. A lot of thought went into its provision.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
        A lot of thought went into its provision.

        Why do I think "homework!" all of a sudden? :-)

        --shmem

        _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                      /\_¯/(q    /
        ----------------------------  \__(m.====·.(_("always off the crowd"))."·
        ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}