<?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>Flagrant Badassery &#187; Code Challenge</title>
	<atom:link href="http://blog.stevenlevithan.com/category/code-challenge/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.stevenlevithan.com</link>
	<description>A JavaScript and regular expression centric blog</description>
	<lastBuildDate>Thu, 25 Oct 2012 16:59:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Code Challenge: Change Dispenser</title>
		<link>http://blog.stevenlevithan.com/archives/change-dispenser</link>
		<comments>http://blog.stevenlevithan.com/archives/change-dispenser#comments</comments>
		<pubDate>Fri, 20 Jun 2008 18:00:16 +0000</pubDate>
		<dc:creator>Steven Levithan</dc:creator>
				<category><![CDATA[Code Challenge]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://blog.stevenlevithan.com/?p=79</guid>
		<description><![CDATA[I recently encountered a brain teaser that asked to take an amount of change and return the equivalent in dollars and coins. Here's the five-minute solution I first came up with. function makeChange (money) { var i, num, output = [], coins = [ [100, "dollar", "dollars" ], [25, "quarter", "quarters"], [10, "dime", "dimes" ], [...]]]></description>
				<content:encoded><![CDATA[<p>I recently encountered a brain teaser that asked to take an amount of change and return the equivalent in dollars and coins.</p>

<p>Here's the five-minute solution I first came up with.</p>

<pre class="code">function makeChange (money) {
    var i, num,
        output = [],
        coins  = [
            [100, "dollar",  "dollars" ],
            [25,  "quarter", "quarters"],
            [10,  "dime",    "dimes"   ],
            [5,   "nickel",  "nickels" ],
            [1,   "penny",   "pennies" ]
        ];
    money = money * 100; // avoid float precision issues
    for (i = 0; i < coins.length; i++) {
        num = Math.floor(money / coins[i][0]);
        money -= num * coins[i][0];
        if (num) {
            output.push(num + " " + coins[i][num > 1 ? 2 : 1]);
        }
    }
    return output.join(", ");
}

makeChange(0.37); <span class="comment">// "1 quarter, 1 dime, 2 pennies"</span></pre>

<p>I feel like I'm missing something, though. <span style="font-size:125%;"><em>How would you improve this code to make it shorter, faster, or otherwise better?</em></span></p>]]></content:encoded>
			<wfw:commentRss>http://blog.stevenlevithan.com/archives/change-dispenser/feed</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Regex Day Contest</title>
		<link>http://blog.stevenlevithan.com/archives/regexday-2008</link>
		<comments>http://blog.stevenlevithan.com/archives/regexday-2008#comments</comments>
		<pubDate>Thu, 29 May 2008 09:24:47 +0000</pubDate>
		<dc:creator>Steven Levithan</dc:creator>
				<category><![CDATA[Code Challenge]]></category>
		<category><![CDATA[Regular Expressions]]></category>
		<category><![CDATA[contest]]></category>
		<category><![CDATA[schwag]]></category>

		<guid isPermaLink="false">http://blog.stevenlevithan.com/archives/regexday-2008</guid>
		<description><![CDATA[A few months ago Ben Nadel (a regex fan and prominent ColdFusion blogger) asked me if I was interested in promoting his idea for a "National Regular Expression Day," where he'd give away some shirts and books and basically just have some fun with regex evangelism. Well, Ben finally kicked if off, assigning the honor [...]]]></description>
				<content:encoded><![CDATA[<p>A few months ago <a href="http://www.bennadel.com">Ben Nadel</a> (a regex fan and prominent ColdFusion blogger) asked me if I was interested in promoting his idea for a "National Regular Expression Day," where he'd give away some shirts and books and basically just have some fun with regex evangelism. Well, Ben finally <strong><a href="http://www.bennadel.com/index.cfm?dax=blog:1243.view">kicked if off</a></strong>, assigning the honor to June 1st, 2008. Make sure to check out his blog post, because by simply posting a comment noting your preferred item from his list before June 2nd, you're entered to win it.</p>

<p>I'm all for regex evangelism, so I figured I'd get in on the action with my own regex contest where you can win the best commercial regex products I know of, worth up to $150! The rules are a little different here though. For one thing, you've got more time to enter &mdash; I'll keep this open until the end of Friday, June 13. Second, this isn't a lottery. The rules are still pretty simple, though.</p>

<ul>
	<li>Write (or link to) some kind of creative regex content in a comment on this blog post.</li>
	<li>It has to be something new, specifically for this contest.</li>
	<li>Enter by unlucky Friday, June 13.</li>
	<li>When submitting your entry, make sure to include an email address where I can reach you in the email field (it won't be visible to others, and I'll only use it to contact you about this contest).</li>
	<li>You can submit multiple entries, but each will be judged on its own and one person cannot win more than one award.</li>
	<li>I get to be the judge and jury.</li>
</ul>

<p>As for what kind of content is eligible, well, pretty much anything as long as it's regex related. You can write a regex joke (preferably not ending with the punchline "now they have two problems"), post a regex article somewhere, create a regex comic strip, share your favorite regex you've written, design a regex superhero, create a regex game, tell a story about how regexes saved the day, link to a blog post you've written about Regular Expression Day, or whatever you can come up with. Go nuts.</p>

<p>Here's what the winners can choose from. If you win first or second place but none of the prizes in that tier interest you, you can pick <strong>two</strong> items from a lower level.</p>

<ul>
	<li><strong>First Prize:</strong>
		<ul>
			<li><a href="http://www.powergrep.com/cgi-bin/affref.pl?aff=SteveL">PowerGREP</a></li>
		</ul>
	</li>
	<li><strong>Second Prize:</strong>
		<ul>
			<li><a href="http://www.regexbuddy.com/cgi-bin/affref.pl?aff=SteveL">RegexBuddy</a></li>
			<li><a href="http://www.amazon.com/dp/0596528124/?tag=slfb-20">Mastering Regular Expressions, 3rd Edition</a></li>
			<li><a href="http://www.thinkgeek.com/tshirts/itdepartment/57f0/">Shakespeare Regular Expression Shirt</a></li>
			<li><a href="http://store.xkcd.com">XKCD Regular Expressions Shirt</a>, based on <a href="http://xkcd.com/208/">comic 208</a></li>
			<li><a href="http://www.zazzle.com/168497609810962553">Regular Expressions Quick Reference Mug</a></li>
			<li><a href="http://www.amazon.com/dp/1411677609/?tag=slfb-20">Regular Expressions: The Complete Tutorial</a></li>
			<li><a href="http://silveragesoftware.com/search-replace-text-tool.html">HandyFile Find and Replace Text Workbench</a> &mdash; I haven't tried this</li>
		</ul>
	</li>
	<li><strong>Third Prize:</strong>
		<ul>
			<li><a href="http://www.amazon.com/dp/0672325667/?tag=slfb-20">Regular Expressions in 10 Minutes</a></li>
			<li><a href="http://www.amazon.com/dp/0596514271/?tag=slfb-20">Regular Expression Pocket Reference, 2nd Edition</a></li>
			<li><a href="http://www.amazon.com/dp/0596006012/?tag=slfb-20">Oracle Regular Expressions Pocket Reference</a></li>
			<li><a href="http://www.amazon.com/dp/0596003528/?tag=slfb-20">sed and awk Pocket Reference, 2nd Edition</a></li>
		</ul>
	</li>
</ul>

<p>Good luck, and I hope you have fun with this. <img src="http://blog.stevenlevithan.com/wp-includes/images/smilies/icon_smile.gif" alt="smile" /> (Once again, make sure to check out <a href="http://www.bennadel.com/index.cfm?dax=blog:1243.view">Ben's post</a> that started this.)</p>]]></content:encoded>
			<wfw:commentRss>http://blog.stevenlevithan.com/archives/regexday-2008/feed</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>JavaScript Roman Numeral Converter</title>
		<link>http://blog.stevenlevithan.com/archives/javascript-roman-numeral-converter</link>
		<comments>http://blog.stevenlevithan.com/archives/javascript-roman-numeral-converter#comments</comments>
		<pubDate>Sun, 16 Mar 2008 04:59:51 +0000</pubDate>
		<dc:creator>Steven Levithan</dc:creator>
				<category><![CDATA[Code Challenge]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://blog.stevenlevithan.com/archives/javascript-roman-numeral-converter</guid>
		<description><![CDATA[While looking for something quick to do during a brief internet outage, I wrote some code to convert to and from Roman numerals. Once things were back up I searched for equivalent code, but only found stuff that was multiple pages long, limited the range of what it could convert, or both. I figured I [...]]]></description>
				<content:encoded><![CDATA[<p>While looking for something quick to do during a brief internet outage, I wrote some code to convert to and from Roman numerals. Once things were back up I searched for equivalent code, but only found stuff that was multiple pages long, limited the range of what it could convert, or both. I figured I might as well share what I came up with:</p>

<pre class="code">function romanize (num) {
	if (!+num)
		return false;
	var	digits = String(+num).split(""),
		key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
		       "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
		       "","I","II","III","IV","V","VI","VII","VIII","IX"],
		roman = "",
		i = 3;
	while (i--)
		roman = (key[+digits.pop() + (i * 10)] || "") + roman;
	return Array(+digits.join("") + 1).join("M") + roman;
}

function deromanize (str) {
	var	str = str.toUpperCase(),
		validator = <span class="regex">/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/</span>,
		token = <span class="regex">/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g</span>,
		key = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1},
		num = 0, m;
	if (!(str &amp;&amp; validator.test(str)))
		return false;
	while (m = token.exec(str))
		num += key[m[0]];
	return num;
}

</pre>

<p style="font-size:130%">How would <em>you</em> rewrite this code? Can you create a shorter version?</p>]]></content:encoded>
			<wfw:commentRss>http://blog.stevenlevithan.com/archives/javascript-roman-numeral-converter/feed</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>JavaScript String Multiplication Performance Exploration</title>
		<link>http://blog.stevenlevithan.com/archives/fast-string-multiply</link>
		<comments>http://blog.stevenlevithan.com/archives/fast-string-multiply#comments</comments>
		<pubDate>Sun, 18 Nov 2007 07:56:43 +0000</pubDate>
		<dc:creator>Steven Levithan</dc:creator>
				<category><![CDATA[Code Challenge]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://blog.stevenlevithan.com/archives/fast-string-multiply</guid>
		<description><![CDATA[Since JavaScript concatenates strings with the + operator, it would be nifty if it would also let you multiply strings using e.g. str * 10 (as can be done in Python, at least). Since you can't do that, and no native string multiplication method is provided, I recently explored a few ways to pull it [...]]]></description>
				<content:encoded><![CDATA[<p>Since JavaScript concatenates strings with the <code>+</code> operator, it would be nifty if it would also let you multiply strings using e.g. <code>str * 10</code> (as can be done in Python, at least). Since you can't do that, and no native string multiplication method is provided, I recently explored a few ways to pull it off&hellip;</p>

<p>A naive approach to writing a string multiplier function goes something like this:</p>

<pre class="code">function mul0 (str, num) {
	if (!num) return "";
	var newStr = str;
	while (--num) newStr += str;
	return newStr;
}
</pre>

<p>As many JavaScripters are aware, that isn't the best approach since string concatenation can be quite slow in Internet Explorer. And while IE tends to get a bad rap for this (fortunately, the IE team is <a href="http://blogs.msdn.com/jscript/archive/2007/10/17/performance-issues-with-string-concatenation-in-jscript.aspx">fixing the problem</a> in the next version of their browser), Firefox isn't exactly blazing fast at string concatenation either. Due to the performance issues, the typical string multiplication approach is to build an array and <code>join</code> it. Here's a nice, short way to do that:</p>

<pre class="code">function mul1 (str, num) {
	return num ? Array(num + 1).join(str) : "";
}
</pre>

<p>Note that the falsy <code>num</code> handling is probably not warranted in this case since the function would handle value <code>0</code> correctly without it. It's done anyway to keep functionality equivalent across the variations.</p>

<p>Unfortunately, <code>mul1</code> can still be pretty slow in Firefox 2 when multiplying large strings many times. It might be unnoticeable with small strings and repetition numbers, but the completion time goes up at a super-linear rate as the numbers increase. In search of a faster solution, I tried using a regex to keep down the size of the string being worked with:</p>

<pre class="code">var mul2 = function () {
	function mul (str, num) {
		return Array(num + 1).join(str);
	}
	return function (str, num) {
		return num ? str.replace(/^/, mul("$'", num - 1)) : "";
	};
}();
</pre>

<p>The above multiplies the two-character string "<code>$'</code>" <code>num - 1</code> times, then uses that as the replacement for a regex which just matches the start of the string (<code>$'</code> returns the text to the right of the match). How does that perform? It delivers in Firefox 2 on my Windows Vista system, with numbers like 95ms vs. 29800ms (<code>mul1</code>) when using a 2700x2700 string length/multiplier. However, based on my testing, that sort of speed gain appears to be limited to Firefox, and in Safari 3 beta <code>mul2</code> is considerably slower that the alternative versions.</p>

<p>Finally, I tried creating a version which multiplied the string at an exponential rate:</p>

<pre class="code">function mul3 (str, num) {
	if (!num) return "";
	var	orig = str,
		soFar = [str],
		added = 1,
		left, i;
	while (added &lt; num) {
		left = num - added;
		str = orig;
		for (i = 2; i &lt; left; i *= 2) {
			str += str;
		}
		soFar.push(str);
		added += (i / 2);
	}
	return soFar.join("");
}
</pre>

<p>Although that might be more code than you're willing to dedicate to a string multiplication method, it's the fastest of the above versions on average cross-browser. I've also tried a few variations using from zero to two arrays and various array methods (<code>push</code>, <code>concat</code>, etc.), but the above seems to be the fastest on average across the big four browsers.</p>

<p>Make sure to <a href="http://stevenlevithan.com/demo/mul/test.html">try the tests for yourself</a>, and let me know your thoughts and how you would improve the code.</p>

<hr/>

<p><strong>Edit:</strong> <a href="http://cixar.com/~kris.kowal/">Kris Kowal</a> contributed <code>mul4</code> (shown below, and added to the test page). It uses binary interpolation, and in Kris's words "it takes advantage of a fun bitwise identity: <code>(1 &lt;&lt; n) == Math.pow(2, n)</code>". On my system it's significantly faster than <code>mul3</code> in Firefox, but a little slower than <code>mul3</code> in IE, Safari, and Opera. Due to its high speed and lighter weight, this looks like the one to beat. Try the <a href="http://stevenlevithan.com/demo/mul/test.html">test page</a> in several browsers and see what you think.</p>

<pre class="code">function mul4 (str, num) {
	var acc = [];
	for (var i = 0; (1 &lt;&lt; i) &lt;= num; i++) {
		if ((1 &lt;&lt; i) &amp; num)
			acc.push(str);
		str += str;
	}
	return acc.join("");
}
</pre>

<hr/>

<p><strong>Edit 2:</strong> <a href="http://www.liucougar.net/blog">LiuCougar</a> of the Dojo development team posted a <a href="http://www.liucougar.net/blog/archives/76">follow-up</a> which includes several additional variations, and <a href="http://web-graphics.com/">David Andersson</a> emailed me an additional four variations including this one:</p>

<pre class="code">function mul8 (str, num) {
	var	i = Math.ceil(Math.log(num) / Math.LN2),
		res = str;
	do {
		res += res;
	} while (0 &lt; --i);
	return res.slice(0, str.length * num);
}
</pre>

<p>I should clarify however that this is mostly just academic discussion, since repeating the kinds of strings in the test page as many times as it does is a pretty crazy idea. Still, it's fun to experiment. <img src="http://blog.stevenlevithan.com/wp-includes/images/smilies/icon_smile.gif" alt="smile"/></p>

<hr/>

<p><strong>Edit 3:</strong> All the variations posted or emailed in response to this post can be seen at <strong style="font-size:120%"><a href="http://stevenlevithan.com/demo/mul/all.js">stevenlevithan.com/demo/mul/all.js</a></strong>. For the sake of consistency I've made a few minor adjustments to some of the functions such as whitespace tweaks and renaming the input arguments to <code>str</code> and <code>num</code>.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.stevenlevithan.com/archives/fast-string-multiply/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
