<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>davinci’s notebook &#187; recursion</title>
	<atom:link href="http://stargrads.net/blogs/davinci/tag/recursion/feed/" rel="self" type="application/rss+xml" />
	<link>http://stargrads.net/blogs/davinci</link>
	<description>everything is an experiment</description>
	<lastBuildDate>Mon, 21 Mar 2011 18:31:14 +0000</lastBuildDate>
	<language>fa</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Programming exercise: permutations of a string</title>
		<link>http://stargrads.net/blogs/davinci/2009/10/programming-exercise-permutations-of-a-string/</link>
		<comments>http://stargrads.net/blogs/davinci/2009/10/programming-exercise-permutations-of-a-string/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 17:57:07 +0000</pubDate>
		<dc:creator>davinci</dc:creator>
				<category><![CDATA[programming and technical issues]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[characters]]></category>
		<category><![CDATA[chars]]></category>
		<category><![CDATA[comparison of programming languages]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[permutations]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[programming exercises]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://stargrads.net/blogs/davinci/?p=2318</guid>
		<description><![CDATA[
I do another programming exercise.  The problem this time is to output all the permutations of a string.  I solve this in Scheme, Python, and C++.
]]></description>
			<content:encoded><![CDATA[<p>The problem is to implement a function that outputs all possible <a href="http://en.wikipedia.org/wiki/Permutations">permutations</a> of the characters in a string.  Unlike <a href="http://en.wikipedia.org/wiki/Combinations">combinations</a>, two permutations are considered distinct if they contain the same characters, but in a different order.  Also, for the purposes of this exercise, each occurrence of a repeated character is considered to be a distinct character.  That is, if the input is &#8220;aaa&#8221;, the output should be <em>six</em> repetitions of &#8220;aaa&#8221;.  The permutations may be output in any order.</p>
<p>This exercise, like <a href="http://stargrads.net/blogs/davinci/2009/10/programming-exercise-combinations-of-a-string">the previous one</a> on combinations of a string, is from the book <a href="http://www.amazon.ca/gp/product/047012167X?ie=UTF8&amp;tag=davincisnoteb-20&amp;linkCode=as2&amp;camp=15121&amp;creative=330641&amp;creativeASIN=047012167X"><i>Programming Interviews Exposed</i></a><img src="http://www.assoc-amazon.ca/e/ir?t=davincisnoteb-20&amp;l=as2&amp;o=15&amp;a=047012167X" width="1" height="1" border="0" alt="" style="border:none !important;margin:0px !important" /> by John Mongan and Noah Suojanen<sup><a class='footnote' id='note-2318-1' href='#footnote-2318-ms00pie'>[1]</a></sup>\(\)<span id="more-2318"></span>.<!--adsensestart--></p>
<p>For a string of length \(n\), there are \(n! = n \times (n-1) \times (n-2) \times \cdots \times 1\) permutations.  It&#8217;s fairly easy to see how these arise.  A permutation may begin with any of the \(n\) characters.  Having fixed this first character, the second one may be chosen from the remaining \((n &#8211; 1)\) characters.  And so on.  </p>
<p>The recursive structure of the problem is then obvious.  To compute the permutations of a string of \(n\) characters, first cycle through the characters in the string.  For each character, remove it from the string, compute the permutations of the remaining \((n &#8211; 1)\) characters, and then prepend the previously removed character to each of the resulting permutations.  The base case is the empty string, whose only permutation is itself.</p>
<p>The problem stipulates that each occurrence of a repeated character is to be treated as a distinct character.  Consider the input string &#8220;aba&#8221;.  When dealing with the first &#8220;a&#8221;, the program should remove it, compute the permutations of &#8220;ba&#8221; (which are &#8220;ba&#8221; and &#8220;ab&#8221;), and then prepend &#8220;a&#8221; to those permutations (resulting in &#8220;aba&#8221; and &#8220;aab&#8221;).  However, when dealing with the second occurrence of &#8220;a&#8221;, the program should remove <em>that</em> &#8220;a&#8221;, and compute the permutations of the remaining string, &#8220;ab&#8221;.  This seems to cause some difficulty, as it will mean that our program has to distinguish between the removal of the first &#8220;a&#8221; and the removal of the second &#8220;a&#8221;.  Note, however, that the permutations of &#8220;ab&#8221; are the same as the permutations of &#8220;ba&#8221; (though they might be output in a different order).  A little thought shows that any time we need to remove a character, we can always just remove its first occurrence, since the permutations of the resulting characters will be the same regardless of which occurrence we remove.<!--adsensestop--></p>
<p>To begin with, we need a function to remove the first occurrence of an item from a list.  This is basically an exercise from &#8220;Scheme 101&#8243;:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="scheme" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">define</span> <span style="color: #66cc66;">&#40;</span>remove<span style="color: #66cc66;">-</span>once the<span style="color: #66cc66;">-</span>item the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cond</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null?</span> the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span> '<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
          <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">equal?</span> the<span style="color: #66cc66;">-</span>item <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">car</span> the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
          <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cons</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">car</span> the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>remove<span style="color: #66cc66;">-</span>once the<span style="color: #66cc66;">-</span>item <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>The heart of our solution will be a function called <code>permute</code>.  Given an empty set, it returns a set containing only the empty set.  Otherwise, it calls itself recursively.  The outline looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="scheme" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">define</span> <span style="color: #66cc66;">&#40;</span>permute the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null?</span> the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span> '<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span>...<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>What goes into the <code>(...)</code> above?  We can build this up from the inside out.  We know that there is a recursive call to <code>permute</code>, but with the selected character removed (ignoring for the moment how we select this character):</p>

<div class="wp_syntax"><div class="code"><pre class="scheme" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>permute <span style="color: #66cc66;">&#40;</span>remove<span style="color: #66cc66;">-</span>once the<span style="color: #66cc66;">-</span>selected the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>The selected character should be prepended to each of the resulting permutations:</p>

<div class="wp_syntax"><div class="code"><pre class="scheme" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">map</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span>the<span style="color: #66cc66;">-</span>rest<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cons</span> the<span style="color: #66cc66;">-</span>selected the<span style="color: #66cc66;">-</span>rest<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>permute <span style="color: #66cc66;">&#40;</span>remove<span style="color: #66cc66;">-</span>once the<span style="color: #66cc66;">-</span>selected the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Each of the characters should become the selected character in turn:</p>

<div class="wp_syntax"><div class="code"><pre class="scheme" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">map</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span>the<span style="color: #66cc66;">-</span>selected<span style="color: #66cc66;">&#41;</span> 
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">map</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span>the<span style="color: #66cc66;">-</span>rest<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cons</span> the<span style="color: #66cc66;">-</span>selected the<span style="color: #66cc66;">-</span>rest<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span>permute <span style="color: #66cc66;">&#40;</span>remove<span style="color: #66cc66;">-</span>once the<span style="color: #66cc66;">-</span>selected the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> 
                 the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Running the above code on the input <code>'(a b c d e)</code> will result in something like <code>'( (a-perms) (b-perms) (c-perms) (d-perms) (e-perms) )</code>, where <code>x-perms</code> are permutations beginning with the letter <code>x</code>.  This list of lists of permutations should be flattened by <code>apply</code>ing <code>append</code>.  The rest of the program in Scheme is then:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="scheme" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">define</span> <span style="color: #66cc66;">&#40;</span>permute the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null?</span> the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span> '<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span>apply <span style="color: #b1b100;">append</span>
            <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">map</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span>the<span style="color: #66cc66;">-</span>selected<span style="color: #66cc66;">&#41;</span> 
                         <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">map</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span>the<span style="color: #66cc66;">-</span>rest<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cons</span> the<span style="color: #66cc66;">-</span>selected the<span style="color: #66cc66;">-</span>rest<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
                              <span style="color: #66cc66;">&#40;</span>permute <span style="color: #66cc66;">&#40;</span>remove<span style="color: #66cc66;">-</span>once the<span style="color: #66cc66;">-</span>selected the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> 
                 the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">list</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">define</span> <span style="color: #66cc66;">&#40;</span>permutations the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">string</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">map</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">s</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>apply <span style="color: #b1b100;">string</span> <span style="color: #b1b100;">s</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span>permute <span style="color: #66cc66;">&#40;</span>string<span style="color: #66cc66;">-&amp;</span>gt<span style="color: #808080; font-style: italic;">;list the-string)))</span>
<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">define</span> test<span style="color: #66cc66;">-</span>input <span style="color: #ff0000;">&quot;abcde&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">display</span> <span style="color: #66cc66;">&#40;</span>permutations test<span style="color: #66cc66;">-</span>input<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>Because we need to output \(n!\) permutations (note that the factorial grows faster than the exponential function), it&#8217;s probably a good idea in most cases not to keep the permutations in memory, but rather to print them out as they are generated.  </p>
<p>The following Python program uses logic similar to the above Scheme program, but prints out each permutation right away.  The only difference in the logic is that, because the Python program uses strings and indices into strings, it distinguishes between each occurrence of a repeated character:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> print_permutations<span style="color: black;">&#40;</span>input_string<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> print_permutations_helper<span style="color: black;">&#40;</span>set_of_chars, output_string<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> set_of_chars == <span style="color: #483d8b;">&quot;&quot;</span>:
            <span style="color: #ff7700;font-weight:bold;">print</span> output_string,
        <span style="color: #ff7700;font-weight:bold;">else</span>:
            <span style="color: #ff7700;font-weight:bold;">for</span> index, char <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">enumerate</span><span style="color: black;">&#40;</span>set_of_chars<span style="color: black;">&#41;</span>:
                print_permutations_helper<span style="color: black;">&#40;</span>
                    set_of_chars<span style="color: black;">&#91;</span>:index<span style="color: black;">&#93;</span>+set_of_chars<span style="color: black;">&#91;</span>index+<span style="color: #ff4500;">1</span>:<span style="color: black;">&#93;</span>, 
                    output_string + char<span style="color: black;">&#41;</span>
&nbsp;
    print_permutations_helper<span style="color: black;">&#40;</span>input_string, <span style="color: #483d8b;">&quot;&quot;</span><span style="color: black;">&#41;</span>
&nbsp;
test_input = <span style="color: #483d8b;">&quot;abcde&quot;</span>
print_permutations<span style="color: black;">&#40;</span>test_input<span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>One can manipulate sets, lists, or strings in C++ using <abbr title="Standard Template Library">STL</abbr> classes, but it&#8217;s probably much faster to just use a boolean array to keep track of which letters have been &#8220;removed&#8221; from use.  The following C++ program produces the same output as the above Python program:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include&amp;lt;iostream&amp;gt;</span>
<span style="color: #339900;">#include&amp;lt;string.h&amp;gt;</span>
<span style="color: #0000ff;">using</span> <span style="color: #0000ff;">namespace</span> std<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">void</span> print_permutations_helper<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>input, <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>output, <span style="color: #0000ff;">bool</span> <span style="color: #000040;">*</span>used,
    <span style="color: #0000ff;">int</span> len, <span style="color: #0000ff;">int</span> depth<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #666666;">// At the current depth, cycle through all the letters.</span>
    <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> i <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> len<span style="color: #008080;">;</span> i<span style="color: #000040;">++</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
        <span style="color: #666666;">// If the letter hasn't been used yet, use it.</span>
        <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> <span style="color: #000040;">!</span>used<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            output<span style="color: #008000;">&#91;</span>depth<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> input<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
&nbsp;
            <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> depth <span style="color: #000080;">==</span> len <span style="color: #000040;">-</span> <span style="color: #0000dd;">1</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                <span style="color: #0000dd;">cout</span> <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> output <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> <span style="color: #FF0000;">&quot; &quot;</span><span style="color: #008080;">;</span>
            <span style="color: #008000;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #008000;">&#123;</span>
                used<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff;">true</span><span style="color: #008080;">;</span>
                print_permutations_helper<span style="color: #008000;">&#40;</span>input, output, used, len, depth<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
                used<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">void</span> print_permutations<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>input<span style="color: #008000;">&#41;</span> 
<span style="color: #008000;">&#123;</span>
    <span style="color: #666666;">// Allocate a new character buffer to hold the output, and also</span>
    <span style="color: #666666;">// an array of flags for keeping track of which letters have</span>
    <span style="color: #666666;">// already been used.  (Assume that this always succeeds, or</span>
    <span style="color: #666666;">// that error handling is taken care of elsewhere.)</span>
    <span style="color: #0000ff;">int</span> len <span style="color: #000080;">=</span> <span style="color: #0000dd;">strlen</span><span style="color: #008000;">&#40;</span>input<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>output <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> <span style="color: #0000ff;">char</span><span style="color: #008000;">&#91;</span>len<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
    output<span style="color: #008000;">&#91;</span>len<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #FF0000;">'\ 0'</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">bool</span> <span style="color: #000040;">*</span>used <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> <span style="color: #0000ff;">bool</span><span style="color: #008000;">&#91;</span>len<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// Initialise all the letters as unused.</span>
    <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> i <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> len<span style="color: #008080;">;</span> i<span style="color: #000040;">++</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        used<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #666666;">// Recursively print the permutations. </span>
    print_permutations_helper<span style="color: #008000;">&#40;</span>input, output, used, len, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000dd;">cout</span> <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> endl<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// Free the memory.    </span>
    <span style="color: #0000dd;">delete</span> output<span style="color: #008080;">;</span>
    <span style="color: #0000dd;">delete</span> used<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">char</span> test_input<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;abcde&quot;</span><span style="color: #008080;">;</span>
    print_permutations<span style="color: #008000;">&#40;</span>test_input<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>As with the <a href="http://stargrads.net/blogs/davinci/2009/10/programming-exercise-combinations-of-a-string/">previous exercise on combinations of a string</a>, this exercise also demonstrates how the typical approach to solving a problem will differ depending on whether Scheme or C++ (or some other language) is used.  One can postulate a version of the <a href="http://en.wikipedia.org/wiki/Linguistic_relativity">Sapir-Whorf hypothesis</a> for programming languages, that the language used to tackle a problem has an effect on the way in which it is solved.</p>
<p>&#8211; davinci 11804</p>
<img src="http://stargrads.net/blogs/davinci/?ak_action=api_record_view&id=2318&type=feed" alt="" /><p>Related posts:<ol>
<li><a href='http://stargrads.net/blogs/davinci/2009/10/programming-exercise-combinations-of-a-string/' rel='bookmark' title='Programming exercise: combinations of a string'>Programming exercise: combinations of a string</a></li>
<li><a href='http://stargrads.net/blogs/davinci/2009/09/programming-exercise-hello-world/' rel='bookmark' title='Programming exercise: Hello, world!'>Programming exercise: Hello, world!</a></li>
<li><a href='http://stargrads.net/blogs/davinci/2009/09/programming-exercise-maximum-value-in-integer-array-part-1/' rel='bookmark' title='Programming exercise: maximum value in integer array, part 1'>Programming exercise: maximum value in integer array, part 1</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://stargrads.net/blogs/davinci/2009/10/programming-exercise-permutations-of-a-string/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming exercise: combinations of a string</title>
		<link>http://stargrads.net/blogs/davinci/2009/10/programming-exercise-combinations-of-a-string/</link>
		<comments>http://stargrads.net/blogs/davinci/2009/10/programming-exercise-combinations-of-a-string/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 18:13:27 +0000</pubDate>
		<dc:creator>davinci</dc:creator>
				<category><![CDATA[programming and technical issues]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[characters]]></category>
		<category><![CDATA[chars]]></category>
		<category><![CDATA[combinations]]></category>
		<category><![CDATA[comparison of programming languages]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[permutations]]></category>
		<category><![CDATA[power set]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[programming exercises]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://stargrads.net/blogs/davinci/?p=2290</guid>
		<description><![CDATA[
The problem is to implement a function that outputs all possible combinations of the characters in a string (with length ranging from one to the length of the string). Unlike permutations, two combinations are considered to be the same if they contain the same characters, but in a different order. Another way to define the [...]
]]></description>
			<content:encoded><![CDATA[<p>The problem is to implement a function that outputs all possible <a href="http://en.wikipedia.org/wiki/Combinations">combinations</a> of the characters in a string (with length ranging from one to the length of the string).  Unlike <a href="http://en.wikipedia.org/wiki/Permutations">permutations</a>, two combinations are considered to be the same if they contain the same characters, but in a different order.  Another way to define the problem is to find the <a href="http://en.wikipedia.org/wiki/Power_set">power set</a> of the characters of the string (excluding the empty set).</p>
<p>Like the previous exercise, this one is also from the book <a href="http://www.amazon.ca/gp/product/047012167X?ie=UTF8&amp;tag=davincisnoteb-20&amp;linkCode=as2&amp;camp=15121&amp;creative=330641&amp;creativeASIN=047012167X"><i>Programming Interviews Exposed</i></a><img src="http://www.assoc-amazon.ca/e/ir?t=davincisnoteb-20&amp;l=as2&amp;o=15&amp;a=047012167X" width="1" height="1" border="0" alt="" style="border:none !important;margin:0px !important" /> by John Mongan and Noah Suojanen<sup><a class='footnote' id='note-2290-1' href='#footnote-2290-ms00pie'>[1]</a></sup>\(\)<span id="more-2290"></span>.<!--adsensestart--></p>
<p>To begin with, let&#8217;s consider an example.  What are the combinations of the string &#8220;abcde&#8221;?  Since the ordering of the letters within the combinations don&#8217;t matter, let&#8217;s keep the letters in the same order as in the original string.  Also, for now, let&#8217;s include the empty string as one of the combinations, for simplicity.  Then it&#8217;s clear that there are \(2^{5} = 32\) combinations, since each of the \(5\) letters can be either included or excluded.  (For an input string of length \(n\), there will be \(2^{n}\) combinations, including the empty string.)<!--adsensestop--></p>
<p>The letter &#8220;a&#8221; will be included in half of the combinations, and excluded in the other half.  (Of course, this is also true of each of the other letters.)  In fact, those combinations that exclude &#8220;a&#8221; are just the combinations of the string &#8220;bcde&#8221;, and those that include &#8220;a&#8221; are exactly these same combinations, but prefixed with &#8220;a&#8221;.  This gives an obvious recursive solution to the problem.</p>
<p>Expressed in Scheme, the program looks like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="scheme" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">define</span> <span style="color: #66cc66;">&#40;</span>power<span style="color: #66cc66;">-</span>set the<span style="color: #66cc66;">-</span>set<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null?</span> the<span style="color: #66cc66;">-</span>set<span style="color: #66cc66;">&#41;</span> '<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">&#40;</span>power<span style="color: #66cc66;">-</span>set<span style="color: #66cc66;">-</span>of<span style="color: #66cc66;">-</span>subset <span style="color: #66cc66;">&#40;</span>power<span style="color: #66cc66;">-</span>set <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> the<span style="color: #66cc66;">-</span>set<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> 
               <span style="color: #66cc66;">&#40;</span>prepend<span style="color: #66cc66;">-</span>excluded <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span>subset<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cons</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">car</span> the<span style="color: #66cc66;">-</span>set<span style="color: #66cc66;">&#41;</span> subset<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>
             <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">append</span>
                power<span style="color: #66cc66;">-</span>set<span style="color: #66cc66;">-</span>of<span style="color: #66cc66;">-</span>subset
                <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">map</span> prepend<span style="color: #66cc66;">-</span>excluded power<span style="color: #66cc66;">-</span>set<span style="color: #66cc66;">-</span>of<span style="color: #66cc66;">-</span>subset<span style="color: #66cc66;">&#41;</span> 
             <span style="color: #66cc66;">&#41;</span> 
        <span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">define</span> <span style="color: #66cc66;">&#40;</span>combinations the<span style="color: #66cc66;">-</span><span style="color: #b1b100;">string</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">map</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">s</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>apply <span style="color: #b1b100;">string</span> <span style="color: #b1b100;">s</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> 
         <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> <span style="color: #66cc66;">&#40;</span>power<span style="color: #66cc66;">-</span>set <span style="color: #66cc66;">&#40;</span>string<span style="color: #66cc66;">-&amp;</span>gt<span style="color: #808080; font-style: italic;">;list the-string))) )</span>
<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">define</span> test<span style="color: #66cc66;">-</span>input <span style="color: #ff0000;">&quot;abcde&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">display</span> <span style="color: #66cc66;">&#40;</span>combinations test<span style="color: #66cc66;">-</span>input<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>The <code>combinations</code> function just converts the input string to a list of letters, applies <code>power-set</code> to the list, and converts the result back into a list of strings.  (The empty set is excluded by applying <code>cdr</code>, since it is the first item in the list returned by <code>power-set</code> by design.)</p>
<p>The <code>power-set</code> function is pretty straightforward.  It computes the power set of the subset that excludes the first letter (with a recursive call), then returns a set consisting of the elements of this power set along with these elements prepended with the excluded letter.  The base case is slightly tricky: the power set of the empty set is not the empty set, but a set containing only the empty set.  </p>
<p>(Aside: I wish that the higher-order functions <a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)">map</a> and <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">fold/reduce</a> had better names &#8212; especially &#8220;map&#8221;, a word that is used for just too many things.)</p>
<p>The same program can be written in Python as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> combinations<span style="color: black;">&#40;</span>input_string<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> combinations_helper<span style="color: black;">&#40;</span>set_of_chars<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> set_of_chars == <span style="color: #483d8b;">&quot;&quot;</span>:
            <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: black;">&#93;</span>
        <span style="color: #ff7700;font-weight:bold;">else</span>:
            combinations_of_subset = combinations_helper<span style="color: black;">&#40;</span>set_of_chars<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span>:<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
            combinations_of_subset.<span style="color: black;">extend</span><span style="color: black;">&#40;</span>
                <span style="color: #008000;">map</span><span style="color: black;">&#40;</span> <span style="color: #ff7700;font-weight:bold;">lambda</span> t: set_of_chars<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span> + t, combinations_of_subset<span style="color: black;">&#41;</span>
            <span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> combinations_of_subset
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">return</span> combinations_helper<span style="color: black;">&#40;</span>input_string<span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span>:<span style="color: black;">&#93;</span>
&nbsp;
test_input = <span style="color: #483d8b;">&quot;abcde&quot;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> combinations<span style="color: black;">&#40;</span>test_input<span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>The Python program uses string manipulation operations (string slicing, concatenation) instead of treating the input as a list as the Scheme program does.  The idea, however, is exactly the same.</p>
<p>There are probably more efficient ways to write these programs in these languages.  In particular, the conversions between strings and lists (in Scheme) and the string manipulation operations (in Python) may be expensive.  </p>
<p>What I like about the <em>idea</em> behind the above programs is that the result of the computation for the combinations excluding a character are re-used when computing the combinations including it.  This saves on a lot of recursive calls.</p>
<p>The &#8220;obvious&#8221; solution to the same problem in C++ is the following:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include&amp;lt;iostream&amp;gt;</span>
<span style="color: #339900;">#include&amp;lt;string.h&amp;gt;</span>
<span style="color: #0000ff;">using</span> <span style="color: #0000ff;">namespace</span> std<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">void</span> print_combinations_helper<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>input, <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>output, 
    <span style="color: #0000ff;">int</span> len, <span style="color: #0000ff;">int</span> depth, <span style="color: #0000ff;">int</span> start<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #666666;">// The variable depth holds the recursion depth, or, equivalently, </span>
    <span style="color: #666666;">// the index into the output string of the character that's being</span>
    <span style="color: #666666;">// generated.  The variable start is the index of the first of</span>
    <span style="color: #666666;">// the still available letters.</span>
&nbsp;
    <span style="color: #666666;">// At the current depth, cycle through the still available letters.</span>
    <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> start<span style="color: #008080;">;</span> i <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> len<span style="color: #008080;">;</span> i<span style="color: #000040;">++</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        output<span style="color: #008000;">&#91;</span>depth<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> input<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
        print_combinations_helper<span style="color: #008000;">&#40;</span>input, output, len, depth<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span>, i<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
    output<span style="color: #008000;">&#91;</span>depth<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #FF0000;">'\ 0'</span><span style="color: #008080;">;</span>
    <span style="color: #0000dd;">cout</span> <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> output <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> endl<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">void</span> print_combinations<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>input<span style="color: #008000;">&#41;</span> 
<span style="color: #008000;">&#123;</span>
    <span style="color: #666666;">// Allocate a new character buffer to hold the output.  (Assume </span>
    <span style="color: #666666;">// that this always succeeds, or that error handling is being</span>
    <span style="color: #666666;">// taken care of elsewhere.)</span>
    <span style="color: #0000ff;">int</span> len <span style="color: #000080;">=</span> <span style="color: #0000dd;">strlen</span><span style="color: #008000;">&#40;</span>input<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>output <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> <span style="color: #0000ff;">char</span><span style="color: #008000;">&#91;</span>len<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// Recursively print the combinations, starting with the first</span>
    <span style="color: #666666;">// character.</span>
    print_combinations_helper<span style="color: #008000;">&#40;</span>input, output, len, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// Free the memory for the output buffer.</span>
    <span style="color: #0000dd;">delete</span> output<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> 
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">char</span> test_input<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;abcde&quot;</span><span style="color: #008080;">;</span>
    print_combinations<span style="color: #008000;">&#40;</span>test_input<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>The above program actually also prints out the empty string as one of the combinations, but this can be easily fixed by an <code>if</code> clause, or by relocating the <code>cout</code> statement (lines 18&#8211;19) inside the loop (at line 16, and substituting <code>depth+1</code> for <code>depth</code>).  The reason that I didn&#8217;t write the program that way is because then the combinations would have been output in a very different order compared to the above Scheme/Python programs.  (The way it&#8217;s written now, the output is actually in exactly the reverse order, but that&#8217;s good enough for comparison purposes.)</p>
<p>While the recursive function is called only \(n+1\) times in the Scheme/Python programs (once for each character and once more for the empty set), the C++ program makes a total of \(2^{n}\) calls to the recursive helper function.  On the other hand, while the Scheme/Python programs have to keep \(2^{n}\) items in memory (each of which is \(O(n)\) in size), the C++ program prints each combination as soon as it has been computed and thus uses only \(O(n)\) memory.  </p>
<p>Personally, I prefer the solution used in the Scheme program because I find it conceptually much more elegant.  It would also be preferably if recursive function calls are expensive for some reason.  However, the solution used in the C++ program is better if memory is limited, or if the combinations do not need to be retained in memory after they have been printed.  </p>
<p>Of course, one can write the first program in C++ or the second one in Scheme, but the point is that the two solutions are, in some sense, the more &#8220;natural&#8221; ones for their respective languages.</p>
<p>&#8211; davinci 11803</p>
<img src="http://stargrads.net/blogs/davinci/?ak_action=api_record_view&id=2290&type=feed" alt="" /><p>Related posts:<ol>
<li><a href='http://stargrads.net/blogs/davinci/2009/10/programming-exercise-permutations-of-a-string/' rel='bookmark' title='Programming exercise: permutations of a string'>Programming exercise: permutations of a string</a></li>
<li><a href='http://stargrads.net/blogs/davinci/2009/09/programming-exercise-hello-world/' rel='bookmark' title='Programming exercise: Hello, world!'>Programming exercise: Hello, world!</a></li>
<li><a href='http://stargrads.net/blogs/davinci/2009/09/programming-exercise-maximum-value-in-integer-array-part-1/' rel='bookmark' title='Programming exercise: maximum value in integer array, part 1'>Programming exercise: maximum value in integer array, part 1</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://stargrads.net/blogs/davinci/2009/10/programming-exercise-combinations-of-a-string/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Programming exercise: maximum value in integer array, part 1</title>
		<link>http://stargrads.net/blogs/davinci/2009/09/programming-exercise-maximum-value-in-integer-array-part-1/</link>
		<comments>http://stargrads.net/blogs/davinci/2009/09/programming-exercise-maximum-value-in-integer-array-part-1/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 06:32:20 +0000</pubDate>
		<dc:creator>davinci</dc:creator>
				<category><![CDATA[programming and technical issues]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Common Lisp. Scheme]]></category>
		<category><![CDATA[comparison of programming languages]]></category>
		<category><![CDATA[fold]]></category>
		<category><![CDATA[int]]></category>
		<category><![CDATA[integers]]></category>
		<category><![CDATA[iteration]]></category>
		<category><![CDATA[iterators]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[max]]></category>
		<category><![CDATA[maximum]]></category>
		<category><![CDATA[pointers]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[programming exercises]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[reduce]]></category>
		<category><![CDATA[STL]]></category>
		<category><![CDATA[tail recursion]]></category>

		<guid isPermaLink="false">http://stargrads.net/blogs/davinci/?p=2145</guid>
		<description><![CDATA[
In this post, I write a program to find the maximum value in an integer array in several programming languages.
]]></description>
			<content:encoded><![CDATA[<p>This exercise is just a <em>little</em> bit more substantial than the <a href="http://stargrads.net/blogs/davinci/2009/09/programming-exercise-hello-world/">last one</a> &#8212; but not by very much.  Given an array of \(n\) non-negative integers, find the maximum value in the array, or return \(-1\) if the array is empty.  Obviously, the use of any built-in maximum-finding function is forbidden.  While the problem is almost trivial, it does illustrate how each language works with array or vector data types, as well as how it handles iteration.  </p>
<p>This exercise, like some of the other ones that I will also be going through, is from the book <a href="http://www.amazon.ca/gp/product/047012167X?ie=UTF8&amp;tag=davincisnoteb-20&amp;linkCode=as2&amp;camp=15121&amp;creative=330641&amp;creativeASIN=047012167X"><i>Programming Interviews Exposed</i></a><img src="http://www.assoc-amazon.ca/e/ir?t=davincisnoteb-20&amp;l=as2&amp;o=15&amp;a=047012167X" width="1" height="1" border="0" alt="" style="border:none !important;margin:0px !important" /> by John Mongan and Noah Suojanen<sup><a class='footnote' id='note-2145-1' href='#footnote-2145-ms00pie'>[1]</a></sup><span id="more-2145"></span>.<!--adsensestart--></p>
<p>For consistency, let&#8217;s assume that the array for which we&#8217;re trying to find the maximum value is \(\{6, 3, 8, 7, 1, 2, 0, 9, 4, 5\}\).  Let&#8217;s also assume for simplicity that \(n\) is given, that we don&#8217;t have to check for errors (the input is a list of non-negative integers as promised), and that we can write \(-1\) for the error return code.  (In production code, we would of course define a named constant such as <code>ARRAY_EMPTY_ERROR</code>, or use some other form of error-handling such as exceptions.)<!--adsensestop--></p>
<p>Let&#8217;s begin with C.  The code is pretty straightforward, except that I had to remind myself to declare the loop counter \(i\) outside of the loop.  (Declaring it in the loop initialisation is not allowed in standards prior to C99.)  It&#8217;s also a lot harder to code on paper than it is on a keyboard (my handwriting is terrible, due to atrophy).  Here&#8217;s the program in C:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include&amp;lt;stdio.h&amp;gt;</span>
&nbsp;
<span style="color: #993333;">int</span> arraymax<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> array<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> currentMax<span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> n<span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;=</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
    currentMax <span style="color: #339933;">=</span> array<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span> i <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> n<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> currentMax <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            currentMax <span style="color: #339933;">=</span> array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> currentMax<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>argv<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> testinput<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> <span style="color: #0000dd;">6</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">3</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">7</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">9</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">5</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;max = %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> arraymax<span style="color: #009900;">&#40;</span>testinput<span style="color: #339933;">,</span> <span style="color: #0000dd;">10</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>I could, of course, have written the exact same program in C++, but to make things interesting, I&#8217;m going to use the <abbr title="Standard Template Library">STL</abbr> <code>vector</code> class:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include&amp;lt;iostream&amp;gt;</span>
<span style="color: #339900;">#include&amp;lt;vector&amp;gt;</span>
&nbsp;
<span style="color: #0000ff;">using</span> <span style="color: #0000ff;">namespace</span> std<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">int</span> vectormax<span style="color: #008000;">&#40;</span>vector<span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #0000ff;">int</span><span style="color: #000040;">&amp;</span>gt<span style="color: #008080;">;</span> vec<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">int</span> currentMax<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> vec.<span style="color: #007788;">empty</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">return</span> <span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    currentMax <span style="color: #000080;">=</span> vec<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> i <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> vec.<span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> i<span style="color: #000040;">++</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> vec<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000040;">&amp;</span>gt<span style="color: #008080;">;</span> currentMax <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            currentMax <span style="color: #000080;">=</span> vec<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">return</span> currentMax<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">int</span> values<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000dd;">6</span>, <span style="color: #0000dd;">3</span>, <span style="color: #0000dd;">8</span>, <span style="color: #0000dd;">7</span>, <span style="color: #0000dd;">1</span>, <span style="color: #0000dd;">2</span>, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">9</span>, <span style="color: #0000dd;">4</span>, <span style="color: #0000dd;">5</span> <span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
    vector<span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #0000ff;">int</span><span style="color: #000040;">&amp;</span>gt<span style="color: #008080;">;</span> testinput<span style="color: #008000;">&#40;</span>values, values<span style="color: #000040;">+</span><span style="color: #0000dd;">10</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000dd;">cout</span> <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> <span style="color: #FF0000;">&quot;max = &quot;</span> <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> vectormax<span style="color: #008000;">&#40;</span>testinput<span style="color: #008000;">&#41;</span> <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> endl<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>The only tricky part was I had to look up how to initialise a vector without looping through the values and using <code>push_back</code>.  The code above calls the iteration constructor, using the trick that an <code>int</code> array in C++ is just a pointer to its first element, and the fact that pointers are iterators.</p>
<p>Apparently, in the proposed <a href="http://en.wikipedia.org/wiki/C%2B%2B0x">c++0x</a> standard, it will be possible to initialise a vector using a static array like <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists">this</a>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>26
27
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;">    <span style="color: #666666;">// Use the initialiser list constructor.</span>
    vector<span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #0000ff;">int</span><span style="color: #000040;">&amp;</span>gt<span style="color: #008080;">;</span> testinput <span style="color: #000080;">=</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000dd;">6</span>, <span style="color: #0000dd;">3</span>, <span style="color: #0000dd;">8</span>, <span style="color: #0000dd;">7</span>, <span style="color: #0000dd;">1</span>, <span style="color: #0000dd;">2</span>, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">9</span>, <span style="color: #0000dd;">4</span>, <span style="color: #0000dd;">5</span> <span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>In the program above, I&#8217;ve used indices as if the vector were just a regular array.  The preferred way to access vector elements in C++ is to use iterators.  This means replacing lines 14&#8211;15 with the following:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>14
15
16
17
18
19
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;">    vector<span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #0000ff;">int</span><span style="color: #000040;">&amp;</span>gt<span style="color: #008080;">;::</span><span style="color: #007788;">iterator</span> vi <span style="color: #000080;">=</span> vec.<span style="color: #007788;">begin</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span> currentMax <span style="color: #000080;">=</span> <span style="color: #000040;">*</span>vi<span style="color: #000040;">++</span><span style="color: #008080;">;</span> vi <span style="color: #000040;">!</span><span style="color: #000080;">=</span> vec.<span style="color: #007788;">end</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> vi<span style="color: #000040;">++</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> <span style="color: #000040;">*</span>vi <span style="color: #000040;">&amp;</span>gt<span style="color: #008080;">;</span> currentMax <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            currentMax <span style="color: #000080;">=</span> <span style="color: #000040;">*</span>vi<span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>I had to think a little bit about the loop initialisation condition, <code>currentMax = *vi++</code>.  The iterator is <a href="http://stackoverflow.com/questions/859770/-on-a-dereferenced-pointer-in-c">dereferenced before it is incremented</a>, which is the desired behaviour.</p>
<p>There are a number of differences between the C# and C/C++ programs.  First, there&#8217;s the <code>foreach</code> statement, which makes for nicer-looking loops.  Then there&#8217;s the fact that the array type specifier <code>[]</code> must appear before the variable name, rather than after.  Here&#8217;s the code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ArrayMax <span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">int</span> arraymax<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> array<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span><span style="color: #008000;">&#40;</span> array<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #6666cc; font-weight: bold;">int</span> currentMax <span style="color: #008000;">=</span> array<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">foreach</span><span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> value <span style="color: #0600FF; font-weight: bold;">in</span> array <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">if</span><span style="color: #008000;">&#40;</span> value <span style="color: #008000;">&amp;</span>gt<span style="color: #008000;">;</span> currentMax <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                currentMax <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">return</span> currentMax<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> testinput <span style="color: #008000;">=</span> <span style="color: #008000;">&#123;</span> <span style="color: #FF0000;">6</span>, <span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">8</span>, <span style="color: #FF0000;">7</span>, <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">2</span>, <span style="color: #FF0000;">0</span>, <span style="color: #FF0000;">9</span>, <span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">5</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
        Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;max = {0}<span style="color: #008080; font-weight: bold;">\n</span>&quot;</span>, arraymax<span style="color: #008000;">&#40;</span>testinput<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>I had to remember to make the <code>arraymax</code> function static so that it can be called without instantiating the <code>ArrayMax</code> class.</p>
<p>The Java code is essentially identical to the C# code, <em>mutatis mutandis</em>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ArrayMax <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">int</span> arraymax<span style="color: #009900;">&#40;</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> array <span style="color: #009900;">&#41;</span> 
    <span style="color: #009900;">&#123;</span> 
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> array.<span style="color: #006633;">length</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000066; font-weight: bold;">int</span> currentMax <span style="color: #339933;">=</span> array<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span> <span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> array.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> currentMax <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                currentMax <span style="color: #339933;">=</span> array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> currentMax<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span> <span style="color: #003399;">String</span> args<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">int</span> testinput<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> <span style="color: #cc66cc;">6</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">8</span>, <span style="color: #cc66cc;">7</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">9</span>, <span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">5</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;max = &quot;</span> <span style="color: #339933;">+</span> arraymax<span style="color: #009900;">&#40;</span>testinput<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Beginning in J2SE v1.5/5.0<sup><a class='footnote' id='note-2145-2' href='#footnote-2145-java_version_history'>[2]</a></sup>, Java introduced a &#8220;for each&#8221; loop, and so lines 9&#8211;13 above should be replaced with this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>9
10
11
12
13
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">        <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span> <span style="color: #000066; font-weight: bold;">int</span> value <span style="color: #339933;">:</span> array <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> value <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> currentMax <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                currentMax <span style="color: #339933;">=</span> value<span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Now that we&#8217;ve gotten the standard general-purpose imperative and object-oriented (i.e., <a href="http://en.wikipedia.org/wiki/C-like_syntax">&#8220;C-like&#8221;</a>) languages out of the way, it&#8217;s time for some fun(ctional programming).</p>
<p>Of course, Lisp and Scheme already have a <code>max</code> function defined to get the maximum value in a list of integers, but as mentioned before, its use is forbidden to us.  Nevertheless, the solution to the given problem in these languages is still very simple.  How can we express the function that returns the maximum value of a list of integers?  One way to do it is to express it as the <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">folding (or reducing)</a> of the list with a function that compares <em>two</em> integer values and returns the larger one.  Expressed in Lisp, this function is:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> larger <span style="color: #66cc66;">&#40;</span>x y<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; x y) x y))</span></pre></td></tr></table></div>

<p>The rest of the Lisp program easily follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">defun</span> list-<span style="color: #b1b100;">max</span> <span style="color: #66cc66;">&#40;</span>intlist<span style="color: #66cc66;">&#41;</span> 
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null</span> intlist<span style="color: #66cc66;">&#41;</span> -<span style="color: #cc66cc;">1</span>
          <span style="color: #66cc66;">&#40;</span>reduce #'larger intlist<span style="color: #66cc66;">&#41;</span>
     <span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">setq</span> intlist '<span style="color: #66cc66;">&#40;</span> <span style="color: #cc66cc;">6</span> <span style="color: #cc66cc;">3</span> <span style="color: #cc66cc;">8</span> <span style="color: #cc66cc;">7</span> <span style="color: #cc66cc;">1</span> <span style="color: #cc66cc;">2</span> <span style="color: #cc66cc;">0</span> <span style="color: #cc66cc;">9</span> <span style="color: #cc66cc;">4</span> <span style="color: #cc66cc;">5</span> <span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span>format t <span style="color: #ff0000;">&quot;max = ~D&quot;</span> <span style="color: #66cc66;">&#40;</span>list-<span style="color: #b1b100;">max</span> intlist<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>(Incidentally, it&#8217;s because of things like <code>#'</code>, which is called the sharp-quote, that some people don&#8217;t like Lisp.)</p>
<p>The Scheme program is essentially identical:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="scheme" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">define</span> <span style="color: #66cc66;">&#40;</span>listmax intlist<span style="color: #66cc66;">&#41;</span> 
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">null?</span> intlist<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">-</span><span style="color: #cc66cc;">1</span>
          <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">&#40;</span>larger <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">lambda</span> <span style="color: #66cc66;">&#40;</span>x y<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&amp;</span>gt<span style="color: #808080; font-style: italic;">; x y) x y)) ) )</span>
            <span style="color: #66cc66;">&#40;</span>fold larger <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">car</span> intlist<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cdr</span> intlist<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">define</span> intlist '<span style="color: #66cc66;">&#40;</span> <span style="color: #cc66cc;">6</span> <span style="color: #cc66cc;">3</span> <span style="color: #cc66cc;">8</span> <span style="color: #cc66cc;">7</span> <span style="color: #cc66cc;">1</span> <span style="color: #cc66cc;">2</span> <span style="color: #cc66cc;">0</span> <span style="color: #cc66cc;">9</span> <span style="color: #cc66cc;">4</span> <span style="color: #cc66cc;">5</span> <span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">display</span> <span style="color: #ff0000;">&quot;max = &quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">display</span> <span style="color: #66cc66;">&#40;</span>listmax intlist<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>The Python code is also very similar:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> listmax<span style="color: black;">&#40;</span>intlist<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">if</span> intlist == <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> -<span style="color: #ff4500;">1</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>: 
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">reduce</span><span style="color: black;">&#40;</span> <span style="color: #ff7700;font-weight:bold;">lambda</span> x, y : x <span style="color: #ff7700;font-weight:bold;">if</span> x <span style="color: #66cc66;">&amp;</span>gt<span style="color: #66cc66;">;</span> y <span style="color: #ff7700;font-weight:bold;">else</span> y, intlist<span style="color: black;">&#41;</span>
&nbsp;
testinput = <span style="color: black;">&#91;</span> <span style="color: #ff4500;">6</span>, <span style="color: #ff4500;">3</span>, <span style="color: #ff4500;">8</span>, <span style="color: #ff4500;">7</span>, <span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">9</span>, <span style="color: #ff4500;">4</span>, <span style="color: #ff4500;">5</span> <span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;max =&quot;</span>, listmax<span style="color: black;">&#40;</span>testinput<span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>I really like the Python code.  It combines the simplicity of the fold idea used in Lisp/Scheme with the clarity of an ALGOL-like syntax.</p>
<p>I should mention that another way of expressing the function that returns the maximum value in a list of integers is as a recursive function that returns the only element in a list of size one, and returns the larger of the first element and the result of the function applied to the rest of the list for a list of size two or more.  However, unless the program is written using <a href="http://en.wikipedia.org/wiki/Tail_recursion">tail recursion</a>, and one is using a compiler that optimises tail-recursive calls, the stack will grow with the size of the list, so this solution is not as good as the one using fold/reduce.</p>
<p>I was originally also going to write the program in the remaining languages listed in the <a href="http://stargrads.net/blogs/davinci/2009/09/programming-exercise-hello-world/">previous post</a>, but I&#8217;ve spent far too much time already on this exercise, and I&#8217;d like to move on to some more difficult ones.  And besides, the program in the other functional languages will be very similar except for syntax, and there&#8217;s almost no point in coding a &#8220;maximum integer value in an array&#8221; function in the mathematical languages, since an optimised version of such a function is already built into them.  I may return to this exercise later with additional languages, so I&#8217;ll append &#8220;part 1&#8243; to the title of this post.</p>
<p>&#8211; davinci 11796</p>
<img src="http://stargrads.net/blogs/davinci/?ak_action=api_record_view&id=2145&type=feed" alt="" /><p>Related posts:<ol>
<li><a href='http://stargrads.net/blogs/davinci/2009/10/programming-exercise-permutations-of-a-string/' rel='bookmark' title='Programming exercise: permutations of a string'>Programming exercise: permutations of a string</a></li>
<li><a href='http://stargrads.net/blogs/davinci/2009/10/programming-exercise-combinations-of-a-string/' rel='bookmark' title='Programming exercise: combinations of a string'>Programming exercise: combinations of a string</a></li>
<li><a href='http://stargrads.net/blogs/davinci/2009/09/programming-exercise-hello-world/' rel='bookmark' title='Programming exercise: Hello, world!'>Programming exercise: Hello, world!</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://stargrads.net/blogs/davinci/2009/09/programming-exercise-maximum-value-in-integer-array-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

