Skip to content

Instantly share code, notes, and snippets.

@miou-gh
Last active February 15, 2017 16:54
Show Gist options
  • Save miou-gh/df135239f9a82ed110c639c3eb563a56 to your computer and use it in GitHub Desktop.
Save miou-gh/df135239f9a82ed110c639c3eb563a56 to your computer and use it in GitHub Desktop.
Generate a Random Pronouncable Word
public static class RandomWord
{
private static List<string> Consonants = new List<string>() {
// single consonants. without 'q' since it's often awkward in words
"b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "r", "s", "t", "v", "w", "x", "z",
// possible combinations excluding those which cannot start a word
"pt", "gl", "gr", "ch", "ph", "ps", "sh", "st", "th", "wh",
};
private static List<string> ConsonantsSuffixes = new List<string>() {
// these consonants are to be avoided in the beginning of words
"ck", "cm", "dr", "ds", "ft", "gh", "gn", "kr", "ks", "ls",
"lt", "lr", "mp", "mt", "ms", "ng", "ns", "rd", "rg", "rs",
"rt", "ss", "ts", "tch",
};
private static List<string> Vowels = new List<string>() {
// single vowels
"a", "e", "i", "o", "u", "y",
// vowel combinations your language allows
"ee", "oa", "oo",
};
private enum Sound {
Consonant,
Vowel
};
public static string Generate(int length)
{
var currentSound = new[] { Sound.Consonant, Sound.Vowel }.Shuffle()[0];
var currentWord = "";
while (currentWord.Length < length) {
var rnd = "";
// random sign from either cons or vows,
// after the first letter, use every consonant combo
switch (currentSound) {
case Sound.Consonant:
rnd = currentWord.Length > 1 ?
Consonants.Concat(ConsonantsSuffixes).ToList().Shuffle()[0] :
Consonants.Shuffle()[0];
break;
case Sound.Vowel:
rnd = Vowels.Shuffle()[0];
break;
}
// check if random sign fits in word length
if (currentWord.Length + rnd.Length <= length) {
currentWord += rnd;
// alternate sounds
currentSound = currentSound == Sound.Consonant ?
Sound.Vowel : Sound.Consonant;
}
}
return currentWord;
}
}
public static class Helpers
{
public static T[] Shuffle<T>(this T[] list) => Shuffle(list.ToList()).ToArray();
public static IList<T> Shuffle<T>(this IList<T> list)
{
var provider = new RNGCryptoServiceProvider();
var n = list.Count;
while (n > 1) {
var box = new byte[1];
do
provider.GetBytes(box);
while (!(box[0] < n * (byte.MaxValue / n)));
var k = (box[0] % n);
n--;
var value = list[k];
list[k] = list[n];
list[n] = value;
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment