Creating algorithms

Including an algorithm in a page

An algorithm is stored in a single page in the Algorithm namespace. Different variants of the same algorithm are stored on different pages. For example Factorial recursive and Factorial iterative.

You include an algorithm on a different page using the algorithm tag. The last part of the tag is the title of the algorithm page.

[algorithm Fisher-Yates shuffle]

This transcludes the algorithm from Fisher-Yates shuffle.

Creating an algorithm page

An algorithm page is split into five sections: Source, Support, Unit Tests, Options, and Visualisation. Each section is editable in a tabbed code editor at the bottom of the algorithm page.

Algorithm

The 1st section contains the algorithm. This is the code that the user sees in the interactive environment. For example, this is the code for the Fisher-Yates shuffle algorithm.

function shuffle(a) {
    for (var i=a.length-1; i>0; i--) {
        var j = Math.floor(Math.random()*(i+1)); // j random integer [0-i]
        swap(a, j, i);
    }
    return a;
}

Support

The 2nd section contains the support code. This is code that the main algorithm makes use of, for example utility functions. If the support code also includes a run() function then this function is called when running the algorithm, instead of running the algorithm code from line 1.

function swap(a, i, j) {
    var t = a[i]; a[i] = a[j]; a[j] = t;
}
a = [1,2,3,4,5,6,7,8,9,0];
function run() {
    return shuffle(a);
}

Unit Tests

The unit tests section should contain unit tests to ensure the algorithm is correct. Each function in this section whose name has a 'test' prefix will be run on a web-worker thread. If there is any exception thrown during running the function the test fails.

Options

The 4rd section contains options in JSON format. Available options are

A simple example is:

{
    "title":"Fisher-Yates shuffle",
    "height":"270px"
}

For a more complex example see λ Hash set open-hashing.

Visualisation

The 4th section contains the visualisation code. This code is a self contained webpage, it is embedded in an iframe when displayed alongside the code.

The webpage must provide a global update() function, which is called at each new line when running the algorithm. The update function takes several arguments,

Two other functions are optional: globals() and args(). If the visualisation contains a global function args() then the return value of calling that function will be passed into the run() support function. This allows the visualisation to supply the input to the algorithm. If a globals() function is provided then it returns an object whose keys are added to the globals of the interpreter.