views:

1194

answers:

7

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 =)

A: 

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]}++
}
Dave
Eh... it's starting to get a little late, I really think I need som code examples. ;-)
Lasse A Karlsen
+8  A: 
sub duplicate {
    my @args = @_;
    my %items;
    for my $element(@args) {
        $items{$element}++;
    }
    return grep {$items{$_} > 1} keys %items;
}
Leon Timmermans
I think there is a semicolon missing after the hash declaration.
Svante
You're right, I've added it now.
Leon Timmermans
+1  A: 
SquareCog
@array = qw/one two one/ is a _perfectly_ acceptable way of writing that.
Alnitak
I wrote that before Brian D Foy fixed up the original question. He had scalars there originally.. but I've now removed the "first off" comment, since it no longer makes sense.
SquareCog
+2  A: 
# 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";
Amanibhavam
Write `$h{$_}++ for @a;` instead of using `map` in void context.
Aristotle Pagaltzis
A: 

Thanks for the replies, guys! My problem is now solved.

:-)

Lasse A Karlsen
A: 

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, @_;
}
ephemient
That code has an issue in that it will return an element more than once when it occurs three or more times.
Leon Timmermans
Right, you want grep 1==$count{$_}++, ...
ysth
Also, you want to put braces around that.
Leon Timmermans
It depends on whether you want 2 of 3 occurrances returned, or only 1; the question didn't specify. Braces aren't needed.
ephemient
A: 

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.

ysth