#!/usr/bin/perl -w use strict; my $wunschgewicht = $ARGV[0]; die "Bitte Wunschgewicht angeben!\n" unless $wunschgewicht; my (@ary, %decl_hash, $erklaer, $best, $cent); my $diff = 200; $cent->{" "} = 0.00; $cent->{"1Cent"} = 2.30; $cent->{"2Cent"} = 3.06; $cent->{"5Cent"} = 3.92; $cent->{"10Cent"} = 4.10; $cent->{"20Cent"} = 5.74; $cent->{"50Cent"} = 7.80; $cent->{"1Euro"} = 7.50; $cent->{"2Euro"} = 8.50; # fill combinational array: 3 coins are combined to a sum and stored # in @ary. The explanations are put into %decl_hash. foreach my $r (keys %$cent){ foreach my $s (keys %$cent){ foreach my $t (keys %$cent){ my $w1 = $cent->{$r}; my $w2 = $cent->{$s}; my $w3 = $cent->{$t}; my $w = $w1 + $w2 + $w3; push @ary, $w; $decl_hash{$w} ="$r + $s + $t"; } } } # test combinations: The composed weights are combined with eachother # and the best combination is held in $best respectively $erklaer. foreach my $i (@ary){ foreach my $j (@ary){ my $combin = $i - $j; my $d = abs($combin - $wunschgewicht); if($d < $diff){ $best = $combin; $diff = $d; $erklaer = "( $decl_hash{$i} ) - ( $decl_hash{$j} )"; }elsif(($d == $diff) && length("( $decl_hash{$i} ) - ( $decl_hash{$j} )") < length($erklaer)){ $best = $combin; $diff = $d; $erklaer = "( $decl_hash{$i} ) - ( $decl_hash{$j} )"; } } } $erklaer =~ s#\ *\+\ +\+\ *# + #g; $best = sprintf("%.5f", $best); print "$erklaer = $best Gramm\n";