Skip to content

Instantly share code, notes, and snippets.

@newfurniturey
Created June 14, 2014 21:01
Show Gist options
  • Save newfurniturey/0063c9580553226ab36a to your computer and use it in GitHub Desktop.
Save newfurniturey/0063c9580553226ab36a to your computer and use it in GitHub Desktop.
Alphabet permutations without arrays or recursion
<?php
$string_len = 5;
$alphabet = 'abc';
$alphabet_len = strlen($alphabet);
for ($s = 1; $s <= $string_len; $s++) {
$current_key = str_repeat($alphabet[0], $s);
$num_combinations = pow($alphabet_len, $s);
$i = 0;
while ($i++ < $num_combinations) {
printf('%s<br />', $current_key);
$alphabet_index = $i % $alphabet_len;
$current_key[0] = $alphabet[$alphabet_index];
if (($alphabet_index === 0) && ($s !== 1)) {
$key_index = 1;
$alphabet_index = (strpos($alphabet, $current_key[$key_index]) + 1) % $alphabet_len;
$current_key[$key_index] = $alphabet[$alphabet_index];
printf('$current_key[%d] = $alphabet[%d], %d = %s<br />', $key_index, $alphabet_index, $key_index, $alphabet[$alphabet_index]);
if ($alphabet_index === 0) {
$key_index = ($key_index + 1) % $s;
while ($key_index > 0) {
$alphabet_index = (strpos($alphabet, $current_key[$key_index]) + 1) % $alphabet_len;
$current_key[$key_index] = $alphabet[$alphabet_index];
printf('$current_key[%d] = $alphabet[%d], %d = %s<br />', $key_index, $alphabet_index, $key_index, $alphabet[$alphabet_index]);
$key_index = ($key_index + 1) % $s;
if ($alphabet_index !== 0) break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment