[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Arrarys and numbers



"Ken Cartner (News)" <ken@nando.com> writes:
>I have an associative array of words and numbers, i.e. ("Label1", 10,
>"Label 2", 20, "Label3", 30, "Label4", 40...). This array goes on for 30
>labels and numbers. I'd like to generate all combinations of three items,
>listing the three label names and the sum of their numbers. For example,
>"Label1, Label2 and Label3 equal 60. Label1, Label2 and Label4 equal
>70."

Although this question is not Mac specific, it was too much fun to resist
trying:

sub pickR {
   my($num, $max, $list, $items, $label, $sum) = @_;

   if (!$num) {  # We're done
      print "$label = $sum\n";

      return;
   }
   my @newlist  = @$list;
   my $item     = shift @newlist;
   my $newlabel = $label . ($label?"+":"") . $item;
   my $newsum   = $sum + $items->{$item};
   pickR($num-1, $max-1, \@newlist, $items, $newlabel, $newsum);

   pickR($num, $max-1, \@newlist, $items, $label, $sum)
      unless ($num >= $max); 
}

sub pick {
   my($num, $items) = @_;

   my(@k) = sort keys %$items;
   pickR($num, scalar(@k), \@k, $items, "", 0); 
}

pick(3, {"A" => 20, "B" => 30, "C" => 34, "D" => 5, "E" => 78});

Matthias

-----
Matthias Neeracher   <neeri@iis.ee.ethz.ch>   http://www.iis.ee.ethz.ch/~neeri
   "I'm set free to find a new illusion" -- Velvet Underground







***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch