How to Build an Algorithm Part 1: Defining the Problem

The first thing you need to do when building an algorithm is clearly define the inputs and the outputs. This includes the data types to be passed in as parameters and return values. It also includes example input and output, which will turn into your first tests.

The purpose of this exercise is to front-load efficiently so that you can focus on solving the problem instead of wondering if what you've done accomplishes your goals. Start with the most basic example of how your algorithm should function. This is your first test.

Then consider divergent patterns (does it change your solution if the input is an even or odd length) and edge cases (what if the input is a decimal instead of an integer). Create tests to prove that you have solved those edge cases.

The tools you use to create your tests will vary depending on where your algorithm is. For basic Javascript file algorithms (such as you might see in an interview) I like the Mocha framework and the Chai expect library. Jasmine might be a good choice if you'd prefer not to use an HTML spec runner. If you're practicing interview questions, I recommend creating a boilerplate specRunner.html and spec.js file with the libraries that can be copied and pasted into your project root. The goal of testing is to limit extraneous brain use so you can focus on the problem, not how to tell if you solved the problem.

Once you've created a comprehensive suite of tests, you can start to write your pseudo code in the next step (Part 2). As you work through the solution, you may think of other edge cases. You should add these to your tests as you iterate toward a solution.

Read part two next.

Resources:

http://mochajs.org/
http://chaijs.com/
https://github.com/jasmine/jasmine
http://karma-runner.github.io/0.12/index.html
https://docs.npmjs.com/cli/test