Project Euler, #1-10

Posted by Avrithor On July - 1 - 2009

Since I discovered it yesterday, I’ve been hooked on Project Euler, working furiously on solving as many problems as possible. It’s a site that poses hundreds of math problems designed to be solved by writing computer programs, and tracks which ones you’ve solved. Naturally, I’m using JavaScript, and I’ve solved the first ten problems so far. Now, given my inexperience, the solutions I arrived at are going to be flawed—mostly in terms of efficiency—but obviously they work.

I made a file for the project, euler.html, where I’ll write my solutions for each problem. Of course there will be some functions shared among different problems, which is part of the reason for doing it in a single script. I’ll put a button on the page for each problem that’ll run its solution and spit out the answer. Although it doesn’t really matter here, I’ll also stick to best-practices and avoid polluting the global namespace by encapsulating my script’s functionality in a self-executing function. Common, private variables and functions will be defined, and then a hash will be returned with a member for each problem. This exposes them to the rest of the page (so the aforementioned buttons can call them), but they’ll have access to the private stuff thanks to closure.

var Euler = (function() {
  // private stuff here

  return {
    P1: function() {
      // algorithm for problem 1
    },
    // etc...
  };
})();

On to the first 10 problems. Note: If you want to solve them yourself, “spoilers” follow after the jump! Please don’t cheat.
Read the rest of this entry »

JavaScript Custom Event Handling

Posted by Avrithor On June - 4 - 2009

Update, 7/1/2009: Switched code sections from manual coloring to an automatic syntax formatting plugin.

NOTE (6/20/2009): I didn’t intend to close comments on this post. The setting is on “enabled” and I’ve tried disabling and re-enabling them to no avail. Some glitch either with the WordPress 2.8 update or installing the new theme has screwed it up. If you have something to say about this post, drop me a line. My Gmail username is the same as everywhere else.

I haven’t been posting much lately; I have, however, been thinking about my future in some area of computer science, software development, and/or web development. And I’ve been tinkering more with JavaScript since my last post. One thing I’ve discovered how to do is baking event handling into your custom objects. This isn’t really innovative—all the major frameworks out there include it—but I had fun figuring it out on my own. Here’s the solution I arrived at.

I decided that the best way to store and fire event listeners was in an associative array, where the keys are the event names and the values are associative arrays linking IDs to functions. So, for example, a set of registered event listeners for an object representing a door might look like this:

Door.Event
   "Open"   => "a"  => function
   "Close"  => "b1" => function
               "c"  => function
   "Lock"   => (empty)
   "Unlock" => "b2" => function
               "d"  => function

The IDs here are just quick meaningless samples; the idea is that they come from and uniquely identify the object that registered their respective event listeners. They will be used by their originating object to unregister its own event listeners and not any other object’s event listeners if need be, since you may have multiple objects registering listeners for the same event, possibly even the same function registered as a listener by multiple objects. As an example of this, consider a card game. If there are two cards on the board that say, “Whenever a player discards a card, that player takes 5 damage,” you will have two instances of the triggered function (dealing 5 damage to the player) registered on an array of global events for “Discard”, and when that event is fired, both will go off and the function will be executed twice. Yet, if one of those cards is destroyed, it should remove its own specific instance of event listener registration—perhaps the other has had a spell cast on it modifying its effect, so it could matter which one gets deregistered.

Using this system, implementing event listener registration is simple.

Read the rest of this entry »

JavaScript Looping Speed

Posted by Avrithor On April - 16 - 2009

Update, 7/1/2009: Switched code blocks from manual coloring to an automatic syntax highlighter plugin.

Looking for JavaScript optimization tweaks, I encountered a claim that a decrementing do-while loop is faster than an incrementing for loop. I decided to do a quick-and-dirty test to see if there’s any clearly discernible difference. I wrote two scripts, each of which does the exact same thing: create 100,000 DIVs and append them to the body of the page. First we have the standard for version, then the do-while format that the site claimed was superior.

Version 1:

for (var i = 0, d; i < 100000; i++) {
  d = document.createElement("div");
  d.innerHTML = "DIV #" + i + "";
  document.body.appendChild(d);
}

Version 2:

var j = 0;
do {
  var i = 100000 - j,
      d = document.createElement("div");
  d.innerHTML = "DIV #" + i + "";
  document.body.appendChild(d);
} while (--j);

Note that the do-while has an extra line to set a variable i that will increment just as i does in the for loop, thus we get the same result of DIVs numbered 0-99,999. But what if the direction doesn’t matter? What if going backwards and numbering the DIVs from high to low is acceptable, or even what we actually want? The do-while proponent cited in support of his claim that computers are simply faster at counting down than they are at counting up. Whether that’s true or not, I don’t know. But it seemed worthwhile to include two more variants in my testing:

Version 3:

for (var i = 99999, d; i >= 0; i--) {
  d = document.createElement("div");
  d.innerHTML = "DIV #" + i + "";
  document.body.appendChild(d);
}

Version 4:

var j = 99999;
do {
  var d = document.createElement("div");
  d.innerHTML = "DIV #" + j + "";
  document.body.appendChild(d);
} while (j--);

I tested each version 10 times. Each test ran in a fresh instance of Firefox v3.0.6 with no other open tabs. Here are the results:

There seems to be no significant difference here between different looping techniques. In light of this, I’d call it a matter of clarity/readability and somewhat personal preference. If you have to increment, obviously the for loop is clearer to read. For decrementing, either seems fine, though I like the do-while.

About Me

I'm a computer science student at the University of Minnesota and enthusiast for the arts, gaming, and technology.

Quotable

"Madame, my kingdom is a small one,
but I am king there."


—Frederic Chopin, asked why he wrote many nocturnes, but never a symphony or opera