Quicksort is a computer algororithm for sorting a collection of items. In this example, we sort a random collection of notes from
C minor
and convert each comparison operation into a note event. Representing events as musical notes is one common tool of sonifiers.(this example presently requires that hanoi also be copied).
The basic audio setup for is a clone of that described in the
hanoi example. In fact we rely on kick.wav
that
is present in that example so to run this example you must "install"
both this and hanoi by the right-click-to-copy command.
Here we'll highlight portion of the entire solution but leave it to you to inspect the example code in detail.
First we produce a random collection of notes from a scale using the Tonal.js module.
// Create a range of notes from a scale. Repeat them, then shuffle.
let notes = Tonal.Scale.rangeOf("C Minor")("C2", "C6")
.map((nm) => Tonal.Note.midi(nm));
let manyNotes = repeat(notes, 5); // local function to repeat our notes
shuffle(manyNotes); // local function to shuffle the array of notes.
Next we install a callback for sort
's comparison callback where
we stash the comparison for conversion to notes. He we only stash
one of the two notes, you can imagine that doing something with both
notes might produce interesting results.
let noteList = [];
manyNotes.sort((a, b) =>
{
if(a < b)
ret = -1;
else
if(b > a)
ret = 1;
else
ret = 0;
noteList.push([a, .9, dur, nextTime]);
nextTime += intervalDur;
return ret;
});
Finally we schedule the note-events, noteList
, for performance. Here we use
Anode.Note to
schedule a note for a future time.
console.log(`Sorting ${manyNotes.length} notes produced ${noteList.length} events.`);
for(let i=0;i<noteList.length;i++)
{
let [key, vel, dur, when] = noteList[i];
inst.Note(key, vel, dur, when);
if(i%4 == 0)
drum.Note(1, .6, dur, when);
await scene.Wait(.9*dur);
yield;
}