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 »
