Perl Christmas Quiz

Torsten Knorr create-soft at freenet.de
Sun Dec 14 09:44:48 GMT 2008


> 3) Write a Perl function that takes two references to arrays and returns the intersect of them. 
> If an entry appears n times in array 1 and m times in array 2, 
> the output should list that entry min(n,m) times. 
> Bonus mark for one line solutions.

#!/usr/bin/perl -w
#*** compare_int_arrays_v001.pl ***#
#-------------------------------------------------
 use strict;
#-------------------------------------------------
 my (@i_list1, @i_list2);
 push(@i_list1, int(rand(100))) for(1..200);
 push(@i_list2, int(rand(20))) for(1..10);
 print("value:\tlist 1:\tlist 2:\n");
 print("$_->[0]\t$_->[1]\t$_->[2]\n") for(@{Intersect(\@i_list1, \@i_list2)});
#-------------------------------------------------
 sub Intersect
 	{
 	my ($rai_1, $rai_2) = @_;
 	return [] unless(ref($rai_1) eq 'ARRAY' && ref($rai_2) eq 'ARRAY');
 	my (%i_seen, @i_ret);
 	$i_seen{$_}[0]++ for(@$rai_1);
 	$i_seen{$_}[1]++ for(@$rai_2);
 	@i_ret = map [$_, $i_seen{$_}[0], $i_seen{$_}[1]],
 	grep $i_seen{$_}[0] && $i_seen{$_}[1],
 	keys(%i_seen);
 	return [sort({ $a->[0] <=> $b->[0]} @i_ret)];
 	}
#-------------------------------------------------

 Torsten




More information about the london.pm mailing list