Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Bjorklund algorithm in JavaScript

View bjorklund.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
/*
An implementation of the Bjorklund algorithm in JavaScript
Inspired by the paper 'The Euclidean Algorithm Generates Traditional Musical Rhythms'
by Godfried Toussaint

This is a port of the original algorithm by E. Bjorklund which I
found in the paper 'The Theory of Rep-Rate Pattern Generation in the SNS Timing Systems' by
E. Bjorklund.
Jack Rutherford
*/
 
 
function bjorklund(steps, pulses) {
steps = Math.round(steps);
pulses = Math.round(pulses);
 
if(pulses > steps || pulses == 0 || steps == 0) {
return new Array();
}
 
pattern = [];
counts = [];
remainders = [];
divisor = steps - pulses;
remainders.push(pulses);
level = 0;
 
while(true) {
counts.push(Math.floor(divisor / remainders[level]));
remainders.push(divisor % remainders[level]);
divisor = remainders[level];
level += 1;
if (remainders[level] <= 1) {
break;
}
}
counts.push(divisor);
 
var r = 0;
var build = function(level) {
r++;
if (level > -1) {
for (var i=0; i < counts[level]; i++) {
build(level-1);
}
if (remainders[level] != 0) {
build(level-2);
}
} else if (level == -1) {
pattern.push(0);
} else if (level == -2) {
pattern.push(1);
}
};
 
build(level);
return pattern.reverse();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.