I have a list of numbers L. There is another list of numbers M. I need to return a list L' of numbers found in both L and M.
Edit: Mathematically, I am looking for Multiset intersection.
Example:
L = 3,
1
, 4,1
, 5,9
,2
, 6
M =9
, 7,1
,2
,1
, 1
L' = 9, 1, 2, 1
I wrote the following code for that:
my @some-numbers = 3, 1, 4, 1, 5, 9, 2, 6;
my @to-match = 9, 7, 1, 2, 1, 1;
my @matched;
my %histogram;
for @some-numbers -> $n { %histogram{$n}++ };
for @to-match -> $n {
next if not defined %histogram{$n};
if %histogram{$n} > 0 {
push @matched, $n;
%histogram{$n}--;
}
};
say @matched;
While it achieves the purpose, I was wondering whether there was an idiomatic Perl6 way of doing this?
Some background: I have been trying to learn Perl6 and Python together, and solve the same puzzles in both the languages. Python offered a particularly pleasing solution for the above problem. To my beginner eyes at least :)