0

交叉发布在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;
}
4

1 回答 1

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;
}
于 2012-06-21T13:23:45.073 回答