Last active
February 15, 2017 16:54
-
-
Save miou-gh/df135239f9a82ed110c639c3eb563a56 to your computer and use it in GitHub Desktop.
Generate a Random Pronouncable Word
This file contains 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
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