Daily Programmer Challenge #174: Thue-Morse Sequences
My submission to: http://www.reddit.com/r/dailyprogrammer/comments/2cld8m/8042014_challenge_174_easy_thuemorse_sequences/
by pendensproditor
HTML
<ol id="results" start="0"></ol>
CSS
li {
padding-bottom: 5px;
font: 10px/125% monospace;
word-break: break-all;
}
JavaScript
// Below is the result we should get for the 0-6th order sequences:
// 0 - 0
// 1 - 01
// 2 - 0110
// 3 - 01101001
// 4 - 0110100110010110
// 5 - 01101001100101101001011001101001
// 6 - 0110100110010110100101100110100110010110011010010110100110010110
(function (window, document) {
'use strict';
var results = document.getElementById('results'),
sequence,
order,
interval,
limit = 20, // How many sequences can we generate before this crashes?
initSequence = function () {
sequence = [false];
order = 1;
results.innerHTML = '<li>0</li>';
interval = window.setInterval(function () {
window.requestAnimationFrame(runIteration);
}, 200);
},
appendComplementToSequence = function () {
var complement = [];
for (var i = 0, l = sequence.length; i < l; i++) {
complement.push(!sequence[i]);
}
sequence = sequence.concat(complement);
},
printSequence = function () {
var sequenceHtml = '<li>';
for (var i = 0, l = sequence.length; i < l; i++) {
sequenceHtml += (sequence[i] ? 1 : 0);
}
sequenceHtml += '</li>';
results.innerHTML += sequenceHtml;
},
runIteration = function () {
appendComplementToSequence();
printSequence();
if (++order > limit) window.clearInterval(interval);
};
initSequence();
})(this, document);