    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: The Model Student: A Game of Six Integers (Part 2)</title>
        <link>https://members.accu.org/index.php/journals/1621</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #96 - April 2010 + Design of applications and programs</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c269/">96</a>
                    (5)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c67/">Design</a>
                    (236)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c269-67/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c269+67/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;The Model Student: A Game of Six Integers (Part 2)</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 19 April 2010 08:59:00 +01:00 or Mon, 19 April 2010 08:59:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;What are the properties of the Numbers Game? Richard Harris continues his analysis.</p>
<p><strong>Body:</strong>&nbsp;<p>In the first part of this article we introduced the Countdown numbers game [<a href="#Countdown">Countdown</a>]. Part of the longest running game show on UK television and one of the longest running in the world, it involves picking 6 numbers from a choice of 4 large and 20 small numbers, being the integers 25, 50, 75 and 100 and 2 of each of the integers from 1 to 10 respectively.
  </p><p> 
    The contestants must then seek to construct a formula using the binary operators of addition, subtraction, multiplication and division with each of these 6 numbers no more than once, and with no non-integer intermediate values, that evaluates to a randomly selected target between 1 and 999.
  </p><h2>
    Reverse Polish Notation
  </h2><p> 
    In order to simplify the automatic generation of formulae, we introduced Reverse Polish notation, or RPN, a notation for arithmetic formulae supremely suited to programmatic manipulation.
  </p><p> 
    Unlike the more familiar infix notation, RPN places operators immediately to the right, rather than between, their arguments. For example the infix expression 3+4 would be written as 3 4 + in RPN.
  </p><p> 
    RPN utilises a stack to keep track of the intermediate values in a calculation, and in doing so makes explicit the order in which operators are applied, making parentheses redundant.
  </p><p> 
    Every time a number appears in the input sequence it is pushed on to the stack. Every time an operator appears it pops the arguments it requires off of the stack and pushes its result back on to it. If there are not enough arguments on the stack for an operator, or if there is more than one value on the stack at the end of the RPN formula, an error occurs.
  </p><p> 
    For example, Figure 1 illustrates the state of the stack after each term in the RPN formula 3 4 &times; 2 +</p>
    <p>
    <table class="sidebartable"><tr><td>
    <img src="/content/images/journals/ol96//Overload%20WW%20XML%20and%20CSS-2-1-2.gif"/>
    </td></tr><tr><td class="title">Figure 1</td></tr></table>
    </p>
    <h2>
    Formula templates
  </h2><p> 
    Rather than enumerate the set of valid formulae in any possible Countdown numbers game directly, we instead decided to generate templates into which we could substitute operators and arguments. Acting as place-holders for the operators and arguments we used the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">o</span> and <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">x</span> symbols respectively.
  </p><p> 
    We described an algorithm for generating the set of all formula templates with up to a given number of arguments in which, starting with a single <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">x</span> symbol, recursively replaced <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">x</span> symbols with the symbols <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">xxo</span>. Since both the former and the latter result in a single value on the stack, we cannot therefore create an invalid formula by doing so.
  </p><p> 
    In general, this approach could generate some formula template more than once, so we kept track of the generated templates with a <tt class="code">set</tt> of <tt class="code">string</tt>s. The declaration of the <tt class="code">all_templates</tt> function that implements this algorithm is:
  </p>
<pre class="programlisting">
      std::set&lt;std::string&gt; all_templates(  
        size_t arguments);  
</pre><p> 
    Since each substitution introduces 1 additional argument, we can ensure that we terminate the recursion when we have exhausted the available arguments by subtracting 1 from their number with each substitution and stopping when we reach 0.
  </p><p> 
    Figure 2 gives the complete set of formula templates for up to 5 arguments in order of increasing length, as calculated using these functions.</p>
    <p>
<table class="sidebartable"><tr><td>
<p>
<table class="journaltable" border="1" cellspacing="0" cellpadding="4">
<tr><th>X</th><th>XXO</th><th>XXOXO</th><th>XXXOO</th><th>XXOXOXO</th><th>XXOXXOO</th></tr>
<tr><td>xxxooxo</td><td>xxxoxoo</td><td>xxxxooo</td><td>xxoxoxoxo</td><td>xxoxoxxoo</td><td>xxoxxooxo</td></tr>
<tr><td>xxoxxoxoo</td><td>xxoxxxooo</td><td>xxxooxoxo</td><td>xxxooxxoo</td><td>xxxoxooxo</td><td>xxxoxoxoo</td></tr>
<tr><td>xxxoxxooo</td><td>xxxxoooxo</td><td>xxxxooxoo</td><td>xxxxoxooo</td><td>xxxxxoooo</td><td>&nbsp;</td></tr>
</table>
</p>
</td></tr><tr><td class="title">Figure 2</td></tr></table>
    </p>
    <h2>
    Evaluating RPN formula templates
  </h2><p> 
    We concluded by implementing a mechanism by which we could evaluate a given formula template for a given set of operators and arguments. The first step was to implement an abstract base class to represent arbitrary RPN operators and concrete classes derived from it to represent the four valid binary operators of the Countdown number game. The base class and the declarations of the operators are provided in Listing 1.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class T&gt;  
    class rpn_operator  
    {  
    public:  
      typedef std::stack&lt;std::vector&lt;T&gt; &gt;  stack_type;  
 
      virtual ~rpn_operator();  
      virtual bool apply(stack_type &amp;stack) const = 0;  
    };  
 
    template&lt;class T&gt; class rpn_add;  
    template&lt;class T&gt; class rpn_subtract;  
    template&lt;class T&gt; class rpn_multiply;  
    template&lt;class T&gt; class rpn_divide;  
</pre></td></tr><tr><td class="title">Listing 1</td></tr></table>
<p> 
    Note that since the standard <tt class="code">stack</tt> class does everything we require of an RPN stack, we very sensibly, or very lazily, opted to use it rather than implement our own.
  </p><p> 
    The definitions of the four operator classes are, with the exception of their names, identical, so we provide just the definition of <tt class="code">rpn_divide</tt> in Listing 2.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class T&gt;  
    class rpn_divide : public rpn_operator&lt;T&gt;  
    {  
      public:  
        virtual bool apply(stack_type &amp;stack) const;  
    };
  </pre></td></tr><tr><td class="title">Listing 2</td></tr></table>
  <p> 
    Recall that we gave the operators themselves the responsibility for issuing errors in the event that there are not enough arguments on the stack since this allows us to implement operators that require any particular number of arguments should we have cause to do so.
  </p><p> 
    The <tt class="code">rpn_divide</tt> operator is something of a special case in that it is undefined for some arguments. Specifically, for floating point calculations the second argument must be non-zero and for integer calculations it must wholly divide the first.
  </p><p> 
    It is, therefore, the only one of the four operators that might return <tt class="code">false</tt> from its <tt class="code">apply</tt> member function, indicating that an invalid intermediate value resulted from its application.
  </p><p> 
    We then implemented a simple structure to represent both the validity and the value of the result of a calculation. Given in Listing 3, the <tt class="code">rpn_result</tt> structure is considered valid if it is constructed with a value and invalid if it is not.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class T&gt;  
    struct rpn_result  
    {  
      rpn_result();  
      explicit rpn_result(const T &amp;t);  
 
      bool valid;  
      T    value;  
    };  
  </pre></td></tr><tr><td class="title">Listing 3</td></tr></table>
  <p> 
    Finally, we implemented a function that, given a formula template represented by a string of <tt class="code">o</tt> and <tt class="code">x</tt> characters, a <tt class="code">vector</tt> of pointers to <tt class="code">rpn_operators</tt> and a <tt class="code">vector</tt> of arguments, would substitute the latter pair into the former to produce a result.
  </p><p> 
    The <tt class="code">rpn_evaluate</tt> function, the declaration of which is shown in Listing 4, iterated over the formula template string, pushing the current argument on to the stack of the current term is an <tt class="code">x</tt>, and applying the current operator if it is an <tt class="code">o</tt>. We assert the correctness of the calculation by throwing exceptions if there aren't enough arguments or operators, or if there is not exactly one value on the stack at the end.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class T&gt;  
    rpn_result&lt;T&gt;  
    rpn_evaluate(const std::string &amp;formula,  
      const std::vector&lt;rpn_operator&lt;T&gt; const *&gt;  
      &amp;operators,  
      const std::vector&lt;T&gt; &amp;arguments);  
  </pre></td></tr><tr><td class="title">Listing 4</td></tr></table>
  <p> 
    Whilst this approach isn't particularly useful as a general purpose RPN calculator due to the separation of the formula template, the operators and the arguments, it is particularly well suited to the programmatic evaluation of formulae for precisely the same reason.
  </p><h2>
    Counting the number of formulae
  </h2><p> 
    We noted that in order to fully investigate the statistical properties of the Countdown numbers game we should need a means to enumerate every possible formula that might be expressed.
  </p><p> 
    Recall that we proved that the total number of formulae that it is possible to construct with the 4 binary operations and 6 of the 24 possible arguments was
  </p>
  <img src="/content/images/journals/ol96//Overload%20WW%20XML%20and%20CSS-2-1-4.gif"/>
  <p> 
    where <span style="  font-style: normal; font-weight: normal; vertical-align: super">24</span>C<span style="  font-style: normal; font-weight: normal; vertical-align: sub">6</span> is the number of ways in which we can choose 6 from 24 items when their order is not important, <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">T</span><span style="  font-style: italic; font-weight: normal; vertical-align: sub">i</span> is the number of formula templates with <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span> arguments, 4<span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span>-1 is the number of sets of binary operators that can appear in a formula with <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span> arguments, and <span style="  font-style: normal; font-weight: normal; vertical-align: super">6</span><span style="  font-style: italic; font-weight: normal; vertical-align: baseline">P</span><span style="  font-style: italic; font-weight: normal; vertical-align: sub">i</span> is the number of ways in which we can choose <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span> from 6 items when their order <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">is</span> important.
  </p><p> 
    In light of this result, we concluded that in order to generate every possible formula we would need to enumerate the <span style="  font-style: normal; font-weight: normal; vertical-align: super">24</span><span style="  font-style: italic; font-weight: normal; vertical-align: baseline">C</span><span style="  font-style: normal; font-weight: normal; vertical-align: sub">6</span> combinations of selected numbers, the set of templates with up to 6 arguments, the 4<span style="  font-style: italic; font-weight: normal; vertical-align: super">n</span><span style="  font-style: normal; font-weight: normal; vertical-align: super">-1</span> sets of operators required by formulae with <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span> arguments and the <span style="  font-style: normal; font-weight: normal; vertical-align: super">6</span><span style="  font-style: italic; font-weight: normal; vertical-align: baseline">P</span><span style="  font-style: italic; font-weight: normal; vertical-align: sub">n</span> permutations of <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span> out of 6 arguments.
  </p><p> 
    We closed with the suggestion that the standard <tt class="code">next_permutation</tt> function might be an excellent example to follow and it is at this point that I mean to resume our study.
  </p><h2>
    Evaluating every formula for a given template
  </h2><p> 
    Fortunately for us, we solved the second part of this task during our analysis of knots in a previous study [<a href="#Harris08">Harris08</a>]. The <tt class="code">rotate_state</tt> and <tt class="code">next_state</tt> functions which we used to iterate through every possible state of a set of sequential integer-like values are presented again in Listing 5.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class BidIt, class T&gt;  
    bool  
    rotate_state(BidIt it, const T &amp;lb, const T &amp;ub)  
    {  
      bool last = ++*it==ub;  
      if(last) *it=lb;  
      return last;  
    }  
 
    template&lt;class BidIt, class T&gt;  
    bool  
    next_state(BidIt first, BidIt last,  
       const T &amp;ub, const T &amp;lb = T())  
    {  
      BidIt it = last;  
      while(it!=first &amp;&amp; rotate_state(--it, lb, ub));  
      return first!=last &amp;&amp; (it!=first || *it!=lb);  
    }  
  </pre></td></tr><tr><td class="title">Listing 5</td></tr></table>  
<p> 
    Since iterators behave in a sequential integer-like fashion, we can place instances of our four RPN operators in a container and use <tt class="code">next_state</tt> with the iterators ranging over it to generate every possible set of operators.
  </p><p> 
    The third part is a little more complicated. The standard library already provides us with a function to iterate through every permutation of a strictly ordered set of values in <tt class="code">next_permutation</tt>. Unfortunately, it does not give us a mechanism for iterating through the permutations of the subsets of such a set, so we shall have to knock one together ourselves.
  </p><p> 
    Since <tt class="code">next_permutation</tt> enumerates the permutations of the elements in the iterator range passed to it in lexicographical order, we can trick it into jumping past permutations of the elements not in the subset of interest. We do this by ensuring that they are in their lexicographically final order, thus forcing the next permutation to be the one that enumerates the next subset. Specifically we sort the spare elements in decreasing order, as illustrated in Listing 6.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class BidIt&gt;  
    bool  
    next_permutation(BidIt first,  
       BidIt mid, BidIt last)  
    {  
      std::sort(mid, last);  
      std::reverse(mid, last);  
      return std::next_permutation(first, last);  
    }  
  </pre></td></tr><tr><td class="title">Listing 6</td></tr></table>
<p> 
    This new version of the <tt class="code">next_permutation</tt> function thus enumerates the permutations of <tt class="code">mid-first</tt> elements from the iterator range <tt class="code">first</tt> to <tt class="code">last</tt> in lexicographical order. Listing 7 shows how we would use this function to enumerate the set of permutations of two elements from a vector containing the integers 0 to 3.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    std::vector&lt;long&gt; seq;  
    for(size_t i=0;i!=4;++i)  seq.push_back(i);  
 
    std::vector&lt;long&gt;::iterator first = seq.begin();  
    std::vector&lt;long&gt;::iterator mid   = seq.begin()+2;  
    std::vector&lt;long&gt;::iterator last  = seq.end();  
 
    do  
    {  
      std::vector&lt;long&gt;::iterator it = first;  
      while(it!=mid)  std::cout &lt;&lt; *it++ &lt;&lt; &quot; &quot;;  
      std::cout &lt;&lt; std::endl;  
    }  
    while(next_permutation(first, mid, last));  
  </pre></td></tr><tr><td class="title">Listing 7</td></tr></table>
<p> 
    The output of this code snippet is given in Figure 3 and, as you can see, it correctly lists the permutations of two elements in lexicographically increasing order.
    </p>
    <p>
<table class="sidebartable"><tr><td>
<p align="center">
0&nbsp;&nbsp;1<br/>
0&nbsp;&nbsp;2<br/>
0&nbsp;&nbsp;3<br/>
1&nbsp;&nbsp;0<br/>
1&nbsp;&nbsp;2<br/>
1&nbsp;&nbsp;3<br/>
2&nbsp;&nbsp;0<br/>
2&nbsp;&nbsp;1<br/>
2&nbsp;&nbsp;3<br/>
3&nbsp;&nbsp;0<br/>
3&nbsp;&nbsp;1<br/>
3&nbsp;&nbsp;2<br/>
</p>
</td></tr><tr><td class="title">Figure 3</td></tr></table>
    </p>
    <p> 
    Note that since we have implemented our new <tt class="code">next_permutation</tt> function in terms of the standard one, we are subject to its restrictions. Specifically, the sequence cannot contain two or more elements with equivalent ordering. This condition shall not necessarily be met by the numbers we pick in the Countdown numbers game since there are two of each of the integers from 1 to 10. We shall sidestep this by instead considering permutations of iterators from a sequence of the selected numbers, which will guaranteed to be unique.
  </p><p> 
    The major issue I have with this new overload is that it sorts the spare elements at every step, despite the fact that in a series of calls to it they are guaranteed to be sorted for all but the first call.
  </p><p> 
    We can improve matters somewhat by first checking whether or not these elements are already sorted. Assuming we have <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span> unused elements, this is at worst an <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span>-step operation; hardly ideal, but certainly better than the worst case of the call to <tt class="code">sort</tt> which is greater by a factor of the base 2 logarithm of <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span>. We shall do this using another function, <tt class="code">sorted</tt>, as illustrated in Listing 8.<sup>1</sup></p>
    <table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class BidIt&gt;  
    bool  
    sorted(BidIt first, BidIt last)  
    {  
      BidIt next = first;  
      if(next!=last)  ++next;  
 
      while(next!=last &amp;&amp; !(*next&lt;*first)) {  
         ++first; ++next;}  
      return next==last;  
    }  
 
    template&lt;class BidIt&gt;  
    bool  
    next_permutation(BidIt first, BidIt mid,  
       BidIt last)  
    {  
      if(!sorted(mid, last))  std::sort(mid, last);  
      std::reverse(mid, last);  
      return std::next_permutation(first, last);  
    }  
    </pre></td></tr><tr><td class="title">Listing 8</td></tr></table>
<p> 
    Whilst I'm sure that with some thought we could come up with something more efficient, the relative simplicity of this approach is enough to convince me to stick with it.
  </p><h2>
    Enumerating the choice of numbers
  </h2><p> 
    Well, we're nearly ready to start investigating the properties of the Countdown numbers game in detail.
  </p><p> 
    All that remains to do is to implement a mechanism for enumerating every way in which we might pick 6 numbers from the available 24. We don't care about their order since we shall be iterating through the permutations of the chosen numbers when we evaluate each function template. Hence we shall need to enumerate the combinations of 6 out of the 24 numbers.
  </p><p> 
    We might as well shoot for a general purpose implementation along the lines of our <tt class="code">next_permutation</tt> overload, as illustrated by the following declaration:
  </p>
<pre class="programlisting">
      template&lt;class BidIt&gt; bool next_combination(  
         BidIt first, BidIt mid, BidIt last);  
 
</pre><p> 
    This function should transform the range <tt class="code">first</tt> to <tt class="code">mid</tt> to the lexicographically subsequent combination of <tt class="code">mid-first</tt> elements from the range <tt class="code">first</tt> to <tt class="code">last</tt>. Furthermore, like <tt class="code">next_permutation</tt>, it should, upon having exhausted the set of combinations, leave the range in a sorted state and return <tt class="code">false</tt>.
  </p><h2>
    An algorithm for enumerating combinations
  </h2><p> 
    Having trawled through my personal library for an algorithm to enumerate combinations in such a fashion, I unfortunately emerged empty handed. We shall therefore have to don the mantle of such luminaries as Knuth and Cormen <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">et al</span> and come up with an algorithm of our own.
  </p><p> 
    The first thing we should note in seeking an algorithm to enumerate the combinations of a set is that combinations are subsets that are distinguished only by the elements that they contain and not by the order of those elements, as permutations are. To simplify their enumeration it therefore makes sense to keep the elements of the combinations in a particular order; specifically in increasing order.
  </p><p> 
    To describe the algorithm, I shall use the example of enumerating the combinations of four of the integers from 1 to 6. Since we want the algorithm to act as much like the standard <tt class="code">next_permutation</tt> function as possible, and hence work for any elements that can be strictly ordered, we must avoid all operations other than assignment, or strictly speaking swapping, and the less than operator.
  </p><p> 
    We shall represent a permutation as a sequence of elements, with a bar separating the elements that are in the combination from those that are not. For example, the lexicographically first combination of four from six integers shall be represented as
  </p><p class="indented"> 
    1 2 3 4 | 5 6
  </p><p> 
    The clue that nudges us in the direction of an effective algorithm is that fact that if we rotate the last three elements of the sequence one  to the left, we generate the lexicographically subsequent combination
  </p><p class="indented"> 
    1 2 3 5 | 6 4
  </p><p> 
    Doing so again generates the next combination
  </p><p class="indented"> 
    1 2 3 6 | 4 5
  </p><p> 
    At this point applying the same operation will return us to a lexicographically earlier combination; the very first as it happens. Fortunately, we can identify that this is about to happen since the element after the bar is now less than the element before it.
  </p><p> 
    What we need to do next is return the sequence to its original order and rotate the last four elements, yielding
  </p><p class="indented"> 
    1 2 4 5 | 6 3
  </p><p> 
    And herein lays the basic principal by which our algorithm shall algorithmicate.
  </p><p> 
    If the rotation of the last element in the combination would yield a lexicographically earlier sequence, we iterate backwards through the combination seeking an element for which we can rotate the following elements to return it and them to their lowest lexicographical order. We then rotate both it and them together to yield the lexicographically subsequent combination.
  </p><p> 
    As an example, let us consider the combination
  </p><p class="indented"> 
    2 4 5 6 | 1 3
  </p><p> 
    As we iterate back through the elements of the combination we find that the last element for which we can rotate subsequent the elements into an increasing order is in fact the first. Choosing the lexicographically earliest sequence we can thusly generate we have
  </p><p class="indented"> 
    2 3 4 5 | 6 1
  </p><p> 
    Now rotating the first and subsequent elements yields
  </p><p class="indented"> 
    3 4 5 6 | 1 2
  </p><p> 
    which is, as can easily be confirmed, the lexicographically next greatest combination.
  </p><p> 
    The full enumeration of our example combinations would proceed as illustrated in Figure 4, in which we differentiate the valid combinations from the intermediate steps with a bold font and we identify the elements that we shall need to rotate by underlining them.
    </p>
    <p>
<table class="sidebartable"><tr><td>
<p align="center">
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;4&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<u>2</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>2</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;3&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<u>2</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;3&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>2</u>&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;3&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<u>2</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>2</u>&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;<u>1</u>&nbsp;&nbsp;<u>2</u>&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<u>1</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>1</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<u>1</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>1</u>&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;2&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<u>1</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;2&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>1</u>&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;<u>2</u>&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;<u>1</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;<u>3</u>&nbsp;&nbsp;<u>4</u>&nbsp;&nbsp;<u>5</u>&nbsp;&nbsp;<u>6</u>&nbsp;&nbsp;|&nbsp;&nbsp;<u>1</u>&nbsp;&nbsp;<u>2</u>&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;|&nbsp;&nbsp;5&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
</p>
</td></tr><tr><td class="title">Figure 4</td></tr></table>
</p><h2>
    Implementing our algorithm in C++
  </h2><p> 
    Now English is a pretty damn inconvenient language in which to describe algorithms, which is of course why Algol was invented. That said, this is ostensibly a C++ article and so, Algol be damned, we shall formally describe our algorithm in C++.
  </p><p> 
    Before we can proceed to an implementation of the <tt class="code">next_combination</tt> function, however, we shall need some helper functions.
  </p><p> 
    As we did in our <tt class="code">next_permutation</tt> overload, we shall need to check whether or not the input sequence represents a valid combination and if not, rearrange its elements so that it does. Again, the reason for performing the check first is that it is computationally less expensive than rearranging the elements and the sequence will always be a valid combination after the call to the function.
  </p><p> 
    Specifically a valid combination will be sorted between <tt class="code">first</tt> and <tt class="code">mid</tt>, and from <tt class="code">mid</tt> to <tt class="code">last</tt> will be a rotation of the sorted elements such that either <tt class="code">mid</tt> contains the next largest element than the one that precedes it, or that every element in the range is smaller than it.
  </p><p> 
    Listing 9 illustrates the function that we shall use to check whether or not the sequence is a combination.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class BidIt&gt;  
    bool  
    is_combination(BidIt first, BidIt mid, BidIt last)  
    {  
      if(mid==first || mid==last) return sorted(  
         first, last);  
      if(!sorted(first, mid))     return false;  
 
      BidIt prev = mid; --prev;  
      BidIt next = mid; ++next;  
 
      while(next!=last &amp;&amp; !(*next&lt;*mid)  
         &amp;&amp; *prev&lt;*mid) {++mid;++next;}  
 
      if(next==last) return true;  
      if(*mid&lt;*prev) return false;  
      ++mid; ++next;  
      while(next!=last &amp;&amp; !(*next&lt;*mid)   
         &amp;&amp; !(*prev&lt;*mid)) {++mid;++next;}  
 
      return next==last;  
    }  
  </pre></td></tr><tr><td class="title">Listing 9</td></tr></table>
<p> 
    We make a sequence into a combination by sorting the elements between <tt class="code">first</tt> and <tt class="code">mid</tt> and the elements between <tt class="code">mid</tt> and <tt class="code">last</tt> before finally rotating the latter so that the smallest of them that is greater than the last of the former is in <tt class="code">mid</tt>.
  </p><p> 
    Listing 10 provides the definition of the function that rearranges the elements into valid a combination.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class BidIt&gt;  
    void  
    make_combination(BidIt first, BidIt mid,  
       BidIt last)  
    {  
      std::sort(first, mid);  
      std::sort(mid, last);  
 
      BidIt prev = mid;  
      if(prev!=first)  
      {  
        std::rotate(mid, std::upper_bound(  
           mid, last, *--prev), last);  
      }  
    }
  </pre></td></tr><tr><td class="title">Listing 10</td></tr></table>
<p> 
    The final helper function that we shall need is one to find the smallest element in the range <tt class="code">mid</tt> to <tt class="code">last</tt> that is larger than the last in the range <tt class="code">first</tt> to <tt class="code">mid</tt> that is smaller than any of them. We cannot use <tt class="code">upper_bound</tt> this time since the range will not, in general, be sorted. Listing 11 illustrates the function that we shall use to locate the element in question.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class BidIt, class T&gt;  
    BidIt  
    min_greater(BidIt first, BidIt last, const T &amp;t)  
    {  
      BidIt result = last;  
      while(first!=last)  
      {  
        if(t&lt;*first &amp;&amp; (  
           result==last || *first&lt;*result))  
           result = first;  
        ++first;  
      }  
      return result;  
    }  
  </pre></td></tr><tr><td class="title">Listing 11</td></tr></table>
<p> 
    We are now ready to implement the <tt class="code">next_combination </tt>as shown in Listing 12. As you can clearly see, this is simply our algorithm directly translated into C++, with a few extra conditions to cover the corner cases of combinations of none or all of the elements in the sequence.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class BidIt&gt;  
    bool  
    next_combination(BidIt first, BidIt mid,  
       BidIt last)  
    {  
      if(!is_combination(first, mid, last))  
      {  
        make_combination(first, mid, last);  
      }  
 
      if(mid==first || mid==last) return false;  
 
      BidIt next = mid;  
      BidIt prev = mid; --prev;  
 
      if(!(*prev&lt;*next))  
      {  
        BidIt target = last;  
        while(target==last &amp;&amp; prev!=first)  
        {  
          target = min_greater(mid, last, *--prev);  
        }  
 
        if(target==last)  
        {  
          std::rotate(first, mid, last);  
          return false;  
        }  
 
        next = prev; ++next;  
        std::rotate(next, target, last);  
      }  
 
      std::rotate(prev, next, last);  
      return true;  
    }  
  </pre></td></tr><tr><td class="title">Listing 12</td></tr></table>
<p> 
    Note that, like <tt class="code">next_permutation</tt>, this function can't cope with sequences that contain multiple elements with equivalent orderings and will terminate before having enumerated the full set of combinations for such sequences.
  </p><p> 
    Once again, I'm not entirely convinced that this is the most efficient possible algorithm. However, given that checking whether or not an input sequence of <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span> elements is a combination requires at best <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span> operations, and that our algorithm requires at worst a fixed multiple of <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span> operations, I suspect that it could only be bettered by some constant factor.
  </p><p> 
    Figure 5 illustrates the result of enumerating the set of combinations of four from the integers 1 to 6 using this function.
    </p>
    <p>
<table class="sidebartable"><tr><td>
<p align="center">
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;5&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;4&nbsp;&nbsp;5&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;4&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;5&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;5&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;3&nbsp;&nbsp;5&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
&nbsp;&nbsp;1&nbsp;&nbsp;4&nbsp;&nbsp;5&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;5&nbsp;&nbsp;<br/>
&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;5&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
&nbsp;&nbsp;2&nbsp;&nbsp;4&nbsp;&nbsp;5&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;5&nbsp;&nbsp;6&nbsp;&nbsp;<br/>
</p>
</td></tr><tr><td class="title">Figure 5</td></tr></table>
    </p><h2>
    But does it actually work?
  </h2><p> 
    Now, it's all well and good describing, implementing and demonstrating our algorithm, but we cannot be certain that it will work for all possible sets of combinations until we get on with the rather more tedious business of proving it. Fortunately for us, it's not too onerous a task.
  </p><p> 
    The key point is in fact addressed by the <tt class="code">is_combination</tt> function. If we can demonstrate that whenever a sequence satisfies this condition, our algorithm generates the lexicographically subsequent combination, and that the sequence representing it also satisfies the condition, then our work is done.
  </p><p> 
    Representing a combination of <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span> from <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span> elements as
  </p>
  <p class="indented">
  x<sub>0</sub> x<sub>1</sub> x<sub>2</sub> ... x<sub><i>i</i></sub> ... x<sub><i>i</i>-1</sub> | x<sub><i>r</i></sub> ... x<sub><i>j</i></sub> ... x<sub><i>n</i>-1</sub>
  </p>
  <p> 
    where the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span>th element is the last that is smaller than any of those in the range <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span> to <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span>-1 and the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">j</span>th is the smallest in that range that is larger than the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span>th.
  </p><p> 
    Now if this is the very last combination, the elements <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span> to <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span>-1 must be smaller than the elements 0 to <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span>-1 and both ranges must be in increasing order. Rotating the sequence so that the latter precede the former therefore returns us to the first combination.
  </p><p> 
    If <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span> is equal to <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span>-1, then since our condition is assumed to be satisfied, <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">j</span> must be equal to <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span>. Applying our algorithm therefore results in the sequence
  </p>
  <p class="indented">
  x<sub>0</sub> x<sub>1</sub> x<sub>2</sub> ... x<sub><i>r</i></sub> | x<sub><i>r</i>+1</sub> ... x<sub><i>n</i>-1</sub> ... x<sub><i>r</i>-1</sub>
  </p>
  <p> 
    This is trivially the lexicographically subsequent combination and must satisfy our condition. Indeed, if it did not, it would imply a contradiction since the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span>-<span style="  font-style: normal; font-weight: normal; vertical-align: baseline">1</span>th element would have to be greater than both the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span>th and the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span>-1<span style="  font-style: normal; font-weight: normal; vertical-align: super">th</span>.
  </p><p> 
    Otherwise, we can be certain that the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span>+1th to the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span>-1th elements must all be larger than the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">j</span>th to the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span>-1th and that both sequences must be sorted in increasing order.
  </p><p> 
    The first rotation we perform must therefore return the sequence to the lexicographically smallest with the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span>th element in its given position. Since this previous combination could not have been the lexicographically last, there must now be at least 1 element larger in the range <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r </span>to <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">n</span>-1 that is larger than those in the range 0 to <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span>-1. Most importantly, the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span>th element must be larger than the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span>-1th. The second rotation therefore results in the lexicographically subsequent combination. Furthermore, it too must satisfy our condition, since the before the second rotation the elements after the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span>th were in increasing order up to some element after the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">r</span>-1th and the elements that follow those, if any, must be smaller than the <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">i</span>th.
  </p><p> 
    QED.
  </p><p> 
    I <span style="  font-style: italic; font-weight: normal; vertical-align: baseline">think</span>.
  </p><p> 
    I'll freely admit that this has been a somewhat handwaving attempt at a proof, and that I wouldn't be terribly surprised to learn that I've missed a corner case or two. Nevertheless, I believe that we can be reasonably confident that our algorithm will correctly enumerate any set of combinations and so we can happily use it to analyse the Countdown numbers game.
  </p><h2>
    Putting it all together
  </h2><p> 
    Note that our formula template evaluation function expects <tt class="code">vector</tt>s of pointers to <tt class="code">rpn_operator</tt> objects and <tt class="code">long</tt> integers, and we shall be using our choice enumeration functions with sequences containing iterators into these in order that their elements exhibit the strict ordering and integer-like behaviour that they require.
  </p><p> 
    We shall therefore need a pair of functions to convert to and from <tt class="code">vector</tt>s of values and <tt class="code">vector</tt>s of iterators, as provided in Listing 13.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class FwdIt&gt;  
    void  
    fill_iterator_vector(FwdIt first, FwdIt last,  
                         std::vector&lt;FwdIt&gt; &amp;vec)  
    {  
      vec.resize(std::distance(first, last));  
      std::vector&lt;FwdIt&gt;::iterator out = vec.begin();  
 
      while(first!=last)  *out++ = first++;  
    }  
 
    template&lt;class FwdIt, class T&gt;  
    void  
    fill_dereference_vector(FwdIt first, FwdIt last,  
                            std::vector&lt;T&gt; &amp;vec)  
    {  
      vec.resize(std::distance(first, last));  
      std::vector&lt;T&gt;::iterator out = vec.begin();  
 
      while(first!=last)  *out++ = **first++;  
    }  
  </pre></td></tr><tr><td class="title">Listing 13</td></tr></table>
<p> 
    To simplify the gathering of various forms of information regarding the numbers game, we shall take a leaf out of the STL's book and build a function template like the standard <tt class="code">for_each</tt> to do the actual iteration and forward on the calculation to a function passed in as an argument.
  </p><p> 
    We shall build this in two parts, the first of which iterates through the combinations of selections of numbers to work with, and the second of which iterates through every possible game that can be played with those numbers. By doing so we shall be able to examine the properties of both every possible game and any specific game.
  </p><p> 
    Illustrated in Listing 14, the first of these functions expects four arguments. The <tt class="code">first</tt> and <tt class="code">last</tt> arguments represent the numbers from which we can choose our arguments, the <tt class="code">args</tt> argument the number that we shall choose and finally the <tt class="code">f</tt> argument the function we wish to apply to the result of every calculation.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class BidIt, class Fun&gt;  
    Fun  
    for_each_numbers_game(BidIt first, BidIt last,  
       size_t args, Fun f)  
    {  
      std::vector&lt;BidIt&gt; number_choice;  
      fill_iterator_vector(first, last,  
         number_choice);  
 
      if(args&gt;std::distance(first, last))  
      {  
        throw std::invalid_argument(&quot;&quot;);  
      }  
 
      std::vector&lt;BidIt&gt;::iterator first_choice  
         = number_choice.begin();  
      std::vector&lt;BidIt&gt;::iterator mid_choice  
         = first_choice+args;  
      std::vector&lt;BidIt&gt;::iterator last_choice  
         = number_choice.end();  
 
      do  
      {  
        f = for_each_numbers_game(first_choice,  
           mid_choice, f);  
      }  
      while(next_combination(first_choice,  
         mid_choice, last_choice));  
 
      return f;  
    }  
  </pre></td></tr><tr><td class="title">Listing 14</td></tr></table>
<p> 
    This function simply iterates through the combinations of <tt class="code">args</tt> from our available numbers, passing the iterator range representing each of them together with the function to be called on to the second version of the function.
  </p><p> 
    The second, significantly longer, function is illustrated in Listing 15. Note that this enumerates the permutations of arguments for each formula template using the iterator range representing the current choice of numbers. Since the <tt class="code">next_permutation</tt> function will eventually return it to lexicographical order, we can be sure that at the end of this function, the full range into which they point will once again represent a valid combination.
  </p><p> 
    The operation of this second function is reasonably straightforward. Firstly, it constructs the full set of formula templates and a collection of the available operators. It then iterates through every formula template, argument choice and operator choice, calculating the result of each function thus generated using temporary buffers into which the argument and operator choices are dereferenced, and calls our statistics gathering function for each valid result.
  </p><table class="sidebartable"><tr><td><pre class="programlisting">
    template&lt;class BidIt, class Fun&gt;  
    Fun  
    for_each_numbers_game(BidIt first_number_choice,  
                          BidIt last_number_choice,  
                          Fun f)  
    {  
      typedef  
         rpn_operator&lt;long&gt; const * operator_type;  
      typedef  
         std::vector&lt;operator_type&gt; operators_type;  
      typedef  
         operators_type::const_iterator  
         operator_iterator;  
 
      const size_t args =  
         std::distance(first_number_choice,  
         last_number_choice);  
 
      operators_type operators(4);  
 
      const rpn_add&lt;long&gt;      add;  
         operators[0] = &amp;add;  
      const rpn_subtract&lt;long&gt; subtract;  
         operators[1] = &amp;subtract;  
      const rpn_multiply&lt;long&gt; multiply;  
         operators[2] = &amp;multiply;  
      const rpn_divide&lt;long&gt;   divide;  
         operators[3] = &amp;divide;  
 
      std::vector&lt;operator_iterator&gt; operator_choice(  
         args-1, operators.begin());  
      const std::set&lt;std::string&gt;    templates(  
         all_templates(args));  
 
      operators_type    used_operators;  
      std::vector&lt;long&gt; used_arguments;  
 
      std::set&lt;std::string&gt;::const_iterator  
         first_template = templates.begin();  
      std::set&lt;std::string&gt;::const_iterator  
         last_template  = templates.end();  
 
      while(first_template!=last_template)  
      {  
        const size_t template_args = (  
           first_template-&gt;size()+1)/2;  
 
        do  
        {  
          fill_dereference_vector(first_number_choice,  
             first_number_choice+template_args,  
             used_arguments);  
 
          do  
          {  
            fill_dereference_vector(  
               operator_choice.begin(),  
               operator_choice.begin()  
                  +template_args-1,  
               used_operators);  
 
            const rpn_result&lt;long&gt; result =  
               rpn_evaluate(*first_template,  
               used_operators, used_arguments);  
            if(result.valid)  f(result.value);  
          }  
          while(next_state(operator_choice.begin(),  
             operator_choice.begin()+template_args-1,  
             operators.end(), operators.begin()));  
        }  
 
        while(next_permutation(first_number_choice,  
           first_number_choice+template_args,  
           last_number_choice));  
          ++first_template;  
      }  
      return f;  
    }  
  </pre></td></tr><tr><td class="title">Listing 15</td></tr></table>
<p> 
    Unfortunately, however, I have spent so much time developing the tools with which we shall perform our analysis that I have run out of time in which we might actually do it.
  </p><p> 
    So we shall have to wait until the next instalment before we can answer the question that we originally posed.
  </p><p> 
    Until then, dear reader, farewell.</p><h2>
    Acknowledgements
  </h2><p> 
    With thank to Keith Garbutt for proof reading this article.
  </p><h2>
    References and further reading
  </h2><p class="bibliomixed"><a name="Countdown"></a> 
    [Countdown]  <a href="http://www.channel4.com/programmes/countdown">http://www.channel4.com/programmes/countdown</a>
    </p><p class="bibliomixed"><a name="Harris08"></a> 
    [Harris08]  Harris, R., The Model Student: A Knotty Problem, Overload 84, 2008.
  </p><p class="footnote"> 1 The upcomingnew C++ standard library will in fact have an <tt class="code">is_sorted</tt> function, but for now we must write our own.
  </p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
