Hi all,
Let's make this very easy. What I want:
@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.
Thanks =)
Hi all,
Let's make this very easy. What I want:
@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.
Thanks =)
Use a dictionary, put the value in the key, and the count in the value.
Ah, just noticed you've tagged as perl
while ([...]) { $hash{[dbvalue]}++ }
sub duplicate {
my @args = @_;
my %items;
for my $element(@args) {
$items{$element}++;
}
return grep {$items{$_} > 1} keys %items;
}
# assumes inputs can be hash keys
@a = (1, 2, 3, 3, 4, 4, 5);
# keep count for each unique input
%h = ();
map { $h{$_}++ } @a;
# duplicate inputs have count > 1
@dupes = grep { $h{$_} > 1 } keys %h;
# should print 3, 4
print join(", ", sort @dupes), "\n";
I'm going golfing!
sub duplicate {
my %count;
grep $count{$_}++, @_;
}
@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.
# or if returning *exactly* 1 occurrance of each duplicated item is important
sub duplicate {
my %count;
grep ++$count{$_} == 2, @_;
}
Unspecified in the question is the order in which the duplicates should be returned.
I can think of several possibilities: don't care; by order of first/second/last occurrence in the input list; sorted.