Skip to content

Instantly share code, notes, and snippets.

@russellsamora
Last active March 9, 2020 19:32
Show Gist options
  • Save russellsamora/0c95e012e572411427549100cafc5e70 to your computer and use it in GitHub Desktop.
Save russellsamora/0c95e012e572411427549100cafc5e70 to your computer and use it in GitHub Desktop.
make this FAST
const d3 = require("d3");
const MersenneTwister = require("mersenne-twister");
const generator = new MersenneTwister();
/*
generate random attempts at playing a correct sequence of notes,
given a range of midi (note) and duration options
*/
function generateAttempts({ range, sequence, iterations }) {
const answer = sequence.map(d => `${d.midi}-${d.duration}.`).join("");
const { midis, durations } = range;
midis.sort(d3.ascending);
durations.sort(d3.ascending);
const mL = midis.length;
const dL = durations.length;
// this is where the magic happens (ie optimization needed)
const makeAttempt = () => {
const seq = sequence.map(() => {
const mR = midis[Math.floor(generator.random() * mL)];
const dR = durations[Math.floor(generator.random() * dL)];
return [mR, dR];
});
const a = seq.map(d => `${d[0]}-${d[1]}.`).join("");
done = a === answer;
return { seq, done };
};
const output = [];
let i = 0;
while (i < iterations) {
// store the 1000 most recent attempts
const a = makeAttempt();
output[i % 1000] = a;
if (a.done) break;
i += 1;
}
return { output, done, attempts: i };
}
function init() {
// INPUT
const range = { midis: [73, 64, 66, 74], durations: [1, 2, 3] };
const sequence = [
{ midi: 73, duration: 1 },
{ midi: 64, duration: 2 },
{ midi: 66, duration: 3 },
{ midi: 66, duration: 1 },
{ midi: 74, duration: 2 },
{ midi: 73, duration: 2 },
{ midi: 66, duration: 1 }
];
const iterations = 1000000;
const result = generateAttempts({ range, sequence, iterations });
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment