home

perl

#!/usr/bin/perl

# blame: shardy@@differentchairs.com

#
# find a value in the given list that occurs an odd number of times
#
sub findOddCount {
	my ($valref, $defVal) = @_;
	my %bucket;

	foreach $v (@$valref) {
		$bucket{$v}++;
		}
	foreach $ii (keys %bucket) {
		if (($bucket{$ii} % 2) != 0) {
			return $ii;
			}
		}
	return $defVal;
}

my $myDefVal = -1;
my @a1 = (1,1,2,2,3,3,4,4,5,5,6,7,7,7,7);
my @a2 = (10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10);
my @a3 = (6,6,10,10,7,7,6,6, 2,2,3,3,4,4,5,5,6,7,7,7,7,10,10);
my @a4 = (10,10,7,7, 2,2,3,3,4,4,5,5,7,7,7,7,10,10,6);
my @a5 = (6,6);
my @a6 = (1);

printf( "odd value in a1 is %d\n", findOddCount(\@a1, $myDefVal) );
printf( "odd value in a2 is %d\n", findOddCount(\@a2, $myDefVal) );
printf( "odd value in a3 is %d\n", findOddCount(\@a3, $myDefVal) );
printf( "odd value in a4 is %d\n", findOddCount(\@a4, $myDefVal) );
printf( "odd value in a5 is %d\n", findOddCount(\@a5, $myDefVal) );
printf( "odd value in a6 is %d\n", findOddCount(\@a6, $myDefVal) );