在http://perlmonks.org/index.pl?node_id=977333
交叉发布给出以下哈希:
my %hash = (1 => "i", 2 => "j", 3 => "k", 4=> "l");
和输入对
my @pair = (1,2);
my @pair2 = (2,3);
my @pair3 = (1,3);
my @pair4 = (2,4);
我们希望在%hash
中找到值小于成员的键
任何给定的对。
所需的输出是:
@pair -> []
@pair2 -> [1]
@pair3 -> [2]
@pair4 -> [1,3]
这样做的正确算法是什么? 以下是我的代码,但失败了:
sub get_output {
my ($inputhash,$pair) = @_;
my @output = ();
my %done = ();
foreach my $pr (@{$pair}){
foreach my $kn (keys %{$inputhash}){
next if ($pr <= $kn || $done{$kn});
push @output,$kn;
$done{$kn} = 1;
}
}
use Data::Dumper;
print Dumper \@output;
return @output;
}
答案 0 :(得分:1)
效率不高但效果很好。仍然没有看到散列的点,因为您请求的输出不涉及散列。:
#!/usr/bin/perl
use strict;
use warnings;
my %hash = (1 => "i", 2 => "j", 3 => "k", 4=> "l");
my @pair = (1,2); #tested all your cases and it showed to work
my $it;
my $iterator;
my $sit;
my @occurence;
my @oldpair = @pair;
@occurence = (0, 0, 0, 0);
foreach(@oldpair)
{
if ($_ == 1)
{
$occurence[0] += 1;
}
if ($_ == 2)
{
push(@pair, 1);
$occurence[0] += 1;
$occurence[1] += 1;
}
if ($_ == 3)
{
push(@pair, 2);
$occurence[1] += 1;
$occurence[2] += 1;
}
if ($_ == 4)
{
push(@pair, 3);
$occurence[2] += 1;
$occurence[3] += 1;
}
}
foreach $iterator(@occurence)
{
$it++;
if ($iterator > 1)
{
@pair = grep { $_ != $it } @pair;
}
}
foreach $sit(@oldpair)
{
@pair = grep { $_ != $sit } @pair;
}