eventual wrote:
Hi,

Hello,

I have an array , @datas, and each element within @datas is a string
that's made up of 6 digits with spaces in between like this “1 2 3 4 5
6”, so the array look like this
@datas = ('1 2 3 4 5 6', '1 2 9 10 11 12', '1 2 3 4 5 8', '1 2 3 4 5
9' , '6 7 8 9 10 11');
Now I wish to compare each element of @datas with the rest of the
elements in @datas in such a way that if 5 of the digits match, to
take note of the matching indices,  and so the script I wrote is
appended below.
However, the script below takes a long time to run if the datas at
@datas are huge( eg 30,000 elements). I then wonder is there a way to
rewrite the script so that the script can run faster.
Thanks

###### script below #######################

#!/usr/bin/perl
use strict;

my @matched_location = ();
my @datas = ('1 2 3 4 5 6', '1 2 9 10 11 12', '1 2 3 4 5 8', '1 2 3 4 5 9' , '6 
7 8 9 10 11');

my $iteration_counter = -1;
foreach (@datas){
    $iteration_counter++;
    my $reference = $_;

    my $second_iteration_counter = -1;
    my $string = '';
    foreach (@datas){
       $second_iteration_counter++;
       my @individual_digits = split / /,$_;

       my $ctr = 0;
       foreach(@individual_digits){
           if($reference =~/^$_ | $_ | $_$/){
               $ctr++;
           }
       }
       if ($ctr>= 5){
           $string = $string . "$second_iteration_counter ";
       }
    }
    $matched_location[$iteration_counter] = $string;
}

my $ctr = -1;
foreach(@matched_location){
     $ctr++;
     print "Index $ctr of \@matched_location = $_\n";
}


Your program can be reduced to:

my @matched_location;
my @datas = ( '1 2 3 4 5 6', '1 2 9 10 11 12', '1 2 3 4 5 8', '1 2 3 4 5 9', '6 7 8 9 10 11' );


for my $i ( 0 .. $#datas ) {
    for my $j ( 0 .. $#datas ) {
$matched_location[ $i ] .= "$j " if 5 <= grep $datas[ $i ] =~ /(?:^|(?<= ))$_(?= |$)/, split ' ', $datas[ $j ]
        }
    }

print map "Index $_ of \@matched_location = $matched_location[$_]\n", 0 .. $#matched_location;

You should benchmark it to see if it is any faster than your original code.



John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction.                   -- Albert Einstein

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to