intersections entre 2 arrays

intersections entre 2 arrays - Perl - Programmation

Marsh Posté le 12-03-2017 à 01:08:40    

Bonsoir à tous,  
 
,
Depuis plusieurs heures que j'essai de trouver une solution à mon problème.. en fait je veux extraire l'intersection entre 2 tableaux, j'ai fait ce code :

Code :
  1. use strict;
  2. use Data::Dumper;
  3.  
  4. my @array1 = (1, 2, 3,3,3,3,4);
  5. my @array2 = (2, 3, 4,4,4);
  6. my %original = ();
  7. my @isect = ();
  8.  
  9. map { $original{$_} = 1 } @array1;
  10. @isect = grep { $original{$_} } @array2;
  11.  
  12. print "@isect\n";


le résultat est 2 3 4 4 4  
mais ce n'est pas vraiment ce que je souhaite avoir l'intersection dois etre : 2 3 4  
un autre exemple si :  
my @array1 = (5,6,5,7);
my @array2 = (5,6,7,7);
alors le résultat est : 5 6 7

Reply

Marsh Posté le 12-03-2017 à 01:08:40   

Reply

Marsh Posté le 12-03-2017 à 03:29:32    

my (%h1, %h2);
foreach (@array1) { $h1{$_}++ }
foreach (@array2) { if ($h1{$_}) { $h2{$_}++} }
foreach (keys %h2) { if ($h1{$_} < $h2{$_}) { $h2{$_} = $h1{$_} } }
foreach (keys %h2) { push @isect, ($_) x $h2{$_} }
sort @isect;

 

A+,


Message édité par gilou le 12-03-2017 à 19:10:31

---------------
There's more than what can be linked! --    Iyashikei Anime Forever!    --  AngularJS c'est un framework d'engulé!  --
Reply

Sujets relatifs:

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed