VincentK has asked for the wisdom of the Perl Monks concerning the following question:
Good day.
I am working on a problem that is just an intellectual challenge. I am not asking for help on solving the actual problem, rather just help on optimizing a loop. As it stands, running the script over the input takes a few hours to complete.
After the initial loading the array @input_connections, will contain pairs of numbers where each element is in a format like '7-12' (starting connection-ending connection). The code snippet below reads through each of these pairs and culls out the ones that are already implied by the other pairs
Whereas if the pair '7-12' was stored and the next pair is '7-10', '7-10' would be rejected because '7-10' falls within the range of '7-12'.
The array @used_connections stores numbers that have been used in each pair. The array @output_connections stores the connections that are to be output from the processing.
Ideally, I'd love to have the connections stored in a hash and be able to check for used numbers with something like ' if exists $hash{key1...keyN} ' thereby removing a loop for checking. I am seeking wisdom to see if there is ( and I am sure there is ) a more efficient way to go about this part.
Any suggestions will be most appreciated. Thanks!
I apologize if this does not make sense.
Code snippet
############################################################### my $pair_no = 1; foreach my $conn (@input_connections) { print "\rON pair $pair_no"; my @curr_conn = split(/\-/,$conn); ## check if current connection exists my $exists = 1; my $start = $curr_conn[0]; my $end = $curr_conn[1]; ## first number in pair is larger than second, reverse them if ($curr_conn[0] > $curr_conn[1]) { $start = $curr_conn[1]; $end = $curr_conn[0]; } ## ** Ideally I want to do away with this loop ** ## for ($start..$end) { if ( not defined $used_connections[$_] ) { $exists = 0; last; } } if ($exists == 0) { for ($start..$end) { $used_connections[$_] = 1; # I tried something like @used_connections[$start..$end] = + 1 , but # it did not seem to work the same as what is in place now +. } push @output_connections , $conn; } $pair_no++; } ###############################################################
|
|---|