write an algorithm that generates interesting rhythmic patterns
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I'm designing a simple memory game in which the player is asked to remember a rhythmic pattern and then to repeat it after some delay. I'd like to include a wide variety of rhythmic patterns that vary in difficulty. In the game code, written in javascript, a pattern is represented as an array of durations, in ms, that the sound is held on or off. For example, a pattern that alternates on-off-on-off, switching once per second, would be represented as [1000,1000,1000,0]. As a convention, pattern arrays always begin with the timing for the first 'on' event and end with zero. They always have an even number of elements.

For this bounty, please provide a javascript function that returns an interesting rhythmic pattern. It should have the ability to generate several patterns (e.g., don't just hard code one or two arrays). I have included an example below. I will tip $1 for every unique and interesting function, not just to the first person to respond.

function generate_pattern(len) {
  var choices = new Array(250,500);
  var pat = new Array();
  for(var i = 0; i < (len*2 - 1); i++) {
    pat.push(choices[Math.floor(Math.random() * choices.length)]);
  }
  pat.push(0);
  return pat
}
awarded to Wikimedia

Crowdsource coding tasks.

1 Solution


// it generates rhythm t/s
// t should be less then s
function generate_pattern(s, t) {
var choices = [];
var pat = [];
for (var i = 0; i < t; i++) {
choices.push(250);
}
for (var k = 0; k < s-t; k++) {
choices.push(500);
}
for (var j = 0; j < s; j++) {
var n = Math.floor(Math.random() * choices.length);
pat.push(choices[n]);
choices.splice(n, 1);
}
pat.push(0);
return pat;
}