use strict; use warnings; my @costs; push @costs, [split(/\s+/)] for (); my @combos; gen_set([0..7],[],4,\@combos); my $min_cost = 999999; my $min_set_num; for (0..$#combos) { my $set_cost = get_cost(@{$combos[$_]}); if ($set_cost < $min_cost) { $min_cost = $set_cost; $min_set_num = $_; } } print "Set number $min_set_num, cost $min_cost: ". join(q{ },@{$combos[$min_set_num]}) . "\n"; sub get_cost { my @list = @_; my %list = map { $_ => 1 } @list; my $cost; for my $li (@list) { for my $oi (grep {not exists $list{$_}} (0..7)) { $cost += $costs[$li]->[$oi]; } } return $cost; } sub gen_set { my ($from, $to, $num, $results) = @_; for my $item (@$from) { my @new_to = @$to; push @new_to, $item; if ($num == 1) { push @$results, \@new_to; } else { my @new_from = grep { $_ != $item } @$from; gen_set(\@new_from,\@new_to,$num-1,$results); } } } __DATA__ - 38 72 79 58 88 59 33 38 - 70 71 27 47 77 14 72 70 - 90 42 63 56 90 79 71 90 - 60 57 21 95 58 27 42 60 - 28 33 52 88 47 63 57 28 - 11 85 59 77 56 21 33 11 - 59 33 14 90 95 52 85 59 -