Introduction


Welcome to Algomation.com I design and developed this website to provide a platform for creating, sharing and most importantly, visualizing algorithms of all types. Algorithm visualizations are presented on a player page which incorporates a graphical surface for the visualization, a source code panel that shows that actual algorithm source, a message area which describes the algorithm and how it functions and a control bar that gives you complete control on how the algorithm playback proceeds. You can see an example of a sorting algorithm here: Quick Sort

If you find this site useful or have feedback on how to make it better please let me know via the feedback page.


Viewing Algorithms

Algorithms created by you or any other Algomation user are displayed on their own player page. The player page incorporate five main components.

Player Visualizer

The visualizer displays the graphical output of the algorithm as determined by the author of the algorithm. By default the algorithm will begin running without pauses when you first land on the player page. The size of the player window is automatically determined by the size of your browser window. It is scaled to fit while retaining the original aspect ratio of the display surface.

Player Controls

The player controls let you control the way the algorithm runs. When you first land on the player page the algorithm will load and start running without pauses. Algorithms contain yield points which function much like breakpoints in conventional code. Whenever the player encounters a yield point in the algorithm the visualizer is updated with the current graphical elements determined by the algorithm. Any and all changes to any and all graphical elements in the visualizer are transitioned and animated to their new state. In 'Continuous' mode the player will continue running after updating the display. Clicking the 'Single Step' button will switch to a mode where the algorithm pauses at each yield point. To continue to the next yield point simply click the continue button to proceed.

The speed of the animation and transitions can be selected using the 'Slow', 'Normal' and 'Fast' buttons which have an immediate effect on the output. The speed of the algorithm can be changed at anytime regardless or whether the algorithm is running in Continuous or Single Step mode.

The 'Options' button reveals a drop down menu that presents commands for forking, sharing, embedding, restarting and viewing other algorithms by the same author. Forking makes a new copy of the algorithm and takes you to the algorithm editor ( see below ). Sharing simple presents you with a URL that you can use to share the algorithm. The embedding option provides an interactive dialog for creating the necessary HTML tag to embedded the algorithm visualizer on your own website.

When the algorithm is paused or has completed you can move the history slider below the primary buttons to review each frame of the animation and all the associated changes to the source code window and messages window. Use the mouse to drag the slider thumb or use the keyboard when the control has the focus. When you resume or restart the algorithm the display is restored to the current frame of the animation.

Player Source Code Viewer

The complete source code for each algorithm is presented in the source code window at the bottom left of the player window. The source code editor is a fully interactive editor but is running in read only mode on the player page. Whenever the algorithm reaches a yield point the source window will scroll to an appropriate place in the code, as defined by the author, for that yield point.

Player Messages

The messages area at the top left of the player window display the title and description of the algorithm being played as set by the author. Below the description is the name of the author including a link to any other algorithms created by the Algomation user. When the algorithm encounteres a yield point a description of the significance of this yield point is displayed in the 'Step' section of the window. If the author has choosen to display the values of any variables relevant to the current yield point that are display in the 'Variables' section. The each variables so displayed includes a meaningful name and the current value of that variable.

Sharing Algorithms

Algomation is platform for sharing algorithms so there are two different ways to meet this objective. From the player window open the options menu and select 'Share Algorithm'. You will see a modal dialog containing a link to the algorithm. Copy and paste this link wherever you wish. Openers of the link do not need to be registered or signed into algomation.com it use it.

The algomation site also supported embedding the algorithm on another site in much the same way that YouTube videos can be embedded on other websites. From the options menu select the 'Get Embed Script' command. You will be presented with a modal dialog that allows you to customize the size of the player that is embedded. Once you have selected the desired size copy and paste the embed script into the source for your webpage or blog. The embedded player is a stripped down version of the player that show only the animated display surface. The algorithm is run automatically within the embedded player. Clicks on the algorithm will direct the viewer to the full player page for the algorithm on algomation.com

Finding Algorithms

All the algorithms on Algomation.com are public and available to users of the website whether they are registered users of the site or not. You do not need to be registered or signed on to search for algorithms. The search feature is powered by Mongo DB search text and applies to all terms within the title and description of an algorithm. The search page is located here:  Search Page

If you have created any algorithms on Algomation.com they can be found on the "My Algorithms" page. You will need to register and sign in to create algorithms or before visiting the "My Algorithms" page. The "My Algorithms" page is located here:  My Algorithms

Whenever the site displays a list of algorithms ( Search or My Algorithms for example ) a standard algorithm tile is used. These tiles display title, description, author, creation and modification times of the algorithm. Additionally they display two links, the first to open the algorithm in the player and the second which eithers allows you to edit the algorithm, if you are the author, or fork the algorithm if you are not.

Featured Algorithms

Algorithms of general interest and high quality may be selected to become 'Featured Algorithms'. Featured algorithms appear on our homepage. Featured algorithms are forked copies of an algorithm. If you wish to have your algorithm featured please send me a link to it via our feedback page.

Creating Algorithms

Any registered user can create new algorithms or fork existing algorithms on the site. The algorithm visualizations are created with a simple, yet powerful, graphics API that includes specialized features for displaying algorithms and complex data structures. NO knowledge of HTML or CSS is required. Your algorithm when completed is described entirely by the JavaScript you write in conjunction with our API.

All Algorithms are Public

ALL algorithms on Algomation.com are publicly visible at all times. Further, all Algorithms are made available under the terms of the MIT License. See our Terms of Service for more details.

Although all algorithms are public only the creator of an algorithm may modify it. Registered users may create a fork of an existing algorithm if they wish to modify it or use it as a starting point for their own algorithm.

There are two ways to create a new algorithm. First, clicking the 'Create Algorithm' link in the header and footer of every page will open the algorithm editor with a new algorithm containing some sample code. Secondly, you can fork an existing algorithm by opening it in the player and using the 'Fork' command on the options menu. In either case you will see the editor ready to use.

There are three main areas.

You can try running the algorithm right away clicking the "Debug Test" or "Release Test" button. Both will open a new window with a debug version of the player or as it would appear on the site according to which button you clicked.

Popup Windows

The player window is considered a popup window and might be blocked from opening by your browser. If this is the case you may need to allow popups from algomation.com to automatically open everytime.

There is no need to close the player window after each run, the editor can reuse the same window each time you run the algorithm. Before we dive into running and debugging in more details we are going to look at how you write algorithms for algomation.com

Getting Help

Algorithms created on Algomation.com use API to display and control the playback of their algorithm on the site. We will describe that API in more detail below but for now here are both a link to our API Documentation ( auto-generated by JSDoc ) and the full source code on Github. Please feel free to submit bug reports or defects via the feedback page or better yet by adding features and fixing bugs and submitting pull requests on Github.


API 1.0 Documentation
API 1.0 Source Code ( Github )

New Algomation Tutorials!

There are now a set of guide tutorials to the Algomation API.

Click to visit the tutorials page.

Languages

All algorithms on Algomation are written in JavaScript. Although JavaScript is the lingua franca of the web it is not widely used outside of that context. However, it is a relatively easy language to learn and remarkablely flexible and performant. A good introduction to the language may be found here:


JavaScript on MDN

Algorithms developed on the site are written in JavaScript (ECMAScript 5) with support for generator function borrowed from ECMAScript 6 Harmony. Your code is transpiled down to ECMAScript 5 before running on the site. This step is transparent to the users of the site and is necessary to provide support for generators of which you will read much more below. Since we transpile the algorithms before running it will be possible in the future to support other languages. For example we hope to support Python in the near future.

Architecture

Before describing the steps for creating and testing an algorithm it is neccesary to understand a little of the architecture of the site. We have already mentioned that your algorithm code is developed in JavaScript. Additionally you should be aware that running algorithms are NOT running in the context of a web page but rather in a Web Worker. A web worker is somewhat akin to a traditional thread. Running in a web worker allows us to unload and reload algorithms and ensures that your algorithm cannot disturb the page it is displayed on. Also, since web workers are threaded their execution does not block user interface interactions.

Simplicity

Although you algorithm is a transpiled generator running in a web worker thread almost all of this complexity is hidden from you. You are free to simple make calls to our graphics API and create yield points in your code which will be realized in the player without any other code necessary by you.

Anatomy of an Algorithm

To help you develop your own algorithms we are going to review, line by line, one of the complete algorithms already on the site. The algorithm is a simple demonstration of in-place array reversal. You can see this algorithm running here: ( this is also the template code we provide whenever you create a new algorithm ).


Array Reversal Algorithm

The complete code for this algorithm is below. Although it is a simple algorithm it is not completely trivial and you will a good deal about how to write more complex algorithms on Algomation by reviewing it.

function* algorithm() {

    //=Initialize, display the array/string we are going to reverse
    var WORD = "過ぎたるはなお及ばざるが如し";

    // create and display WORD using letter tiles
    var varray = makeArray();

    // start the algorithm
    var left = 0,
        right = WORD.length - 1;
    yield ({
        step: "The string we are going to reverse. Initialize two indices, left and right to either end of the array.",
        line: "//=Initialize",
        variables: {
            Word: WORD,
            left: left,
            right: right
        }
    });

    // start reversing the array by swapping elements at either end
    //=swap
    while (left < right) {

        yield ({
            step: "Exchange the items in the slots identified by the left and right variables.",
            line: "//=swap",
            variables: {
                left: left,
                right: right
            }
        });

        // swap the two items on the array and reposition their elements
        varray.swap(left, right);

        yield ({
            autoskip: true
        });

        // move left and right indices towards the center of the array
        left += 1;
        right -= 1;
    }

    yield ({
        step: 'The algorithm is complete when the left and right indices either converge on the middle element or pass over each other.'
    });

    // display the WORD variables
    function makeArray() {

        // get bounds of surface we are displayed on
        var bounds = algo.BOUNDS;

        // derive tile size from surface size and word length
        var kS = bounds.w / (WORD.length + 2);

        // we only need a simple single row grid
        var layout = new algo.layout.GridLayout(bounds, 1, WORD.length);

        // create the array wrapper
        return new algo.core.Array({

            // initialize with the word

            data: WORD,

            // called whenever a new item is added to the array, you should return the element used
            // to visualize the item

            createElement: _.bind(function(value, index) {

                // create a new letter tile. Display the letter and the array index in the tile
                var element = new algo.render.LetterTile({
                    text: value,
                    w: kS,
                    h: kS * 1.5,
                    value: index
                });

                // position within the appropriate row/column of the layout
                element.layout(layout.getBox(0, index));

                return element;

            }, this),

            // Use a path based animation to transition swapped elements to thier new locations
            swapElement: _.bind(function(value, newIndex, oldIndex, element) {

                // get the bounding box of the new and old cell
                var newCell = layout.getBox(0, newIndex),
                    oldCell = layout.getBox(0, oldIndex);

                // get x position for element centered in cell
                var newX = newCell.cx - element.w / 2,
                    oldX = oldCell.cx - element.w / 2;

                // height of the cell is used to move the items above or below the displayed string and
                // the start/end vertical position of the tiles is a constant

                var H = element.h * 1.5,
                    Y = element.y;

                // if item was in the left/lower half of the array move it up and over,
                // if item was in the right/upper half of the array move it down and under

                var yoffset = oldIndex < WORD.length / 2 ? H : -H;

                element.set({
                    y: [Y + yoffset, Y + yoffset, Y],
                    x: [oldX, newX, newX],
                    state: [algo.render.kS_BLUE, algo.render.kS_BLUE, algo.render.kS_FADED]
                });
            })
        });
    }
}

Identify you Algorithm

When Algomation wants to run your algorithm it loads your code along with the Algomation API code. It then looks for a function named 'algorithm' in your code. In fact this function must be a special type of function called a generator. You define a generator function by simply putting an asterisk between the keyword 'function' and your generator name, which is this case is called 'algorithm'.

function* algorithm() {

This function is akin to the main function common in C++ or Java programs. Most of your logic and control flow should be inside this function.

Display Elements

Next we define the array/string we are going to reverse and create our display elements.

//=Initialize, display the array/string we are going to reverse
var WORD = "ALGORITHMS";

// create and display WORD using letter tiles
var varray = makeArray();

The first section of 'makeArray()' is concerned with establishing the size of the display area and creating a 'GridLayout' object to help us position elements on the screen. The bounds of the algorithm player are contained within the global variables 'algo.BOUNDS'.

// display the WORD variables
function makeArray() {

    // get bounds of surface we are displayed on
    var bounds = algo.BOUNDS;

    // derive tile size from surface size and word length
    var kS = bounds.w / (WORD.length + 2);

    // we only need a simple single row grid
    var layout = new algo.layout.GridLayout(bounds, 1, WORD.length);

Namespaces

JavaScript does not have support for namespaces. However it is common practise to associated all the variables and functions of a particular library with a single global variable e.g.

algo = algo || {}; algo.BOUNDS = ...

The variable 'bounds' is a reference to an instance of 'algo.layout.Box' which is a rectangle with properties like x, y, w and h

Next we calculate the size of the squares ( kS ) that we are going to use for the letters. We use the width of the available surface, plus a couple of extra letters just to give us some space between the letters.

Display Size

In the current iteration of Algomation the player is always 900 x 556 pixels ( the Golden Ratio ) The dimensions and aspect ratio of the display are always the same. The display is scaled automatically when the available area is less than 900 x 556. Generally you should avoid coding with a fixed size and mind and use fractions of the available dimensions when creating display elements.

Next we create an algo.layout.GridLayout object supplying the bounds of the player and the number of rows and columns we want in the grid. GridLayouts are one of a number of useful classes in the layout namespace for positioning elements on the screen. In this case we need a GridLayout with a single row and a column for each letter in the word.

Next we begin to define the algo.core.Array wrapper using a literal object to parameterize it.

return new algo.core.Array({

The first parameter is just the data we want stored in the array

data: WORD,

The remaining two parameters are callback functions that the array object will invoke as necessary to display the array. The first callback is used to create elements to represent each item in the array

createElement: function(value, index) {

    // create a new letter tile. Display the letter and the array index in the tile
    var element = new algo.render.LetterTile({
        text: value,
        w: kS,
        h: kS,
        value: index
    });

    // position within the appropriate row/column of the layout
    element.layout(layout.getBox(0, index));

    return element;

}.bind(this),

All display elements are within the 'algo.render' namespace. In this case we are creating a LetterTile which is a rectangle with text displayed in the center and a another piece of text displayed at is top right. LetterTile objects are similar to tiles in the board game Scrabble. They are useful for display items with value and position. We 4 parameters to the newly created LetterTile, the text that appears on its face, the width and height it should be and the value that should appear at its top right.

As we create the LetterTile we also set its initial position. For this we use the location returned by our GridLayout object. We then apply this location to the LetterTile object using its layout method, which simply centers the element within the given box

element.layout(layout.getBox(0, index));

Some Context

Before looking at the swapElement callback we need to discuss context in JavaScript. All JavaScript code runs in some context or scope. The scope determines which objects that particular piece of code can access. Imparticular the 'this' keyword in JavaScript can be a little tricky for newcomers. You can read a good description of it here:

JavaScript Context MDN

With callbacks in JavaScript you should always prepare for the possibility that the context you are expecting is not the one you actually get. The easiest way to avoid problems is to ensure that 'this' is what you expect using the 'bind' method available on all function objects.

Function Bind MDN

You will see that both our callbacks use bind at the end of their declaration to ensure that the same scope is in effect when the callback is invoked as when it was created.

}.bind(this),

Even More Context

In some algorithms in the site you might see a callback defined thus:

_.bind(function() {...}), this);

The snippet above is using the excellent UnderscoreJS library to achieve the same effect as the native bind function. Both UnderScoreJS and UnderScore String are available for use by algorithms you develop. They are both extremely useful, UnderScoreJS because it provides functionality similar to itertools in python and UnderScore String because it provides _.sprintf making C/C++ programmers feel right at home.

Underscore JS
Underscore String

Swapping Elements

we call the swap method of the array class.

swapElement: function(value, newIndex, oldIndex, element) {

    // get the bounding box of the new and old cell
    var newCell = layout.getBox(0, newIndex),
        oldCell = layout.getBox(0, oldIndex);

    // get x position for element centered in cell
    var newX = newCell.cx - element.w / 2,
        oldX = oldCell.cx - element.w / 2;

    // height of the cell is used to move the items above or below the displayed string and
    // the start/end vertical position of the tiles is a constant

    var H = element.h * 1.5,
        Y = element.y;

    // if item was in the left/lower half of the array move it up and over,
    // if item was in the right/upper half of the array move it down and under

    var yoffset = oldIndex < WORD.length / 2 ? H : -H;

    element.set({
        y: [Y + yoffset, Y + yoffset, Y],
        x: [oldX, newX, newX],
        state: [algo.render.kS_BLUE, algo.render.kS_BLUE, algo.render.kS_FADED]
    });

}.bind(this)

Our swap element callback it called for each element of the array as it is moved. The parameters to the callback are the value of the item, the new and old index of the item and the graphical element used to display the element.

The first step is to simple get the old and new center x and center y of the element being moved. Next we choose whether to move the element under or over the other tiles according to whether it is in the left half or right half of the string.

Finally we apply the changes to the element using the 'set' method of the element. The set method if the primary and often times the ONLY API you need to change the properties of an element. All changes to the properties of elements are automatically applied as animations to the element. You never need to manage animations or tweens yourself.

Setting Properties

The set API is so important that I have given it its own section in the documentation. Below are several examples of set with explanations for each.

var e = new algo.render.Rectangle();

// 1. The simplest form of set. We supply an object containing the names and values of each
//    property to change.

e.set({
    x: 0,
    y: 0,
    w: 100,
    h: 100
});

// 2. Sometimes you want to set the properties of multiple elements at the same time to the same properties.
//    There is a static version of set that allows you to do just this.

var f = new algo.render.Rectangle();
algo.render.Element.set({

    w   : 100,
    fill: 'red'

}, e, f);

// 3. You can set arrays of property values. When the player encounters an array it applies the
//    properties sequentially with a display update and animated change between each value update.
//

e.set({ x: [0, 100, 150], y: [0, 100, 150]});

// 4. Elements can be collected into groups and properties applied to the entire set

var g = new algo.render.ElementGroup();
g.add(e); g.add(f);
g.set({x: 100});

// 5. Elements always have a parent element, except the root element which belongs to the surface.
//    Elements inherit properties (other than text) from their parent and their position is always relative to
//    their parent. The children of an element are an instance of algo.render.ElementGroup so you can apply
//    properties to all the children of an element thus:

var h = new algo.render.Element({parent: e});
e.children.set({w: 100});

// 6. An elements properties AND its children's properties can be set to any depth i.e. any distance down
//    the parent -> child hierarchy by supply a depth parameter as the final argument to set.
//    For example to set the properties of element e and its children and its children children we could do:

e.set({x: 100}, 2);



Properties set into an element are applied directly to the object so that can subsequently be accessed using dot notation e.g.

var width = someElement.w

Properties set into an element do not necessarily have to be algomation ones. You can associate any key / value pair with elements so long as the names do not conflict the values used by the API e.g.

someElement.set({"yourStringProperty" : "ABC"});

Element States

As a final conveinence you can create sets of named properties and then apply them all at once with a name e.g.

// Creating custom states

var e = new algo.render.Rectangle();

e.addStates([
    {
        name      : "WHITE_STATE",
        properties: {fill: algo.Color.iWHITE, stroke: algo.Color.iBLUE, pen: algo.Color.iBLUE}
    },
    {
        name      : "FADED_STATE",
        properties: {fill: algo.Color.iWHITE, stroke: algo.Color.iGRAY, pen: algo.Color.iGRAY}
    }
]);

// Applying states

e.set({state: "WHITE_STATE"});

e.set({state: "FADED_STATE"});

// NOTE: There are several predefined states available on all elements. They are defined thus:

e.addStates([
    {
        name      : algo.render.kS_NORMAL,
        properties: {fill: algo.Color.iWHITE, stroke: algo.Color.iBLUE, pen: algo.Color.iBLUE}
    },
    {
        name      : algo.render.kS_FADED,
        properties: {fill: algo.Color.iWHITE, stroke: algo.Color.iGRAY, pen: algo.Color.iGRAY}
    },
    {
        name      : algo.render.kS_BLUE,
        properties: {fill: algo.Color.iBLUE, stroke: algo.Color.iBLUE, pen: algo.Color.iWHITE}
    },
    {
        name      : algo.render.kS_GRAY,
        properties: {fill: algo.Color.iGRAY, stroke: algo.Color.iGRAY, pen: algo.Color.iWHITE}
    },
    {
        name      : algo.render.kS_ORANGE,
        properties: {fill: algo.Color.iORANGE, stroke: algo.Color.iORANGE, pen: algo.Color.iWHITE}
    },
    {
        name      : algo.render.kS_RED,
        properties: {fill: algo.Color.iRED, stroke: algo.Color.iRED, pen: algo.Color.iWHITE}
    },
    {
        name      : algo.render.kS_GREEN,
        properties: {fill: algo.Color.iGREEN, stroke: algo.Color.iGREEN, pen: algo.Color.iWHITE}
    },
    {
        name      : algo.render.kS_CYAN,
        properties: {fill: algo.Color.iCYAN, stroke: algo.Color.iCYAN, pen: algo.Color.iWHITE}
    }
]);

Yielding

The main loop of the array reversal algorithm is this:

//=swap
while (left < right) {

    yield ({
        step: "Exchange the items in the slots identified by the left and right variables.",
        line: "//=swap",
        variables: {
            left: left,
            right: right
        }
    });

    // swap the two items on the array and reposition their elements
    varray.swap(left, right);

    yield ({
        autoskip: true
    });

    // move left and right indices towards the center of the array
    left += 1;
    right -= 1;
}

The algorithm itself is of course trivial. Using two indices, one to the left end of the array and another to the right end of the array we swap elements at those locations and increment and decrement the indices respectively. When the left and right indexes meet or pass each other the swap loop terminates. The actual line that performs the swap is:

varray.swap(left, right);

As described above this single call triggers callbacks to our code that in turn update the position of elements used to display the array used the 'set' API common to all elements. The new part of of the code above are the two yield statements.

Yield Statement

The appropriate placement of yield points within your code is essential to creating attractive and illuminating algorithms on algomation.com

Yield statements pause your algorithm and update the display to reflect any changes made to the display since the last yield point or the beginning of the algorithm. In the algorithm player the user will have to click 'Continue' to resume your algorithm unless they are running in 'Continuous' mode in which case your algorithm will resume after a short period of time depending on the speed selected for the player.

Yield statements can be parameterized with a literal object containing zero or more of the following options.

yield({

    // The 'step' parameter is a text message that is
    // displayed to the user in the messages window.

    step: _.sprintf("The left index is now %d.", leftIndex),

    // The 'line' parameter identifies the location
    // in your algorithm source code relevant to this yield.
    //
    // You can specify a line number e.g. line: 210 but that
    // is rather inflexible since the line number
    // will change as you edit the code.

    // The better solution is to use a string label.
    // String labels are single line comments that begin with '//='
    // followed by your label.

    // The JavaScript editor that is part of the algorithm
    // player will automatically scroll to show the appropriate
    // line if you include a line parameter as part of your yield.

    //=first yield
    line: "first yield",
    line: 432,

    // variables are used to display values from within
    // your algorithm relevant to this yield point.
    // Variables are simple key / value pairs displayed
    // in the messages panel of the player. The key names
    // do not have to be valid JavaScript syntax

    variables: {
        "Left"     : leftIndex,
        "Right"    : rightIndex,
        "End Point": rightIndex - leftIndex
    },

    // In certain context you may want to update the
    // users without actually pausing. If you algorithm have
    // many significant steps and clicking through each one
    // would be tedious you can simple set
    // autoSkip to true. The yield will be treated as
    // though the user were running in continuous mode regardless
    // of their player mode.

    autoSkip: true

});

Running and Debugging

We have reviewed the anatomy of an entire algorithm. We will now covers the various ways to run and debug your algorithms. The first and simplest way is simple to click the 'Release Test' button the editor toolbar. This will open a new window containing an instance of the algomation algorithm player and will automatically load and run your algorithm in continuous mode.

All algorithms are transpiled before running to ensure that they can run on browsers without support for the latest version of JavaScript ( ECMAScript 6 / Harmony ). If any syntax errors are noted during this transpilation phase they will be reported to you via a modal dialog box

You must locate and fix any syntax errors before your algorithm can be loaded and run on in the player.

Syntax Errors

The ACE code editor, upon which the algomation IDE editor is based provided full support for flagging errors and warnings about your code. Markers will appear in the left hand gutter for any errors discovered as your edit your code. Warnings will also appear although your algorithm may run fine even with warnings present.

Exceptions

If your algorithm throws any unhandled exceptions during execution they will be reported to you in a modal dialog that appears above the player window. The nature of the exception and a full stack trace is included to help you locate and fix the problem.

Your algorithm is always loaded via an API and can easily be identified by the same ID/GUID as is present in the address bar of your browser. In the above example the exception originated in the algorithm at line 79, column, 22 as indicated by:

(http://algomation.com/api/v1/source/53fb1a1c64302d98258065c5:79:22)

Debugging Prerequisites

Of course waiting for exceptions to occur and attempting to fix them from a stack trace has it limitations as an engineering practise. Fully interactive runs of your algorithm within a debugging environment are usually the best way to fix problems and ensure that your code is running as expected.

To debug your algorithm you will want to run the algomation IDE from a browser that has support for debugging web workers and has native support for ECMAScript 6. At the time of writing ( August 25th 2014 ) there is only one candidate and that is Chrome Canary from Google. Unfortunately all other major browser either lack support for debugging web workers or cannot run ECMAScript 6 ( without algomation transpiling it to ECMAScript 5 ). You can read about and download Chrome Canary here:


Chrome Canary

ECMAScript 6

Algomation will preferentially load your unmodified source code on browsers that support ECMAScript 6 while the transpiled version will be loaded on other browsers. Debugging with the transpiled code is possible but not recommended since your code will look substantially different.

Even when running Chrome Canary you must first enable ECMAScript 6 support. To do this simple point your browser at the url 'chrome://flags' and locate the 'Enable Experimental JavaScript' flag and enable it.

Now you are ready to start debugging your algorithm. Start by clicking the "Debug Test" button on the editor pages main toolbar. Your algorithm will open in a new stripped down version of the player that does not automatically start your algorithm.

You should open the Chrome Debugger using the appropriate keyboard short cut for your operating system. On my Mac that is [ Command Key + Option Key + i ]. Upon opening the debugger you should select the 'Sources' tab. In the left panel of the debugger are all the files that Chrome has loaded for the current page. Double click and open the file that is under: www.algomation.com/api/v1/source/[ALGORITHM GUID]. Now your debugger should look something like the following image:

In the center panel you will see the full source code of your algorithm. Set break points by clicking in the left gutter of the source code in this panel. To reach the break point return to the player and click the 'Continue' button to move your algorithm to the next yield point or select 'Continuous' play mode.

To restart your algorithm either click "Debug Test" again in the IDE window, or select "Restart Algorithm" from the options menu on the player or simple refresh the page containing your algorithm with the page refresh shortcut for your operating system [ Command + Shift + R ] on Mac based browsers.

The Chrome debugger has excellent support for breakpoints, conditional break points, watch windows, stack traces and all the usual debugging features of a AAA environment. You can find a good introduction to its capabilities here:


Chrome JavaScript Debugger

You can safely ignore all the features of the Chrome Debugger that related to HTML Documents, CSS and other mundanities of web development since those are only for the wretched soles who make a living creating web sites. As a pure algomation developer the JavaScript sources panel is your only concern.

Stepping Through Code

To debug your algorithm set a break point at an appropriate location and continue running your algorithm. Eventually your breakpoint will be reached and you can begin inspecting variables using the debugging and fixing problems. One important thing to note is that when stepping over yield statements you will need to return to the player and click continue before control is passed back to the debugger.

Once you have identified a problem in your code you can simple fix it in the algomation editor and click "Debug Test" once again to reload the algorithm in the player. Chrome will remember any breakpoints that you previously set so you can confirm that the problem is fixed when you once again reach that point in your code.

Debugging Roadmap

Chrome permits you to install extensions to the browser. One feature of such extensions is the ability to creating debugging sessions. I hope in the near future to create such an extension. That will allow settings of breakpoints directly from the Algomation IDE.

Summary

That ends this introduction to Algomation.com. We have reviewed how to find, view, create and debug algorithms. If there is anything I can do to improve the experience on the site and help you to create powerful visualizations of algorithms do please let me know via the feedback page.

Algorithm Help

If you have read through this guide and are having problems writing or debugging an algorithm on the site please send me a link to your algorithm via the feedback page. I'd be happy to try and help you solve any problems you encounter.

Thanks for visiting the site. - Duncan Meech