From: Stefan Reiter Date: Wed, 17 Jul 2019 13:03:44 +0000 (+0200) Subject: Add array_intersect and array_unique functions X-Git-Url: https://git.proxmox.com/?p=pve-common.git;a=commitdiff_plain;h=a59544e779ff4de859973d6a32f1c9521ef6bb69;ds=sidebyside Add array_intersect and array_unique functions Signed-off-by: Stefan Reiter --- diff --git a/src/PVE/Tools.pm b/src/PVE/Tools.pm index 4dd073f..c31ebeb 100644 --- a/src/PVE/Tools.pm +++ b/src/PVE/Tools.pm @@ -1649,4 +1649,33 @@ sub dev_t_minor($) { return (($dev_t >> 12) & 0xfff00) | ($dev_t & 0xff); } +# Given an array of array refs [ \[a b c], \[a b b], \[e b a] ] +# Returns the intersection of elements as a single array [a b] +sub array_intersect { + my ($arrays) = @_; + + return [] if @$arrays == 0; + return $arrays->[0] if @$arrays == 1; + + my $return_arr; + @$return_arr = array_unique(@{$arrays->[0]}); + for my $i (1 .. $#$arrays) { + my %count = (); + foreach my $element (@$return_arr, array_unique(@{$arrays->[$i]})) { + $count{$element}++; + } + $return_arr = []; + foreach my $element (keys %count) { + push @$return_arr, $element if $count{$element} > 1; + } + } + + return $return_arr; +} + +sub array_unique { + my %seen = (); + return grep { ! $seen{ $_ }++ } @_; +} + 1;