http://www.perlmonks.org?node_id=86061


in reply to Golf challange: match U.S. State names

Not just a golf solution, its a golf solution generator:

Update: 'Borrowed' tilly's list of states. (my result is a 113 character string - though I too am now wondering where 'KT' is ... I'm told its a brand of whiskey, so I'll keep it in - besides, it is now the 'official' list for this challenge :-)

Another update: Added dws's fix.

#!/usr/local/bin/perl -l -w use strict; my @states=qw( AK AL AR AZ CA CO CT DC DE FL GA HI IA ID IL IN KS KT KY LA MA MD ME MI MN MO MS MT NC ND NE NH NJ NM NV NY OH OK OR PA RI SC SD TN TX UT VA VT WA WI WV WY); my %states; @states{@states} = (); my @results; my $is_done; while (%states) { my ($letter, $is_first); ($letter, $is_first, $is_done) = get_next_letter(\%states); push(@results, keys %states), last if $is_done; my $pos = $is_first ? 0 : 1; my @states = grep { substr($_,$pos,1) eq $letter } keys %states; my $chr_class = '[' . join('', map { substr($_, 1-$pos, 1) } @states) . ']'; push @results, $is_first ? $letter.$chr_class : $chr_class.$letter; delete @states{@states}; } print '/^(',join("|", @results),')$/'; sub get_next_letter { my $states = shift; my (%first, %second, $is_done); for (keys %$states) { my ($first, $second) = split ''; $first{$first}++; $second{$second}++; } my ($first) = sort { $first{$b} <=> $first{$a} } keys %first; my ($second) = sort { $second{$b} <=> $second{$a} } keys %second; $is_done = 1 if $first{$first} == 1 and $second{$second} == 1; ($first{$first} > $second{$second}) ? ($first, 1, $is_done) : ($second, 0, $is_done); } # 113 characters! # Add 5 characters ('pop=~' to the beginning) if you want # it to work on @_ instead of $_ /^([WLPCVGIM]A|N[CDEHJMVY]|M[DEINOST]|[VKUC]T|A[ZKLR]|[WHR]I|O[HKR]|I[ +LND]|[SD]C|[KW]Y|T[XN]|KS|SD|DE|FL|WV|CO)$/