<?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; programming and technical issues</title>
	<atom:link href="http://stargrads.net/blogs/davinci/category/programming-and-technical-issues/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>Old Help:Setup wiki</title>
		<link>http://stargrads.net/blogs/davinci/2010/10/old-helpsetup-wiki/</link>
		<comments>http://stargrads.net/blogs/davinci/2010/10/old-helpsetup-wiki/#comments</comments>
		<pubDate>Sun, 24 Oct 2010 02:25:10 +0000</pubDate>
		<dc:creator>davinci</dc:creator>
				<category><![CDATA[★grads.net]]></category>
		<category><![CDATA[programming and technical issues]]></category>
		<category><![CDATA[help]]></category>
		<category><![CDATA[MediaWiki]]></category>
		<category><![CDATA[setup]]></category>
		<category><![CDATA[wiki]]></category>

		<guid isPermaLink="false">http://stargrads.net/blogs/davinci/?p=2962</guid>
		<description><![CDATA[
I've copied the contents of the old Help:Setup wiki into this post, because I'm getting rid of the MediaWiki installation.
]]></description>
			<content:encoded><![CDATA[<p>The content of this post used to live at <a href="http://stargrads.net/wiki/Help:Setup">http://stargrads.net/wiki/Help:Setup</a>, and described how I had set up the software for this web site.  I am archiving the contents of that page here for the reasons described below.  It probably won&#8217;t interest anyone except for nerds<span id="more-2962"></span>.  </p>
<p><!--adsensestart-->I had <a href="http://stargrads.net/blogs/davinci/2008/10/why-my-own-website/">originally intended</a>  to use <a href="http://www.mediawiki.org/">MediaWiki</a> to help me get out my writer&#8217;s block by using it to <a href="http://stargrads.net/blogs/davinci/2008/10/writing-my-phd-research-proposal-live/">write my Ph.D. proposal live and online</a>.  However, since I have <a href="http://stargrads.net/blogs/davinci/2009/06/my-depression-in-waterloo-part-13-dropping-out/">dropped out</a> of the Ph.D. program, I haven&#8217;t really gone back to look at it.  It turns out that MediaWiki is a magnet for spam, and I simply don&#8217;t have the time to revert edits when some bot inserts spam links into the wikis.  </p>
<p>Another problem is that I had used WordPress<sup>&mu;</sup> to give myself the flexibility of creating more than one blog on this web site.  Since then, WordPress<sup>&mu;</sup> has been merged into WordPress, so much of what is below is no longer relevant or necessary.</p>
<hr />
<p>This is a record of everything I did to set up the software for <a href="http://stargrads.net/">stargrads.net</a>, in case I need to install everything again, or to fix something that broke after an upgrade.</p>
<p>For help on how to <em>use</em> the software, see <a href="http://en.wikipedia.org/wiki/Help:Contents">Help:Contents</a>.</p>
<h1>Blogs (<a href="http://mu.wordpress.org/">WordPress<sup>&mu;</sup></a>)</h1>
<p>I am using the <a href="http://getk2.com/">K2</a> theme for WordPress.  This theme is designed so that the template files do not usually need to be edited.  Most of my customisation is done through a stylesheet and using K2&#8242;s provided hooks.  However, I did make three modifications to the template code in &#8220;theloop.php&#8221;:</p>
<ul>
<li>I moved the permalink from the post title to just after it, and had it displayed as &#8220;[permalink]&#8220;.
</li>
<li>I added a link to a post&#8217;s comments after each post.
</li>
<li>I changed the code for the &#8220;Continue reading&#8221; link so that it expands/collapses the post using AJAX.
</li>
</ul>
<p>The stargrads.net banner and the loader for jsMath are included through &#8220;functions.php&#8221; by adding hooks for &#8220;template_body_top&#8221;.</p>
<p>One slight change to &#8220;header.php&#8221;: on line 52, I changed the string &#8221; at &#8221; to &#8221; @ &#8221; (this makes post titles show up as &#8220;post title @ davinci&#8217;s notebook&#8221; on the individual post pages).</p>
<p>Another change to &#8220;header.php&#8221;: I added links in the header to the RSS and Atom feeds of the comments.</p>
<h2>The Continue Reading Link</h2>
<p>The &#8220;Continue reading&#8221; link (which is normally displayed when WordPress encounters the &lt;!&#8211;more&#8211;&gt; tag) was changed so that it would display ellipses, followed by a new paragraph, before the link to the full post. This behaviour is overridden by the Ajaxified Expand Post NOW Plugin, for which see below.</p>
<p>The original code in &#8220;theloop.php&#8221; was:</p>
<p><code>&lt;?php the_content(sprintf(__('Continue reading \'%s\&lt;em&gt;, 'k2_domain'), the_title(&lt;/em&gt;, '', false))); ?&gt;</code></p>
<p>This was changed to:</p>
<p><code>&lt;?php the_content(sprintf(__(&#039;&#8230;&lt;/p&gt;
&lt;p&gt;&amp;raquo; [Continue reading &lt;span class=&quot;small-entry-title&quot;&gt;%s&lt;/span&gt;]', 'k2_domain'), the_title(&lt;em&gt;, &lt;/em&gt;, false))); ?&gt;</code></p>
<h2>The Ajaxified Expand Post NOW Plugin</h2>
<p>In addition to the above, I activated the <a href="http://blog.chweng.idv.tw/wordpress/ajaxified-expand-post-now/">Ajaxified Expand Post NOW</a> plugin.  Note that this essentially overwrites the above changes.  I made a number of customisations and modifications to the plugin:</p>
<ul>
<li><code>\$aepnLoadingMsg = '&#8230; &amp;raquo; [Fetching data &lt;img src=&quot;http://stargrads.net/blogs/wp-content/themes/k2/images/spinner.gif&quot; align=&quot;absmiddle&quot; /&gt;]';</code>,
</li>
<li><code>\$postLess = 'Collapse post';</code>, and
</li>
<li><code>\$postMore = 'Expand post';</code>.
</li>
</ul>
<p>I also replaced the line <code>\$content=preg_replace(...)</code> and the following line with:<br />
<code>\$content=preg_replace('/&lt;a&gt;(.*)/', (\$postLinkPrefix.'&lt;span&gt;&#8230; &amp;raquo; [&lt;a href=&quot;'.get_permalink().'#more-\$2&quot;&gt;'.\$postMore.'&lt;/a&gt;]&lt;/span&gt;&lt;span class=&quot;viewBox&quot;&gt;&lt;/span&gt;&lt;span&gt;&amp;laquo; [&lt;a href=&quot;'.get_permalink().'#more-\$2&quot;&gt;'.\$postLess.'&lt;/a&gt;]&lt;/span&gt;'.\$postLinkPostfix.' [&lt;a href=&quot;'.get_permalink().'&quot;&gt;Permalink&lt;/a&gt;]'), \$content);</code></p>
<p>In the &#8220;getPost&#8221; function, I added the lines:</p>
<ul>
<li><code>global $post;</code>
</li>
<li><code>\$post-&gt;ID = $id;</code>
</li>
</ul>
<p>These were required to allow the footnotes plugin to create its anchors properly.</p>
<p>In the same function, I replaced the lines beginning <code>\$content=explode(...)</code> with:</p>
<p><code>\$content=explode(\$token,apply_filters('the_content',\$post_content),2); if (count(\$content)==2) { echo \$content[1]; }</code></p>
<p>This was needed so that plugins can apply filters to both parts of a text separated by the &lt;!&#8211;more&#8211;&gt; tag.</p>
<p>Finally, in the line <code>gE('viewBox-'+postID).style.display = 'block';</code>, I changed <code>block</code> to <code>inline</code>.</p>
<p>The above changes allow the post to be collapsed in the middle of a paragraph (or of a sentence, even).</p>
<p>There&#8217;s a slight bug in the integration of the The Ajaxified Expand Post NOW Plugin with jsMath.  Currently, mathematical formulas after the &lt;!&#8211;more&#8211;&gt; tag do not get processed.  To get around this, in posts where formulas appear after the &lt;!&#8211;more&#8211;&gt; tag but not before, an empty equation needs to be inserted before the tag to force jsMath to load.  Furthermore, the plugin code needs to be edited to add these lines to the end of the &#8220;fetchDone&#8221; function:</p>
<p><code>jsMath.ConvertTeX('viewBox-'+postID);&lt;br /&gt;
jsMath.Process('viewBox-'+postID); </code></p>
<p>Come to think of it, there&#8217;s probably nothing I can do about this.  The reason is that if there are any error messages (jsMath is missing fonts, and so on), they have to be displayed at the top of the site.  There&#8217;s no way this can happen if jsMath is loaded dynamically through Ajax when a post is expanded.</p>
<h2>OpenID</h2>
<p><s>The OpenID plugin has a bug which prevents trackbacks and pingbacks from working.  See <a href="http://wordpress.org/support/topic/263012">here</a> for the fix.</s>  This is fixed in the latest version.</p>
<h2>WP-Syntax (GeSHi)</h2>
<p>The <a href="http://wordpress.org/extend/plugins/wp-syntax/">WP-Syntax</a> plugin needs to escape special characters.  See <a href="http://blog.felho.hu/escaping-problem-with-wp-syntax-wordpress-plugin.html">here</a> for the fix.</p>
<p>Move geshi to the common subdirectory, since it&#8217;s also used by MediaWiki.  Change the line <code>include_once(&quot;geshi/geshi.php&quot;)</code> to <code>include_once(getenv(&quot;DOCUMENT_ROOT&quot;) . &quot;/common/geshi/geshi.php&quot;)</code>.</p>
<h2>WP-reCAPTCHA</h2>
<p>After setting the tab index in the options, the &#8220;comments.php&#8221; file has to be edited to change the tab index of the &#8220;Submit&#8221; button, so that the reCAPTCHA appears between the comment and the submit button.  </p>
<h2>Subscribe to Comments</h2>
<p>The Subscribe to Comments plug-in likewise needs to be edited so that its checkbox appears just before the reCAPTCHA.  The &#8220;comments.php&#8221; file needs to be edited to allow users to subscribe to comments even if they haven&#8217;t commented, by adding a call to <code>show_subscription_checkbox()</code>.  I&#8217;ve also edited the plugin to insert some tab index information.</p>
<p>The plugin needs to be edited in a number of places to make it compatible with WordPress<sup>&mu;</sup>, especially its concept of <a href="http://codex.wordpress.org/Roles_and_Capabilities">roles and capabilities</a>.  In particular, references to <code>current_user_can('manage_options')</code> should be changed to <code>current_user_can('publish_posts')</code> (to enable editors and blog posters who are not administrators to manage subscriptions).  Also, SQL queries to <code>SELECT</code> comments need to have <code>AND comment_type = ''</code> added, so that pingbacks and trackbacks are ignored.</p>
<p>A minor cosmetic change: the &#8220;Return to the page you were viewing&#8221; link was changed so that it goes to the &#8220;#respond&#8221; anchor on that page.</p>
<h2>Yet Another Related Posts Plugin</h2>
<p>There&#8217;s a bug in version 3.0.13 of YARPP which adds slashes in front of quotation marks for several options on the options page.  See <a href="http://wordpress.org/support/topic/315560">here</a>.</p>
<h2>Sociable</h2>
<p>The Sociable, YARPP, and AEPN plugins interact with each other in a bad way.  Sociable and YARPP work together in single posts.  However, when they are used together with AEPN, inside an expanded post (say, on the front page) the Sociable plugin interferes with the YARPP plugin so that the latter displays the <em>wrong</em> list of related posts.</p>
<p>I don&#8217;t know how to fix this, except to turn off the option to &#8220;Automatically display related posts&#8221;, and then adding a call to <code>related_posts()</code> to the K2 hook <code>template_entry_foot</code>.</p>
<h2>K2 Rolling Archives</h2>
<p>In the &#8220;themes/k2/js/k2.functions.js&#8221; file, change the &#8220;smartPosition&#8221; function to the following:</p>
<p>/* Fix the position of an element when it is about to be scrolled off-screen */<br />
function smartPosition(obj) {</p>
<pre>
       if ( jQuery.browser.msie &amp;&amp; parseInt(jQuery.browser.version, 10) = jQuery(obj).offset().top) {
                       jQuery('body').addClass('smartposition');
                       rollingarchives.style.left = '' + (345 - document.documentElement.scrollLeft) + 'px';
               } else {
                       jQuery('body').removeClass('smartposition');
                       rollingarchives.style.left = '0px';
               }
       });
</pre>
<p>};</p>
<p>The value of 345 was determined experimentally.  There&#8217;s probably a better (cleaner) way to do this!</p>
<h2>Kses hack</h2>
<p>The tags &#8220;ref&#8221;, &#8220;references&#8221;, and &#8220;wikindx&#8221; had to be allowed through a so-called &#8220;kses hack&#8221;, so that footnotes and citations would work.</p>
<p>I had to edit the &#8220;wp-includes/kses.php&#8221; file to include &#8220;market&#8221; as an allowed protocol, to allow links to Android Market.</p>
<h2>Incompatible plugins</h2>
<p>Some plugins written for WordPress may be incompatible with WordPress<sup>&mu;</sup>.  In some cases, it may be impossible to update the plugin&#8217;s options.  A hack to get around this is to comment out any &#8220;check_admin_referer&#8221; lines in the plugin, change the options, and then uncomment those lines.</p>
<h1>Wiki (<a href="http://www.mediawiki.org">MediaWiki</a>)</h1>
<p>Major changes to the skin, obviously.  The original settings for the sidebar were:</p>
<ul>
<li>SEARCH
</li>
<li>navigation
<ul>
<li>mainpage|mainpage-description
</li>
<li>portal-url|portal
</li>
<li>currentevents-url|currentevents
</li>
<li>recentchanges-url|recentchanges
</li>
<li>randompage-url|randompage
</li>
<li>helppage|help
</li>
</ul>
</li>
<li>TOOLBOX
</li>
<li>LANGUAGES
</li>
</ul>
<p>Note that to edit the sidebar, just edit the special wiki page <a href="http://stargrads.net/wiki/MediaWiki:Sidebar">MediaWiki:Sidebar</a>.</p>
<p>The CSS for the site is found at <a href="http://stargrads.net/wiki/MediaWiki:Common.css">MediaWiki:Common.css</a>.</p>
<h1>Forums (<a href="http://bbpress.org/">bbPress</a>)</h1>
<p>In the &#8220;header.php&#8221; file, add the line &#8220;<code></code>&#8221; to load jsMath.</p>
<h1>Bibliography (<a href="http://wikindx.sourceforge.net/"><span style="font-variant: small-caps">Wikindx</span></a>)</h1>
<p>To write the name of the software, use &#8220;<code>&lt;span style=&quot;font-variant: small-caps;&quot;&gt;Wikindx&lt;/span&gt;</code>&#8220;, which shows up as<br />
<span style="font-variant: small-caps">Wikindx</span>.</p>
<h1>Calendar (<a href="http://www.k5n.us/webcalendar.php">WebCalendar</a>)</h1>
<p>These pertain to WebCalendar 1.20.</p>
<p>There&#8217;s a bug that prevents WebCalendar from display pages with untimed events if using PHP 5.2.8 and up.  Typically the web server returns a zero-sized reply.  See <a href="http://sourceforge.net/forum/forum.php?thread_id=2725065&amp;forum_id=11587">this post</a> for the fix.</p>
<p>There&#8217;s another bug that prevents user/group selection pages from displaying with the error &#8220;Program Error: No Form Specified&#8221;.  See <a href="http://sourceforge.net/forum/message.php?msg_id=5801794">here</a> for the fix.</p>
<h1>Equations (<a href="http://www.math.union.edu/~dpvc/jsMath/">jsMath</a>)</h1>
<p>The following code was inserted into the header files of the templates for this web site:<br />
<code>&lt;script type=&quot;text/javascript&quot; src=&quot;http://&lt;em&gt;path.to&lt;/em&gt;/jsMath/easy/load.js&quot;&gt;&lt;/script&gt;</code></p>
<p>To get equations to display correctly in {{sc|W|IKINDX}}, curly brackets have to be escaped correctly.  Replace each &#8220;{&#8221; with &#8220;{{}&#8221; and each &#8220;}&#8221; with &#8220;{}}&#8221;.</p>
<p>When updating, don&#8217;t forget to save the customised macros and the installed fonts.</p>
<p>See above for a slight bug with the Ajaxified Expand Post NOW Plugin in regards to jsMath.</p>
<h1>Web Analytics (<a href="http://piwik.org/">piwik</a>)</h1>
<p>When upgrading piwik, pay special attention to the config and tmp subdirectories, especially their permission settings.</p>
<p>There are plugins available for <a href="http://piwik.org/blog/2008/06/new-plugin-wordpress-piwik-integration/">WordPress</a> and <a href="http://piwik.org/blog/2008/06/new-plugin-mediawiki-piwik-integration/">MediaWiki</a>, but for now, the piwik code is just going into the template. <!--adsensestop--></p>
<p>&#8211; davinci</p>
<img src="http://stargrads.net/blogs/davinci/?ak_action=api_record_view&id=2962&type=feed" alt="" /><p>Related posts:<ol>
<li><a href='http://stargrads.net/blogs/davinci/2009/09/wikindx-macro-plug-in-for-wordpress/' rel='bookmark' title='Wikindx macro plug-in for WordPress'>Wikindx macro plug-in for WordPress</a></li>
<li><a href='http://stargrads.net/blogs/davinci/2009/08/using-the-ajaxified-expand-post-now-plugin-with-rob-millers-footnotes-plugin/' rel='bookmark' title='Using the Ajaxified Expand Post Now plug-in with Rob Miller&#8217;s Footnotes plug-in'>Using the Ajaxified Expand Post Now plug-in with Rob Miller&#8217;s Footnotes plug-in</a></li>
<li><a href='http://stargrads.net/blogs/davinci/2009/06/using-jsmath-with-wordpress-bbpress-and-wikindx/' rel='bookmark' title='Using jsMath with WordPress, bbPress, and Wikindx'>Using jsMath with WordPress, bbPress, and Wikindx</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://stargrads.net/blogs/davinci/2010/10/old-helpsetup-wiki/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming exercise: interweaved strings</title>
		<link>http://stargrads.net/blogs/davinci/2009/11/programming-exercise-interweaved-strings/</link>
		<comments>http://stargrads.net/blogs/davinci/2009/11/programming-exercise-interweaved-strings/#comments</comments>
		<pubDate>Sun, 22 Nov 2009 01:45:33 +0000</pubDate>
		<dc:creator>davinci</dc:creator>
				<category><![CDATA[programming and technical issues]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[dynamic programming]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[programming exercises]]></category>

		<guid isPermaLink="false">http://stargrads.net/blogs/davinci/?p=2574</guid>
		<description><![CDATA[
Another programming exercise.  The problem is to determine whether one string can be formed by interweaving two others.
]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t quite remember where I saw this problem, but I&#8217;m sure it&#8217;s appeared in a number of places.  Given two strings \(s\) and \(t\), determine whether a string \(u\) is formed by interweaving \(s\) and \(t\).  That is, determine whether \(u\) can be formed by taking the first few characters of (say) \(s\), followed by the first few characters of \(t\), then the next few characters of \(s\), and so on.  For example, the string &#8220;abccdcxey&#8221; can be formed by interweaving &#8220;abcde&#8221; with &#8220;ccxy&#8221;<span id="more-2574"></span>.<!--adsensestart--></p>
<p>I took way too long thinking about how to set up the problem than I should have.  In the end, I decided to quickly write up a solution that is easy to code, even if it may not be optimal.  The solution uses an \((m+1) \times (n+1)\) table, with indices starting from \(0\), where the \((i,j)\) entry is a boolean value indicating whether it&#8217;s possible to form the \((i+j)\)-character prefix of \(u\) from the first \(i\) characters of \(s\) and the first \(j\) characters of \(t\).<!--adsensestop--></p>
<p>Let \(m\) and \(n\) be the lengths of \(s\) and \(t\), respectively.  Assume that \(u\) is of length \(m+n\).  (This can be easily checked and handled at the beginning.) The function that determines whether \(u\) is formed by interweaving \(s\) and \(t\) is 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
17
18
19
20
21
</pre></td><td class="code"><pre class="c" style="font-family:monospace;">bool interweave<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>s<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> m<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>t<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> n<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>u<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    bool <span style="color: #339933;">**</span>table <span style="color: #339933;">=</span> new_table<span style="color: #009900;">&#40;</span>m<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>    
    table<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><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: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> row <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> row <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> m<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> row<span style="color: #339933;">++</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> col <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> col <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> col<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> table<span style="color: #009900;">&#91;</span>row<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>col<span style="color: #009900;">&#93;</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> row <span style="color: #339933;">!=</span> m <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    table<span style="color: #009900;">&#91;</span>row<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>col<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>s<span style="color: #009900;">&#91;</span>row<span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> u<span style="color: #009900;">&#91;</span>row<span style="color: #339933;">+</span>col<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> col <span style="color: #339933;">!=</span> n <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    table<span style="color: #009900;">&#91;</span>row<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>col<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>t<span style="color: #009900;">&#91;</span>col<span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> u<span style="color: #009900;">&#91;</span>row<span style="color: #339933;">+</span>col<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    bool result <span style="color: #339933;">=</span> table<span style="color: #009900;">&#91;</span>m<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>n<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    delete table<span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> result<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>When programming on the whiteboard, it&#8217;s important not to get bogged down in details.  In the above, I&#8217;ve assumed the existence of a function <code>new_table(rows,cols)</code> which returns a two-dimensional array of <code>bool</code>s, of the requested number of rows and columns, with all entries initialised to <code>false</code>.  This is simple enough to implement that I hope the interviewer won&#8217;t actually ask me to write it out during the interview, but in case I have to do so, here it is:</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="c" style="font-family:monospace;">bool <span style="color: #339933;">**</span>new_table<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> rows<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> cols<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    bool <span style="color: #339933;">**</span>table <span style="color: #339933;">=</span> new bool<span style="color: #339933;">*</span><span style="color: #009900;">&#91;</span>rows<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> rows<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        table<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> new bool<span style="color: #009900;">&#91;</span>cols<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> j <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> cols<span style="color: #339933;">;</span> j<span style="color: #339933;">++</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            table<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">return</span> table<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The algorithm runs in time \(O(m \times n)\) and also takes that much space.  I wasn&#8217;t really satisfied with this solution because it doesn&#8217;t make use of the fact that the same prefix of \(u\) can be formed by interweaving prefixes of \(s\) and \(t\) in different ways.  For example, &#8220;abcc&#8221; can be formed by interweaving &#8220;abc&#8221; and &#8220;c&#8221; in two different ways.  Now, the above algorithm doesn&#8217;t perform redundant calculations, but only because we&#8217;re sweeping the table row-by-row in an orderly fashion.  </p>
<p>One can, of course, contrive values for which most of the table actually needs to be visited, but for most values of \(s\) and \(t\), if one or more paths from the upper left corner to the lower right corner of the table exists, the only entries of the table that need to be visited are likely to be very close to these paths.  It makes sense therefore to keep track of which entries in the table are actually necessary to visit.  </p>
<p>The following code is closer to the algorithm I have in mind:</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
</pre></td><td class="code"><pre class="c" style="font-family:monospace;">bool interweave<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>s<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> m<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>t<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> n<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>u<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    queue q <span style="color: #339933;">=</span> new queue<span style="color: #009900;">&#40;</span>m<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>n<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    q.<span style="color: #202020;">enqueue</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    bool result <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span>q.<span style="color: #202020;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #993333;">int</span> row<span style="color: #339933;">,</span> col<span style="color: #339933;">;</span>
        q.<span style="color: #202020;">dequeue</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span>row<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span>col<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span> row <span style="color: #339933;">==</span> m <span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #009900;">&#40;</span> col <span style="color: #339933;">==</span> n <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            result <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span> row <span style="color: #339933;">!=</span> m <span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #009900;">&#40;</span> s<span style="color: #009900;">&#91;</span>row<span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> u<span style="color: #009900;">&#91;</span>row<span style="color: #339933;">+</span>col<span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #339933;">!</span>q.<span style="color: #202020;">marked</span><span style="color: #009900;">&#40;</span>row<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>col<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            q.<span style="color: #202020;">enqueue</span><span style="color: #009900;">&#40;</span>row<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>col<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span> col <span style="color: #339933;">!=</span> n <span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #009900;">&#40;</span>t<span style="color: #009900;">&#91;</span>col<span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> u<span style="color: #009900;">&#91;</span>row<span style="color: #339933;">+</span>col<span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #339933;">!</span>q.<span style="color: #202020;">marked</span><span style="color: #009900;">&#40;</span>row<span style="color: #339933;">,</span>col<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            q.<span style="color: #202020;">enqueue</span><span style="color: #009900;">&#40;</span>row<span style="color: #339933;">,</span>col<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    delete queue<span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> result<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In the above, I&#8217;ve assumed the existence of a <code>queue</code> class that allows me to enqueue and dequeue pairs of integers consisting of a row and a column.  A row-column pair is enqueued only if it corresponds to a prefix of \(u\) that can be formed by interweaving a prefix of \(s\) and a prefix of \(t\).  Furthermore, the <code>queue</code> class also keeps track of whether a pair has <em>ever</em> been enqueued.  The <code>marked</code> function returns true if that&#8217;s the case, and false otherwise.  It can do this either using a two-dimensional array, as before, or it can use a fancier structure that trades off time for savings in space.  </p>
<p>If a two-dimensional array is used, the algorithm will still require \(O(m \times n)\) time just to initialise it.  However, the main loop in the <code>interweave</code> function will be \(O(m+n)\) for inputs for which there is little overlap or repetition in the input strings.</p>
<p>&#8211; davinci 11848</p>
<img src="http://stargrads.net/blogs/davinci/?ak_action=api_record_view&id=2574&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/11/programming-exercise-interweaved-strings/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Programming exercise: red-white-blue sorting</title>
		<link>http://stargrads.net/blogs/davinci/2009/11/programming-exercise-red-white-blue-sorting/</link>
		<comments>http://stargrads.net/blogs/davinci/2009/11/programming-exercise-red-white-blue-sorting/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 20:52:38 +0000</pubDate>
		<dc:creator>davinci</dc:creator>
				<category><![CDATA[programming and technical issues]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[programming exercises]]></category>
		<category><![CDATA[quicksort]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://stargrads.net/blogs/davinci/?p=2549</guid>
		<description><![CDATA[
I&#8217;ve been practising coding on the whiteboard for job interviews. This is very different than coding in front of a computer which has a keyboard, a monitor, and a nice editing program that allows you to correct your mistakes and type repetitive text very quickly. I&#8217;m trying to keep my programs simple and short, and [...]
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been practising coding on the whiteboard for job interviews.  This is very different than coding in front of a computer which has a keyboard, a monitor, and a nice editing program that allows you to correct your mistakes and type repetitive text very quickly.  I&#8217;m trying to keep my programs simple and short, and writing in a C-like pseudocode.</p>
<p>This exercise comes from Skiena&#8217;s <a href="http://www.amazon.ca/gp/product/1848000693?ie=UTF8&amp;tag=davincisnoteb-20&amp;linkCode=as2&amp;camp=15121&amp;creative=330641&amp;creativeASIN=1848000693"><i>The Algorithm Design Manual</i></a><img src="http://www.assoc-amazon.ca/e/ir?t=davincisnoteb-20&amp;l=as2&amp;o=15&amp;a=1848000693" width="1" height="1" border="0" alt="" style="border:none !important;margin:0px !important" /><sup><a class='footnote' id='note-2549-1' href='#footnote-2549-skiena08'>[1]</a></sup>\(\)<span id="more-2549"></span>.<!--adsensestart--></p>
<p>You are given an array \(A\) of \(n\) elements, each of which is one of <em>red</em>, <em>white</em>, or <em>blue</em>.  The only permitted operations on \(A\) are to examine an item at position \(i\) using <code>Examine(i)</code>, and to swap two items at positions \(i\) and \(j\) using <code>Swap(i,j)</code>.  The problem is to sort the elements as efficiently as possible, such that the elements are in the order <em>red</em>, followed by <em>white</em>, then finally <em>blue</em>.</p>
<p>The trick to coding on a whiteboard is to first draw some simple visual examples, and use them to talk your interviewer (or yourself) through how the algorithm is supposed to work, before writing down any actual code.  It&#8217;s very important that you have the algorithm you want to code before you start coding, because any editing other than very minor changes is basically impossible on a whiteboard.</p>
<p>The first thing to notice is that we can do better than the standard \(O(n\log n)\) sorting algorithms, since the number of different values for the elements is a small constant.  My first thought was to make one pass of the array to count the number of red, white, and blue elements, one more pass to put all the red elements in front, and a final pass to put the white elements before the blue ones.  While this algorithm is linear time, which is asymptotically the best you can do, with a little thought and a little bookkeeping, it&#8217;s possible to do everything in just one pass of the array.<!--adsensestop--></p>
<p>The idea is as follows.  Keep two &#8220;pointers&#8221;, say \(r\) and \(b\), which begin at the front and back respectively, and which keep track of the places where the next red and blue elements should go.  Now sweep the array from front to back.  </p>
<p>If the current position has a blue element, swap it to position \(b\).  Now, we decrement \(b\), but we don&#8217;t advance the position of the sweep yet, because we might have just swapped in another blue element.  This rule ensures that there are no blue elements behind us (i.e., towards the front of the array).  </p>
<p>Dealing with a red element is a <em>bit</em> trickier, since both the \(r\) pointer and the sweep&#8217;s position are advancing.  If we&#8217;re at the same position as the \(r\) pointer, there&#8217;s a contiguous block of red elements behind us, and we can simply increment \(r\) and move on to the next position.  If we&#8217;re ahead of the \(r\) pointer, we can swap the red element to that position, and increment \(r\).  Note that we can only ever swap in a white element, since we&#8217;ve guaranteed that there are no blue elements behind us, and \(r\) is always beyond the continguous block of known red elements at the front.</p>
<p>Finally, if the current position has a white element, we can just skip over it.  If it&#8217;s in the wrong position, it&#8217;ll be dealt with later when we encounter the red element it needs to be swapped with.</p>
<p>The loop terminates when our sweep hits the contiguous block of blue elements at the back of \(A\), i.e., when \(pos &gt; b\).  For simplicity, we assume that \(n \geq 1\) (which we can always check for before we begin).</p>
<p>This is the algorithm I came up with on the whiteboard:</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="c" style="font-family:monospace;"><span style="color: #993333;">int</span> r<span style="color: #339933;">,</span> b<span style="color: #339933;">,</span> pos<span style="color: #339933;">;</span>
&nbsp;
r <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> b <span style="color: #339933;">=</span> n<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>Examine<span style="color: #009900;">&#40;</span>r<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #ff0000;">'R'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> r<span style="color: #339933;">++;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>Examine<span style="color: #009900;">&#40;</span>b<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #ff0000;">'B'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> b<span style="color: #339933;">--;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
pos <span style="color: #339933;">=</span> r<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> pos <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;=</span> b <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">char</span> val <span style="color: #339933;">=</span> Examine<span style="color: #009900;">&#40;</span>pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> val <span style="color: #339933;">==</span> <span style="color: #ff0000;">'B'</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Swap<span style="color: #009900;">&#40;</span>b<span style="color: #339933;">,</span> pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        b<span style="color: #339933;">--;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> val <span style="color: #339933;">==</span> <span style="color: #ff0000;">'R'</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> r <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> pos <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            Swap<span style="color: #009900;">&#40;</span>r<span style="color: #339933;">,</span> pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
            pos<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
        r<span style="color: #339933;">++;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> val <span style="color: #339933;">==</span> <span style="color: #ff0000;">'W'</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        pos<span style="color: #339933;">++;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>I&#8217;ve assumed that <code>Examine(i)</code> returns one of <code>'R'</code>, <code>'W'</code>, or <code>'B'</code>.  The \(pos\) variable keeps track of the position as I sweep the array from front to back.  The two initial loops skip over any red elements at the front and any blue elements at the back of the array (these are not strictly necessary, but make things a bit faster in some cases).  Each element is examined exactly once, for a total run time of \(n\), making this the most efficient algorithm possible.  </p>
<p>&#8211; davinci 11847</p>
<img src="http://stargrads.net/blogs/davinci/?ak_action=api_record_view&id=2549&type=feed" alt="" /><p>Related posts:<ol>
<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>
<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/11/programming-exercise-red-white-blue-sorting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Persian Soft Keyboard and Applications for Android</title>
		<link>http://stargrads.net/blogs/davinci/2009/11/persian-soft-keyboard-and-applications-for-android/</link>
		<comments>http://stargrads.net/blogs/davinci/2009/11/persian-soft-keyboard-and-applications-for-android/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 06:34:28 +0000</pubDate>
		<dc:creator>davinci</dc:creator>
				<category><![CDATA[languages and linguistics]]></category>
		<category><![CDATA[programming and technical issues]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[complex text layout]]></category>
		<category><![CDATA[Dream]]></category>
		<category><![CDATA[glyph-shaping]]></category>
		<category><![CDATA[HTC]]></category>
		<category><![CDATA[input method]]></category>
		<category><![CDATA[Persian]]></category>
		<category><![CDATA[soft keyboard]]></category>
		<category><![CDATA[virtual keyboard]]></category>

		<guid isPermaLink="false">http://stargrads.net/blogs/davinci/?p=2534</guid>
		<description><![CDATA[
In this post, I discuss a new application I wrote for my Android smart phone, a Persian Soft Keyboard.
]]></description>
			<content:encoded><![CDATA[<p><b>Update (July 25, 2010)</b>: Please read this before posting a comment, sending me an e-mail, or giving the software a rating on the Android Market.  Also, note that the remarks below pertain to Android 2.2 and below, and may become obsolete in the future.                                                                                                                                                                      </p>
<p>About the <b>keyboard</b>:</p>
<ul>
<li>The app is a <em>keyboard</em>.  Please do <em>not</em> say that &#8220;it doesn&#8217;t work&#8221; because &#8220;I see only squares&#8221;.  <b>A keyboard does not help you to render fonts or shape glyphs.</b>  This software is meant only for people who can <em>already</em> display Persian on their phones, but have no means of input.  With that being said, I understand that many people who are looking for an input method for Persian are <em>also</em> looking for a way to display it.  Just don&#8217;t confuse the two functionalities.  (For information on how to display Persian, read on to the next section below.)</li>
<li>There is nothing sinister about the warning that the software may see sensitive information such as passwords and credit card numbers.  <b>It can see anything you type when it is the active keyboard &#8212; <em>and so can every other soft keyboard</em>.</b>  It does <em>not</em> do anything with this information except to use it to guess what you&#8217;re typing.  If you don&#8217;t want your password or credit card number to be read by the app, just switch to the default Android keyboard when you need to type something secret.  (Unless, of course, your password is actually in Persian.)</li>
<li>On most devices, you have to enable an input method after it&#8217;s installed by going into Settings, and <b>to switch input methods you hold the trackball or long-tap with your finger in a text input field</b>.  These depend on the operating system, and are not things that I can change.</li>
</ul>
<p>On <b>installing a font</b> and <b>rooting your phone</b>:</p>
<ul>
<li>To display Persian on Android, <b>it is <em>not sufficient</em> just to install a font.</b>  You also need to get the system to join the glyphs and to display them in right-to-left order.</li>
<li>To install a font, <b>you will need to root your phone</b>.  Instructions can be found by using a <a href="http://www.google.com">search engine</a>.</li>
<li>If you are unable to follow the instructions yourself, or cannot find someone who is <em>physically present</em> to take you through the steps, it is unlikely that anyone can help you online.  It&#8217;s not a trivial task in most cases, and nobody wants to be responsible for accidentally bricking your phone.  I will try to help, but please understand that your request is non-trivial.  Furthermore, please see the remark above about it not being sufficient just to install a font.  Even after a font is installed, there is still a lot of work to do to display Persian on Android.  If you do not understand how to root a phone yourself, you will very likely not understand how to go through the rest of the process either.</li>
</ul>
<p>About <b>displaying Persian</b> on your phone:</p>
<ul>
<li><a href="http://farsitel.com/">FarsiTel</a> has just announced a Persianised version of Android.  If you have a newer Android (2.1 and up) and want a completely Persian ROM, start your investigations there.  Note that this solution includes a keyboard also (and it is a different one from mine).</li>
<li>You can also try <a href="http://ardoid.com/">Arabic Android</a> for displaying Persian.  Yes, it&#8217;s designed for Arabic, but it works for Persian also.  You may have to pay to obtain right-to-left functionality.  Look for the &#8220;Arabic Android&#8221; app in the market once you have the appropriate image from the site installed.</li>
<li>There is an app on the Android Market called &#8220;<a href="http://www.bohlool.net/android-apps/persian-browser">Persian Browser</a>&#8221; that will enable font-shaping in the web browser only.  If your browser displays Perso-Arabic glyphs but don&#8217;t join them or display them right-to-left, you can download this app to fix the problem.</li>
<li>To use these ROMs/apps, you may need to root your phone and/or install fonts.  See the section above.</li>
<li><b>Disclaimer: I am not involved with these projects, and (to my knowledge) neither is my employer.</b></li>
</ul>
<p>And, finally, I cannot make any comments about the state of official support for Persian on Android due to the terms of my employment.  This is my personal web site, and is unaffiliated with my employer.  Anything I write here about Persian support on Android reflects my personal opinion only.</p>
<p>The original post (from Nov. 16, 2009) follows.</p>
<hr />
<p>I recently got a new smart phone &#8212; an Android-powered HTC Dream.  As I wrote in a <a href="http://stargrads.net/blogs/davinci/2009/09/mock-up-of-a-yudit-like-mobile-application/">previous post</a>, one of the first applications that I always look for is a multilingual dictionary, or at the very least a way to enter input in languages other than English<span id="more-2534"></span>.<!--adsensestart--></p>
<p>It took me almost no time to write up a Persian Soft Keyboard, which I have put on the <a href="http://www.android.com/market/">Android Market</a>.  (If you&#8217;re viewing this page on an Android device, you can download the application directly by clicking <a href="net.stargrads.android.inputmethod.persiansoftkeyboard">this link</a>.)</p>
<p>Because Android is open source, it was remarkably easy to learn how to use the <a href="http://developer.android.com/sdk/"><abbr title="software development kit">SDK</abbr></a>.  Unfortunately, despite this, there are a number of design decisions which make it difficult to enable Android devices for the Persian language (or many other languages).  For one thing, it is impossible for the average user to install a new font, and the default fonts that ship with most Android phones don&#8217;t cover character sets outside of the Latin-based alphabets.  For another, built-in support for complex text layout is very incomplete, and that includes the bidirectional text display and glyph-shaping which are essential for properly rendering Persian text.  </p>
<p>I can understand the decision to leave these features out, since space is limited on most Android devices.  However, this means that users who use languages other than English end up having to go to a lot of trouble to get these languages to work, such as downloading versions of applications capable of handling their specific language.  It would have been much simpler if the base Android system had been packaged with a font that covered the Unicode characters for the most common languages in the world and applications that were aware of how to lay out their writing systems.</p>
<p>As things are, even with a Persian font installed, most applications still don&#8217;t display Persian text properly because of directionality and glyph-shaping problems.  I&#8217;ve included an option for the Persian Soft Keyboard to output Unicode presentation forms, i.e., glyphs which are already shaped and joined.  Even though this option does not comply with the Unicode standard, it allows readable Persian text to be entered into and sent through the default SMS application, for example.  (Whether the recipient will be able to read the message at the other end is another issue.)<!--adsensestop--></p>
<p>Currently, I&#8217;m bundling a simple note pad and a translator application with the Persian Soft Keyboard package.  At the moment, the available note pad applications can&#8217;t handle right-to-left text, and the available translators don&#8217;t do glyph-shaping correctly.  I hope that more Android software authors make their applications aware of languages other than English, because I don&#8217;t really want to support or maintain applications which are redundant.</p>
<p>&#8211; davinci 11843</p>
<img src="http://stargrads.net/blogs/davinci/?ak_action=api_record_view&id=2534&type=feed" alt="" /><p>Related posts:<ol>
<li><a href='http://stargrads.net/blogs/davinci/2009/05/the-causes-of-my-depression-part-17-my-frivolous-web-site-and-how-i-learned-persian/' rel='bookmark' title='The causes of my depression, part 17: my &#8220;frivolous&#8221; web site and how I learned Persian'>The causes of my depression, part 17: my &#8220;frivolous&#8221; web site and how I learned Persian</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://stargrads.net/blogs/davinci/2009/11/persian-soft-keyboard-and-applications-for-android/feed/</wfw:commentRss>
		<slash:comments>100</slash:comments>
		</item>
		<item>
		<title>Lists of programming exercises</title>
		<link>http://stargrads.net/blogs/davinci/2009/10/lists-of-programming-exercises/</link>
		<comments>http://stargrads.net/blogs/davinci/2009/10/lists-of-programming-exercises/#comments</comments>
		<pubDate>Mon, 19 Oct 2009 03:34:52 +0000</pubDate>
		<dc:creator>davinci</dc:creator>
				<category><![CDATA[programming and technical issues]]></category>
		<category><![CDATA[programming exercises]]></category>

		<guid isPermaLink="false">http://stargrads.net/blogs/davinci/?p=2507</guid>
		<description><![CDATA[
A list of web sites with programming exercises, and also a few relevant books.
]]></description>
			<content:encoded><![CDATA[<p><!--noadsense-->I&#8217;ve collected a number of web sites with lists of programming exercises, which I&#8217;m going through for practice.</p>
<p>In no particular order, these are<span id="more-2507"></span>:</p>
<ul>
<li><a href="http://projecteuler.net/">Project Euler</a> (a spin-off of <a href="http://mathschallenge.net/">MathsChallenge.net</a>)
</li>
<li><a href="http://www.spoj.pl/problems/classical/">Sphere Online Judge</a>
</li>
<li><a href="http://www.topcoder.com/tc">TopCoder</a>
</li>
<li><a href="http://codekata.pragprog.com/2007/01/code_kata_backg.html">Code Kata</a>
</li>
<li><a href="http://icpc.baylor.edu/past/default.htm">The ACM International Collegiate Programming Contest &#8212; Past Problems</a>
</li>
<li><a href="http://acm.uva.es/contest/">Valladolid Online Judge</a>
</li>
</ul>
<p>The following are language-specific:</p>
<ul>
<li><a href="http://www.cprogramming.com/challenge.html">C/C++ Programming Challenge Problems</a>
</li>
<li><a href="http://cplus.about.com/od/programmingchallenges/Programming_Challenges.htm">About.com C/C++/C# Programming Challenges</a>
</li>
<li><a href="http://www.pythonchallenge.com/">Python Challenge</a>
</li>
<li><a href="http://rubyquiz.com/">Ruby Quiz</a>
</li>
</ul>
<p>And here are some books which may be relevant:</p>
<ul>
<li><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">Programming Interviews Exposed, by John Mongan, Noah Suojanen, and Eric Giguère</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" />
</li>
<li><a href="http://www.amazon.ca/gp/product/0201657880?ie=UTF8&amp;tag=davincisnoteb-20&amp;linkCode=as2&amp;camp=15121&amp;creative=330641&amp;creativeASIN=0201657880">Programming Pearls, by Jon Bentley</a><img src="http://www.assoc-amazon.ca/e/ir?t=davincisnoteb-20&amp;l=as2&amp;o=15&amp;a=0201657880" width="1" height="1" border="0" alt="" style="border:none !important;margin:0px !important" />
</li>
<li><a href="http://www.amazon.ca/gp/product/0470121688?ie=UTF8&amp;tag=davincisnoteb-20&amp;linkCode=as2&amp;camp=15121&amp;creative=330641&amp;creativeASIN=0470121688">Puzzles for Programmers and Pros, by Dennis Shasha </a><img src="http://www.assoc-amazon.ca/e/ir?t=davincisnoteb-20&amp;l=as2&amp;o=15&amp;a=0470121688" width="1" height="1" border="0" alt="" style="border:none !important;margin:0px !important" />
</li>
<li><a href="http://www.amazon.ca/gp/product/0387001638?ie=UTF8&amp;tag=davincisnoteb-20&amp;linkCode=as2&amp;camp=15121&amp;creative=330641&amp;creativeASIN=0387001638">Programming Challenges, by Steven S. Skiena </a><img src="http://www.assoc-amazon.ca/e/ir?t=davincisnoteb-20&amp;l=as2&amp;o=15&amp;a=0387001638" width="1" height="1" border="0" alt="" style="border:none !important;margin:0px !important" />
</li>
<li><a href="http://www.amazon.ca/gp/product/1848000693?ie=UTF8&amp;tag=davincisnoteb-20&amp;linkCode=as2&amp;camp=15121&amp;creative=330641&amp;creativeASIN=1848000693">The Algorithm Design Manual, by Steven S. Skiena</a><img src="http://www.assoc-amazon.ca/e/ir?t=davincisnoteb-20&amp;l=as2&amp;o=15&amp;a=1848000693" width="1" height="1" border="0" alt="" style="border:none !important;margin:0px !important" />
</li>
</ul>
<p>Since the exercises are judged, I probably won&#8217;t be posting solutions here.  My accounts on Project Euler, Sphere Online Judge, and TopCoder are all &#8220;dlyongemallo&#8221;.</p>
<p>&#8211; davinci 11814</p>
<img src="http://stargrads.net/blogs/davinci/?ak_action=api_record_view&id=2507&type=feed" alt="" /><p>Related posts:<ol>
<li><a href='http://stargrads.net/blogs/davinci/2009/09/programming-exercises-and-comparison-of-programming-languages/' rel='bookmark' title='Programming exercises and comparison of programming languages'>Programming exercises and comparison of programming languages</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://stargrads.net/blogs/davinci/2009/10/lists-of-programming-exercises/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>
		<item>
		<title>Programming exercise: Hello, world!</title>
		<link>http://stargrads.net/blogs/davinci/2009/09/programming-exercise-hello-world/</link>
		<comments>http://stargrads.net/blogs/davinci/2009/09/programming-exercise-hello-world/#comments</comments>
		<pubDate>Sun, 27 Sep 2009 16:22:50 +0000</pubDate>
		<dc:creator>davinci</dc:creator>
				<category><![CDATA[programming and technical issues]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[comparison of programming languages]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[Maple]]></category>
		<category><![CDATA[Mathematica]]></category>
		<category><![CDATA[Matlab]]></category>
		<category><![CDATA[ML]]></category>
		<category><![CDATA[Octave]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[programming exercises]]></category>
		<category><![CDATA[Prolog]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Scheme]]></category>

		<guid isPermaLink="false">http://stargrads.net/blogs/davinci/?p=2177</guid>
		<description><![CDATA[
The obligatory "Hello, world!" program in a variety of languages.
]]></description>
			<content:encoded><![CDATA[<p><!--adsensestart-->As a preliminary exercise to jog my memory, here is the obligatory &#8220;Hello, world!&#8221; program in a variety of languages.  On the one hand, the programs do nothing except output a string, and so don&#8217;t illustrate very much about the respective languages.  On the other hand, the simplicity of the task does illustrate the difference between languages that allow you to begin coding right away versus those that require a considerable amount of setting up (importing libraries, declaring classes, etc.) before you even have a functioning program<!--adsensestop--><span id="more-2177"></span>.</p>
<p>To be consistent, the programs will all output &#8220;Hello, world!&#8221;, followed by the newline character.</p>
<p>First up, of course, is C:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include&amp;lt;stdio.h&amp;gt;</span>
<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: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Hello, world!<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></pre></td></tr></table></div>

<p>C++ is similar, except that <code>iostream</code> is used instead of <code>stdio</code>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</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: #0000ff;">using</span> <span style="color: #0000ff;">namespace</span> std<span style="color: #008080;">;</span>
<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: #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;Hello, world!&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> endl<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Java requires that a class be defined:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> HelloWorld <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;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</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;Hello, world!<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>C# looks like a mixture of C and Java:</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="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>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> HelloWorld <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;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Hello, world!<span style="color: #008080; font-weight: bold;">\n</span>&quot;</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>In an interview situation, I doubt that I would use C# or Java, unless explicitly asked.  It wastes too much time to set up the classes.  Also, when writing code on a whiteboard or on paper, the shallower your indentation level, the better, because you don&#8217;t want to use up space unnecessarily, and you&#8217;ll have to move things around when you&#8217;re asked to add to or modify the code.</p>
<p>In Perl, this program is just one line:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="perl" style="font-family:monospace;"><span style="color: #000066;">print</span> <span style="color: #ff0000;">&quot;Hello, world!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The program is almost the same in Python:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Hello, world!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span></pre></td></tr></table></div>

<p>The only difference is that the statement in Python does not need to end in a semicolon (although it is legal, it is superfluous).  In Python 3 and above, print is a function:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">print</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Hello, world!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>In Ruby:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Hello, world!<span style="color:#000099;">\n</span>&quot;</span></pre></td></tr></table></div>

<p>In Common Lisp:</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>format t <span style="color: #ff0000;">&quot;Hello, world!~%&quot;</span><span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>I&#8217;ll probably not be able to remember the format operators on the spot (e.g., &#8220;~%&#8221; instead of the much more common &#8220;\n&#8221; for &#8220;newline&#8221;).</p>
<p>In Scheme:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="scheme" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">display</span> <span style="color: #ff0000;">&quot;Hello, world!&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">newline</span><span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>In Prolog:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="prolog" style="font-family:monospace;"><span style="color: #990000;">write</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Hello, world!'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">nl</span><span style="color: #339933;">.</span></pre></td></tr></table></div>

<p>In Haskell:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="haskell" style="font-family:monospace;"><span style="font-weight: bold;">putStrLn</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;Hello, world!&quot;</span><span style="color: green;">&#41;</span></pre></td></tr></table></div>

<p>Note that <code>putStrLn</code> already appends a newline character.</p>
<p>In Standard ML:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="sml" style="font-family:monospace;">print<span style="color: #a52a2a;">&#40;</span><span style="color: #3cb371;">&quot;Hello, world!\n&quot;</span><span style="color: #a52a2a;">&#41;</span><span style="color: #a52a2a;">;</span></pre></td></tr></table></div>

<p>In the Linux shell (e.g., bash):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'Hello, world!'</span></pre></td></tr></table></div>

<p>The <code>echo</code> command outputs a trailing newline.</p>
<p>And now, for some mathematical languages.  In Matlab:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">fprintf</span><span style="color: #080;">&#40;</span>&quot;Hello, world!\n&quot;<span style="color: #080;">&#41;</span>;</pre></td></tr></table></div>

<p>In Octave (the above Matlab program will also work):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="octave" style="font-family:monospace;">printf<span style="color: #080;">&#40;</span>&quot;Hello, world!\n&quot;<span style="color: #080;">&#41;</span>;</pre></td></tr></table></div>

<p>In Maple:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="maple" style="font-family:monospace;">print(`Hello, world!\n`);</pre></td></tr></table></div>

<p>In Mathematica:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="mathematica" style="font-family:monospace;">Print[&quot;Hello, world!\n&quot;]</pre></td></tr></table></div>

<p>I suppose that, in the mathematical languages, rather than print &#8220;Hello, world!&#8221; to the display, a true &#8220;Hello, world!&#8221; <em>program</em> would assign that value to a string, and then evaluate the string (to itself).</p>
<p>In an interview situation, I&#8217;ll probably use C/C++, because that&#8217;s the general-purpose programming language that I have the most experience with.  However, I think that Python is actually a better language for quickly mocking up working programs on the spot, so I&#8217;m going to practise using Python some more.</p>
<p>&#8211; davinci 11793</p>
<img src="http://stargrads.net/blogs/davinci/?ak_action=api_record_view&id=2177&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-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>
<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>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://stargrads.net/blogs/davinci/2009/09/programming-exercise-hello-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming exercises and comparison of programming languages</title>
		<link>http://stargrads.net/blogs/davinci/2009/09/programming-exercises-and-comparison-of-programming-languages/</link>
		<comments>http://stargrads.net/blogs/davinci/2009/09/programming-exercises-and-comparison-of-programming-languages/#comments</comments>
		<pubDate>Sat, 26 Sep 2009 18:15:14 +0000</pubDate>
		<dc:creator>davinci</dc:creator>
				<category><![CDATA[autobiography]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[programming and technical issues]]></category>
		<category><![CDATA[comparison of programming languages]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[programming exercises]]></category>

		<guid isPermaLink="false">http://stargrads.net/blogs/davinci/?p=2140</guid>
		<description><![CDATA[
This post begins a series in which I complete some programming exercises using various programming languages.  I will comment on and compare the different languages and their suitability for different tasks.
]]></description>
			<content:encoded><![CDATA[<p>I started programming when I was eight years old.  The first programming language I learned was <span style="font-variant: small-caps">Basic</span>, followed very shortly by C and 8086 assembly language.  During elementary school, I was also exposed to Pascal and Logo.  I ignored Pascal because it seemed to me that anything I could do in it I could already do with C, and although I had some fun with Logo&#8217;s turtle graphics, I didn&#8217;t take it very seriously.  At the time, I didn&#8217;t appreciate its connection with Lisp and other &#8220;serious&#8221; programming languages<span id="more-2140"></span>.</p>
<p><!--adsensestart-->The computer science courses in my high school were <a href="http://stargrads.net/blogs/davinci/2009/09/object-oriented-turing/">taught through Turing</a>, a situation which nobody liked.  Some of my classmates already knew how to program, mostly in <span style="font-variant: small-caps">Basic</span> or Pascal.  Knowledge of C was considered somewhat elite.  I bought cheap (student or home) editions of both Microsoft and Borland development tools.  I made some money doing miscellaneous jobs, mostly using C++, which was my favourite language <a href="http://stargrads.net/blogs/davinci/2009/09/nostalgia-old-computer-programming-software-and-books/">during those years</a> and for the first several years of university.  Some of these jobs involved updating legacy code written in <span style="font-variant: small-caps">Fortran</span>, which I had to learn to read.  I also had some small exposure to Lisp through AutoCAD, but not very much.  I did, on the other hand, write a lot of Visual Basic and Visual Basic for Applications (VBA) code for Microsoft Office.</p>
<p>I learned a lot of web programming in my first year of undergraduate studies, because it was a hot topic at the time, and also because the university provided free web space.  This meant HTML, Java, JavaScript, VBScript, and Perl (because of the many <abbr title="Common Gateway Interface">CGI</abbr> programs written in that language).  A little bit later I also learned PHP, which was relatively new at the time.  In school, I also learned hardware description languages such as <abbr title="Simulation Program with Integrated Circuit Emphasis">SPICE</abbr> and <abbr title="V(ery-High-Speed Integrated Circuit) Hardware Description Language">VHDL</abbr>.  Because the university&#8217;s systems were run on Unix (and, later, GNU/Linux), I also learned shell scripting.  (Of course, I already knew how to write batch files for DOS/Windows, but that hardly counts as a programming language.)</p>
<p>In the third year of university, I was finally properly introduced to Scheme and Lisp.  Unfortunately, I was in an environment that wasn&#8217;t very supportive of the study of those languages.  My fellow engineering classmates were used to C/C++ or Java (or more generally, imperative programming), and many <a href="http://stargrads.net/blogs/davinci/2009/05/the-causes-of-my-depression-part-11-nothing-in-common-with-classmates/">mocked the (to them) bizarre syntax of Scheme and the &lambda;-calculus</a>.  However, I appreciated that there were things I could easily do in Scheme or Lisp that would be difficult &#8212; or even impossible &#8212; to do in C/C++ and Java.  I thought that it was unfortunate that no one had explained the rationale behind Lisp to me earlier, even though I had already been exposed to Lisp on multiple occasions before then.  I think that Lisp is a better introductory language for teaching computer programming than C, because it seems to me that Lisp programmers can easily learn C, whereas people who have gotten used to C have a difficult time learning Lisp.</p>
<p>Because I was in an engineering program, during my upper undergraduate years I wrote a lot of programs in <span style="font-variant: small-caps">Matlab</span>, in addition to programming in C/C++.  This continued throughout my first postgraduate degree, which was in electrical engineering, at the University of Toronto.<!--adsensestop--></p>
<p>When I came to the University of Waterloo for a second postgraduate degree, this time in computer science, I joined the <a href="http://plg.uwaterloo.ca/">Programming Languages Lab</a>.  I was also a teaching assistant for several programming courses, including CS442/642, the university&#8217;s upper year/graduate-level Principles of Programming Languages course.  Needless to say, I learned many, many programming languages during this period, in a large variety of programming paradigms.</p>
<p>For my quantum computing research for the past several years, I have been using mostly Maple and Mathematica, in addition to Matlab.  Because of this, I may have gotten rusty with my programming skills in the more general-purpose (i.e., non-mathematical) languages.  Because I&#8217;m interviewing for software engineering jobs, I need to brush up on these skills.</p>
<p>I&#8217;ve collected some programming exercises from various places, and in this series of posts, I&#8217;m going to do these exercises in a variety of languages, for practice.  I&#8217;ll also comment on the suitability of the various languages to different tasks and compare them with one another.</p>
<p>&#8211; davinci 11792</p>
<img src="http://stargrads.net/blogs/davinci/?ak_action=api_record_view&id=2140&type=feed" alt="" /><p>Related posts:<ol>
<li><a href='http://stargrads.net/blogs/davinci/2009/10/lists-of-programming-exercises/' rel='bookmark' title='Lists of programming exercises'>Lists of programming exercises</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/09/programming-exercises-and-comparison-of-programming-languages/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

