-1

让我们很容易做到这一点。我想要的是:

@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.

如何打印数组/哈希的重复值?

4

6 回答 6

8
sub duplicate {
    my @args = @_;
    my %items;
    for my $element(@args) {
        $items{$element}++;
    }
    return grep {$items{$_} > 1} keys %items;
}
于 2008-10-31T22:44:54.353 回答
2

您想要做的更详细、更易读的版本:


sub duplicate {
   my %value_hash;
   foreach my $val (@_) {
     $value_hash{$val} +=1;
   }
   my @arr;
   while (my ($val, $num) = each(%value_hash)) {
     if ($num > 1) {
        push(@arr, $val)
     }
   }
  return @arr;
}

这可以大大缩短,但我故意让它冗长,以便您可以跟进。

不过,我没有对其进行测试,因此请注意我的拼写错误。

于 2008-10-31T22:48:47.590 回答
2
# 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";
于 2008-10-31T22:50:07.637 回答
0

使用字典,将值放入键中,将计数放入值中。

啊,刚刚注意到你标记为 perl

尽管 ([...]) {
 $哈希{[dbvalue]}++
}
于 2008-10-31T22:32:17.233 回答
0

问题中未指定的是应返回重复项的顺序。

我能想到几种可能:不关心;按输入列表中第一次/第二次/最后一次出现的顺序;排序。

于 2008-11-02T02:53:19.610 回答
-1

我要去打高尔夫球!

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 occurrence of each duplicated item is important
sub duplicate {
    my %count;
    grep ++$count{$_} == 2, @_;
}
于 2008-11-01T23:01:30.357 回答