my $ideal_avg_per_group = @list / 6; # your solution my $solution = [ [1 1 1 2 3], [4 4 4 5 5], [6 6 6 7 7], [8 8 8] ]; my $this_score = 0; for (@$solution) { my $num_items = @$_; $this_score += abs($ideal_avg_per_group - $num_items); }