Hi,
Could someone please help me with this? I have two arrays and I need to generate third array containing difference between the two. For example -
@Array1 = [1,5,15,20];
@Array2 = [15,1];
I would like to find difference between these two and generate third array that contains the difference. In this case it would look like -
Array3 - [5,20];
Could anyone please help how to do this in perl?
Thanks,
---------- Post updated at 05:33 PM ---------- Previous update was at 04:40 PM ----------
Nevermind. I found the solution. This is what I am doing now -
foreach $wrkelement \(@Array1, @Array2\) \{ $count\{$element\}\+\+ \}
foreach $element \(keys %count\) \{
push @\{ $count\{$element\} > 1 ? \\@Intersection : \\@Difference \}, $element;
\}
@Difference is the Array3 I was looking for - difference between values in two arrays
Though, if someone has any better way of doing then plz let me know. I would love to know!
Thanks,
$
$ perl -le '@x=(1,5,15,20); @y=(15,1); %y=map{$_=>1} @y;
> @diff=grep(!defined $y{$_}, @x);
> print foreach (@diff)'
5
20
$
tyler_durden
Azhrei
3
No loops are needed:
my @a1, @a2, %diff1, %diff2;
@a1 = (1, 5, 10, 15);
@a2 = (5, 15, 25);
@diff1{ @a1 } = @a1;
delete @diff1{ @a2 };
# %diff1 contains elements from '@a1' that are not in '@a2'
@diff2{ @a2 } = @a2;
delete @diff2{ @a1 };
# %diff2 contains elements from '@a2' that are not in '@a1'
@k = (keys %diff1, keys %diff2);
print "keys = @k\n";
In @k are the values that make up the difference.
A bit off-topic, but it may be interesting to know that Ruby has the most intuitive solution for this problem:
$
$ ruby -e 'a1 = [1,5,15,20]; a2 = [15,1]; puts a1 - a2'
5
20
$
$ ruby -e 'puts [1,5,15,20] - [15,1]'
5
20
$
tyler_durden
Azhrei
5
Hey, that is pretty cool. One more reason to put Ruby on my list of languages to play around with...
Its all there available, don't reinvent the wheel
Try this,
List::Compare - search.cpan.org
---------- Post updated at 09:40 AM ---------- Previous update was at 09:07 AM ----------
Is this working?
- Context used is wrong
- First loop should use $wrkelement and $element
Or, was that just a sample?