Skip to content

Instantly share code, notes, and snippets.

@igorw
Created January 4, 2015 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igorw/327b92441adc7be9acb0 to your computer and use it in GitHub Desktop.
Save igorw/327b92441adc7be9acb0 to your computer and use it in GitHub Desktop.
<?php
$permutations = [
['a', 'c', 'f'],
['b', 'd'],
['a', 'b', 'd'],
['e', 'f'],
];
/*
$permutations = [
['a', 'c', 'f'],
['b', 'd'],
];
*/
$chars = array_unique(call_user_func_array('array_merge', $permutations));
$chars = array_combine($chars, $chars);
$out = [];
$i = 0;
while (count($chars) > 0) {
$cycle = [];
$first = $current = current($chars);
do {
unset($chars[$current]);
foreach ($permutations as $permutation) {
$current = apply_permutation($permutation, $current);
}
$cycle[] = $current;
} while ($current !== $first);
$out[] = $cycle;
}
var_dump($out);
function apply_permutation($permutation, $current) {
foreach ($permutation as $i => $char) {
if ($char === $current) {
return $permutation[($i + 1) % count($permutation)];
}
}
return $current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment