Skip to content

Instantly share code, notes, and snippets.

@nkh
Created February 16, 2021 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkh/b440a0b59b74f0045521931610a9c63d to your computer and use it in GitHub Desktop.
Save nkh/b440a0b59b74f0045521931610a9c63d to your computer and use it in GitHub Desktop.
use Data::TreeDumper ;
@a = (1, 3, 5, 6, 7, 8 );
@b = ( 2, 3, 5, 7, 9);
# one loop
@union = @isect = @diff = ();
%union = %isect = %diff = ();
foreach $e (@a, @b)
{
$union{$e}++
? do { $isect{$e}++ ; delete $diff{$e} }
: $diff{$e}++ ;
}
@union = keys %union;
@isect = keys %isect;
@diff = keys %diff ;
@a_diff = grep { $diff{$_} } @a ;
@b_diff = grep { $diff{$_} } @b ;
# one loop 2
@union = @isect = @diff = ();
%union = %isect = %diffs = ();
%keys = ( 0 => { map { $_ => 1 } @a}, 1 => { map { $_ => 1 } @b} ) ;
for $e (@a, @b)
{
$union{$e}++
? do { $isect{$e}++ ; delete $diffs{0}{$e} ; delete$diffs{1}{$e} }
: $diffs{$keys{1}{$e} // 0}{$e}++ ;
}
@union = keys %union;
@isect = keys %isect;
@a_diff = keys %{$diffs{0}} ;
@b_diff = keys %{$diffs{1}} ;
@diff = (@a_diff, @b_diff) ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment