Skip to content

Instantly share code, notes, and snippets.

@veloxy
Created November 30, 2015 19:24
Show Gist options
  • Save veloxy/282f2416ce42c7f7fe70 to your computer and use it in GitHub Desktop.
Save veloxy/282f2416ce42c7f7fe70 to your computer and use it in GitHub Desktop.
Name generator based on markov process
<?php
function generateMarkovTable($names = [])
{
$table = [];
foreach ($names as $name) {
$letters = str_split($name);
foreach ($letters as $key => $letter) {
$letter = strtolower($letter);
if (!array_key_exists($key + 1, $letters)) {
continue;
}
$nextLetter = strtolower($letters[$key + 1]);
if (!(array_key_exists($letter, $table) && array_key_exists($nextLetter, $table[$letter]))) {
$table[$letter][$nextLetter] = 1;
continue;
}
$table[$letter][$nextLetter] = $table[$letter][$nextLetter] + 1;
}
}
return $table;
}
function generateMarkovName($table, $minLength = 3, $maxLength = 10)
{
$currentLetter = array_rand($table);
$text = [$currentLetter];
$length = mt_rand($minLength, $maxLength);
for ($i = 0; $i < $length; $i++) {
$nextLetter = getRandomWeightedElement($currentLetter, $table);
if (count($text) > 1) {
$previousLetter = $text[$i - 1];
while ($previousLetter == $nextLetter) {
$nextLetter = getRandomWeightedElement($currentLetter, $table);
}
}
$text[] = $nextLetter;
$currentLetter = $nextLetter;
}
return ucfirst(implode('', $text));
}
function getRandomWeightedElement($key, array $table)
{
if (array_key_exists($key, $table)) {
$weightedValues = $table[$key];
$rand = mt_rand(1, (int) array_sum($weightedValues));
foreach ($weightedValues as $key => $value) {
$rand -= $value;
if ($rand <= 0) {
return $key;
}
}
}
return array_rand($table);
}
$names = [
'vagrant',
'docker',
'database',
'node',
'javascript',
'google',
'bandwidth',
'cache',
'cookies',
'delete',
'spam',
'user',
'thread',
'scaleable',
'robot',
'radar',
'multitask',
'legacy',
'tech',
'solution',
'pixel',
'cloud',
'chrome',
'fire',
'Internet',
'Advanced',
'Augmented',
'virtual',
'Development',
'agile',
'opensource'
];
$table = generateMarkovTable($names);
echo PHP_EOL;
echo PHP_EOL;
for ($i=0; $i < 49; $i++) {
echo str_pad(generateMarkovName($table, 4, 7), 12) . '|' . ' ';
if (!($i%8)) {
echo PHP_EOL;
}
}
echo PHP_EOL;
echo PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment