A few thoughts: Given that, one solution could be as follows:
my $MIN_BEST = 2; my @words; my %letters_cache; while (<DATA>) { my ($i, $word) = split; push @{$words[$i-1]}, $word; $letters_cache{$word}{$_} = () = $word =~ /($_)/g for 'a'..'z'; } my %best; my %skip; for my $i (0 .. $#words) { for my $l ('a'..'z') { my $best = 0; $best{$l}[$i] = []; for my $word (@{$words[$i]}) { my $c = $letters_cache{$word}{$l}; if ( $c > $best ) { $best{$l}[$i] = [ $word ]; $best = $c; } elsif ( $c == $best ) { push @{$best{$l}[$i]}, $word; } } $skip{$l}++ if $best < $MIN_BEST; } } my @best_words; my $best_score = 0; foreach my $l ( 'a' .. 'z' ) { next if $skip{$l}; my $iter = NestedLoops($best{$l}); while ( my @w = $iter->() ) { @w = map { ref$_ ? @$_ : $_ } @w; my $score = calculate_score( @w ); if ( $score > $best_score ) { $best_score = $score; @best_words = @w; } } } sub calculate_score { my %letters; foreach my $w (@_) { my $v = $letters_cache{$w}; while (my ($l,$n) = each %$v) { $letters{$l} += $n; } } # add them up. our ($a,$b); # get rid of warning? reduce { $a + calculate_letter_value($b) } 0, values %letters; } sub calculate_letter_value { my $n = shift; ($n * ($n + 1)) / 2; }

This uses your calculate_score() function slightly modified to not change its arguments. I also come up with your 474 list, but in about 0.1 seconds on a PIII-700 with 768M of RAM using the larger dataset you provided. With the full dataset (all 50 states, etc), the prunings I used will remove the best possible score, but I'll get close.


My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

In reply to Re: Challenge: Letter Power by dragonchild
in thread Challenge: Letter Power by Tanktalus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.