Created
November 10, 2020 20:33
-
-
Save jcorbin/227b490311fea60c4a4cd620274ded19 to your computer and use it in GitHub Desktop.
simple markov-powered text corruptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @ts-check | |
/** | |
* Markov transition table on characters. | |
* Empty means "transparent", i.e let the underlying string through | |
* | |
* @typedef {Object<string, number>} Weights | |
* @typedef {Object<string, Weights>} Transitions | |
*/ | |
/** | |
* Steps through a transition table. | |
* | |
* @param {Transitions} table | |
* @param {string} c | |
*/ | |
function next(table, c) { | |
const poss = table[c]; | |
if (!poss) return ''; | |
let choice='', best=NaN; | |
for (const [char, weight] of Object.entries(poss)) { | |
const score = Math.pow(Math.random(), 1/weight); | |
if (isNaN(best) || score > best) | |
choice=char, best=score; | |
} | |
return choice; | |
} | |
const succ = { | |
'': {'!': 1, '@': 1, '?': 1, '.': 1}, | |
'!': {'@': 5, '': 3}, | |
'@': {'?': 5, '': 3}, | |
'?': {'!': 5, '': 3}, | |
'.': {'.': 5, '': 3}, | |
}; | |
/** @param {string} s */ | |
function corrupt(s) { | |
let state = next(succ, ''); | |
let r = ''; | |
for (let i=0; i<s.length; i++) { | |
state = next(succ, state); | |
r += state ? state : s[i]; | |
} | |
return r; | |
} | |
console.log(corrupt('hello')); | |
console.log(corrupt('world')); | |
console.log(corrupt('secret')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment