I'm not quite sure of the word to use here so excuse me if I'm using the wrong terminology.
I'm trying create a function to get the next permutation of a string giving the current string and a string of allowable characters.
For example
<pre>
<?php
$current = '';
$allowed = 'ab';
function next(&$current, &$allowed) {
// This is where I need help
}
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
Should return
a
b
aa
ab
ba
bb
aaa
aab
aba
abb
baa
bab
bba
bbb
aaaa
...and so on
I'm trying to do this in both PHP and JavaScript so I would be grateful for help in 开发者_如何学Pythoneither language.
function nextPermutation(&$current, $allowed) {
if (empty($current)) {
$current = $allowed[0];
} else {
for ($i = strlen($current) - 1; $i >= 0; $i--) {
$index = strpos($allowed, $current[$i]);
if ($index < strlen($allowed) - 1) {
$current[$i] = $allowed[$index + 1];
break;
} else {
$current[$i] = $allowed[0];
if ($i == 0) {
$current = $allowed[0] . $current;
break;
}
}
}
}
return $current;
}
精彩评论