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

Here is something for the monks to mull over on the weekend. It is not a perl specific thing but I fear that large amounts of perl ingenuity will be required to solve it.

Q: What is the shortest string that contains all the numbers from 0000 to 9999.

For example: '012345678' contains 0123, 1234, 2345, 3456, 4567, 5678.

Is it possible to create a string which contains all the numbers and no duplicates? To date my best achievement is:

Length is: '10427'. Missing count: '0' Duplicate count: '424'

Please feel free to use this function to test any strings produced:

# Will return an analysis of the string. # Usage: print analyse( $string ); sub analyse { # Make an array from the number and create hash. my $number = shift; my @string = split //, $number; my %count = (); # Work over the number adding values to the hash. while (1) { my $candidate = $string[0].$string[1].$string[2].$string[3]; $count{$candidate}++; # Get rid of first element of the array. shift @string; # Break out at the end of array. last if scalar @string < 4; } # Tally up the number of duplicates and missing numbers. my $duplicates = 0; my $missing = 0; for ( 0 .. 9999 ) { my $k = 0 x ( 4 - length $_ ) . $_; my $v = $count{$k}; unless ( defined $v ) { $missing++; next; } $duplicates += ( $v - 1 ) if $v > 1; } # Create the summary. my $text; $text .= " Length is: " . length($number) . "\n"; $text .= " Missing count: " . $missing . "\n"; $text .= "Duplicate count: " . $duplicates . "\n\n"; return $text; }

My thoughts on this puzzle are that you can go about it one of two ways: add unused numbers to the end of the string (technique used for results above) or remove duplicates. Probably the best is a combination of both.

Update: Made a change to the analysis code - pesky CVS caught me out.

--tidiness is the memory loss of environmental mnemonics