Skip to content

Instantly share code, notes, and snippets.

@SethVandebrooke
Created October 15, 2020 21:06
Show Gist options
  • Save SethVandebrooke/4ef0e9b553b43139a13a52a2d4accde2 to your computer and use it in GitHub Desktop.
Save SethVandebrooke/4ef0e9b553b43139a13a52a2d4accde2 to your computer and use it in GitHub Desktop.
Machine learning algorithm that learns underlying patterns in sequences and replicates them using frequency analysis
/**
* Machine learning algorithm that learns underlying patterns in sequences and replicates them using frequency analysis.
* AKA a markov chain XD
* @function
* @param {Array|Number} a A sequence or the length of a sequence to return
* @example
* // feed it a sequence to learn from
* m([1,1,2,3,3,2,1]);
* // have it generate a sequence 7 items long
* m(7);
* // feed it more sequences
* m([3,1,3,3,2,2]);
* m([5,2,7,2,3,6,1]);
* // try it again
* m(10);
*/
function m(a) {
if (Array.isArray(a)) {
if (!('d' in m)) m.d = {};
for(var i = 0, p = null; i < a.length; i++) {
(m.d[p]?m.d[p]:m.d[p]=[]).push(p=a[i]);
}
} else if ("number" == typeof a) {
for (var i = 0, p = null, o = []; i < a; i++) {
o.push(p=m.d[p][Math.floor(Math.random()*m.d[p].length)]);
}
return o;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment