On 2011-05-27 10:18, eventual wrote:

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.

a. Do once what you can do only once. There are at least 2 points where you didn't: 1. prepare @datas before looping; 2. don't compare the same stuff more than once.

b. Assemble a result, and report at the end. Don't use any 'shared resources' like incrementing global counters while going along.


#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @data = <DATA>;
$_ = { map { $_ => 1 } split } for @data;
$ARGV[0] and print Dumper( \@data );

my @result;

for my $i ( 0 .. $#data - 1 ) {
    my @k = keys %{ $data[ $i ] };
    for my $j ( $i + 1 .. $#data ) {
        my $n = 0;
        exists $data[ $j ]{ $_ } and ++$n for @k;
        $n >= 5 and push @result, [ $i, $j ];
    }
}

print Dumper( \@result );

__DATA__
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


--
Ruud

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