i am trying to compare values of range from @arr3 with values of range from @arr4 but i am not getting the desired output. please suggest me the modifications in the following c
Note that your for
loops like this
for (my $i = $from1; $i = $to1; $i++) { ... }
are incorrect, because the second clause $i = $to1
should be a test to determine whether the loop should continue, whereas you are assigning the value of $to1
to $i
so the loop will never end if $to1
is true. I imagine your tests have failed to complete?
I also think you are misunderstanding the way the range operator ..
works. An expression like 2..5
returns a list consisting of all the values from 2 up to 5, and is identical to (2, 3, 4, 5)
.
So your array initialisation
my @arr3 = (1..5, 5..10, 10..15)
is the same as
my @arr3 = (
1, 2, 3, 4, 5,
5, 6, 7, 8, 9, 10,
10, 11, 12, 13, 14, 15
)
and so there is no need to use split
on the array values as they have already been expanded for you, and the reason the values 5 and 10 are appearing twice in your output is because they also exist twice in the input.
If you want to find all unique values that are in both arrays, and you can rely on the values in @arr4
being unique (i.e. there is no overlap like there is in @arr3
) then you can write something like the code below. But if both arrays could have overlaps then you have to explicitly remove duplicates, and a solution using a hash which does this has already been posted.
This solution uses a label V4
so that the next
can go to the next iteration of the outer loop. Without it the rest of @arr3
would be scanned for matches even after one had been found.
use strict;
use warnings;
my @arr3 = (1..5, 5..10, 10..15);
my @arr4 = (3..7, 9..12, 14..17);
V4:
for my $v4 (@arr4) {
for my $v3 (@arr3) {
if ($v3 == $v4) {
print "$v3\n";
next V4;
}
}
}
output
3
4
5
6
7
9
10
11
12
14
15