Brute force solution. I wanted to have it near the top (along with my random solution) to show how an inefficient, but obvious solution would work. I would hope that solutions down the line would have much better performance and more creativity. :-)

Note: I have seen someone (cannot remember who) calling Knuth's algorithm for mastermind a brute force algorithm. If it is the one I am thinking of, it is not a brute force algorithm, but (1) trims impossible solutions, and (2) orders guesses by highest potential of helping do (1) on the next pass.

sub MidLifeXis_bruteforce { my $p = shift; my $v = shift; my $check = shift; my $worker = sub { my $worker = shift; my $prefix = shift; my $tot_size = shift; my $places = shift; my $alphabet = shift; my $check = shift; my @solution = ( 0, 0 ); foreach my $letter (@$alphabet) { if ($places < 1) { return ''; } elsif ($places == 1) { @solution = $check->( $prefix . $letter ); return ( $prefix . $letter ) if ( $solution[1] == $tot_size ); } else { my $try = $worker->( $worker, $prefix . $letter, $tot_size, $places - 1, [ grep { $_ ne $letter } @$alphabet ], $check, ); return $try if $try; } } return ''; }; $worker->( $worker, '', $p, $p, [ ( '0' .. '9', 'A' .. 'Z' )[ 0 .. $v - 1 ] ], $check, ); }

--MidLifeXis

Please consider supporting my wife as she walks in the 2009 Alzheimer's Walk.


In reply to Re^2: Challenge: Optimal Bagels Strategy (Solutions) by MidLifeXis
in thread Challenge: Optimal Bagels Strategy by Limbic~Region

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.