## See the DEMO

Requires WebKit Browser, i.e. Chrome, Firefox, Safari

Recently, while at a job interview, the interviewer posed an interesting problem. Could I, in any language, write code to generate a counter clockwise spiral of numbers from the center and radiating out to the edge.

In my limited time, I worked through the problem on a dry erase marker board, and figured out the basics. I got nowhere near the answer though. “Obviously,” he remarked, “I’m not expecting you to have the answer in the limited time we have today.” He was mostly trying to see my process for working through a problem.

Mind you, whenever you give me an interesting problem, my brain tends to get stuck in analysis mode. That evening, I used my GoogleFu to discover that this particular pattern was known as a Ulam Spiral.

The Ulam Spiral, or Prime Spiral, Prime Number Spiral or Ulam Cloth, was devised by Stanislaw Ulam in 1963, while bored during a lecture (the mind reels at what it takes to make a mathematician bored), who started doodling on a piece of paper.

What makes the Ulam Spiral interesting is the odd way that prime numbers reveal themselves on the grid over time, often apparently organizing themselves into diagonal lines (they still haven’t found an explanation for this). For more on the Ulam Sprial, check out the Wikipedia entry.

I found a number of places where the math was laid out, I even found a number of programs designed to teach the concept to math classes, but no where, did I find anyone who had written a solution, let alone one in HTML.

Challenge accepted!

I had an interesting weekend, without a lot of time to focus on the issue, but finally Sunday evening, I was able to sit down and play with it.

Here is the code in it’s entirety. I’ll break it down later:

<html> <head> <title>Ulam Spiral Generator with jQuery</title> <meta name="description" content="Ulam Spiral Generator written with jQuery. The Ulam Spiral is also know as the Ulam Cloth."> <!-- I like to use cdn's whenever possible --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <style> * { font-family: Arial; } td { width: 50px; height: 50px; text-align: center; border-style:solid; border-width:1px; border-radius: 5px; } #spiral { width: 100%; margin: auto; } .prime { color: #fff; background-color: #666; } </style> </head> <body> <script> $(document).ready(function() { // Apply the class numericOnly to any html input to force it to only accept numbers // this class function isn't currently used on this page, but I find it handy to keep around $("input.numericOnly").bind('keypress', function (e) { return ( e.which != 13 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46) ? false : true; }); // we assign the class "true" to the table when we find prime numbers, we just toggle the class the reveal the prime numbers $("#showprimes").on('click', function () { $(".true").toggleClass("prime"); }); // we'll update the div when the slider is updated so the user has feedback $('#cols').change(function() { var x = $(this).val(); $('#output').text(x); }); }); function submit_num() { // remove any td from previous $("#ulam td").remove(); $("#ulam tr").remove(); var cells = []; var x = 0, y = 0, delta = [0, -1], cols = $("#cols").val(); maxsize = cols*cols; for (i = 1; i <= maxsize; i++) { cells[i] = {}; // I know I didn't have to add maxsize to the value, I just don't naturally visualize negative numbers cells[i]['row'] = y + maxsize; cells[i]['col'] = x + maxsize; cells[i]['dat'] = i; prime = isPrime(i); cells[i]['pri'] = prime; //console.debug('POINT ', i, y + maxsize, x + maxsize); if (x === y || (x < 0 && x === -y) || (x > 0 && x === 1-y)){ // change direction delta = [-delta[1], delta[0]] } x += delta[0]; y += delta[1]; } // Now we sort the array based on row, then column, this actually stumped me for a bit, I'm not used // to sorting arrays on two fields, but fortunately, as usual, stackoverflow to the rescue cells.sort( function(a,b){ if (a.row != b.row) { return b.row - a.row; } return a.col - b.col }); var trackrows = cells[1]['row']; for (j = 0; j < maxsize; j++) { if (trackrows != cells[j]['row']) { // we need to close previous rows and start a new one if the row number changes // I'm thinking about rewriting this using ul, li trackrows = cells[j]['row']; $("#ulam").append('</tr><tr>'); } console.log('POINT ', cells[j]['dat'], cells[j]['row'], cells[j]['col']); $("#ulam").append('<td class="'+cells[j]['pri']+'">'+cells[j]['dat']+'</td>'); } } function isPrime(num) { var prime = num != 1; // Everything but 1 can be prime for (var i = 2; i < num; i++) { if (num % i == 0) { prime = false; break; }; }; return prime; }; </script> <div id="spiral"> <h2>Ulam Spiral Generator</h2> <p><a href="http://www.tangledwebsites.com/homework-assignment-a-ulam-spiral-generator/">Read the blog post</a></p> <table> <tbody id="ulam"> </tbody> </table> <form onsubmit="submit_num();"> <p>Use the slider to select the of rows/columsns you would like.<br /> <input id="cols" type="range" min="9" max="20" value="9" /> <input type="button" value="Go" onclick="submit_num();" /><br /> <span id="output">9</span><br /> <input id="showprimes" type="button" value="Toggle Primes" /> </form> </div> </body> </html> |

So this is complex, but far simpler than I had originally thought. Let’s walk through the pieces.

The very first thing I do, is include the Google CDN for jQuery.

<html> <head> <!-- I like to use cdn's whenever possible --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> |

Then I define some really basic styles:

<style> * { font-family: Arial; } td { width: 50px; height: 50px; text-align: center; border-style:solid; border-width:1px; border-radius: 5px; } #spiral { width: 100%; margin: auto; } .prime { color: #fff; background-color: #666; } </style> </head> |

The next little bits are just two jQuery functions that we will use later.

```
<script>
$(document).ready(function() {
// we assign the class "true" to the table when we find prime numbers, we just toggle the class the reveal the prime numbers
$("#showprimes").on('click', function () {
$(".true").toggleClass("prime");
});
// we'll update the div when the slider is updated so the user has feedback
$('#cols').change(function() {
var x = $(this).val();
$('#output').text(x);
});
});
``` |

I’ll explain the core function in Part Two of this posting.

## See the DEMO

Requires WebKit Browser, i.e. Chrome, Firefox, Safari