【问题标题】:Get all (next) subsets or permutations (or something)获取所有(下一个)子集或排列(或其他)
【发布时间】:2011-02-15 12:14:03
【问题描述】:

我不太确定在这里使用的词,如果我使用了错误的术语,请原谅。

我正在尝试创建一个函数来获取一个字符串的下一个排列,给出当前字符串和一个允许字符的字符串。

例如

<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";

应该返回

a
b
aa
ab
ba
bb
aaa
aab
aba
abb
baa
bab
bba
bbb
aaaa

...等等

我正在尝试在 PHP 和 JavaScript 中执行此操作,因此我将不胜感激任何一种语言的帮助。

【问题讨论】:

  • next() 是 PHP 中的内置函数名,所以你绝对不能使用它。
  • @Spudley,这就是命名空间的用途

标签: php javascript set permutation


【解决方案1】:
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;
}

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 2012-01-14
    • 2012-06-01
    • 2020-02-17
    • 2011-04-30
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    相关资源
    最近更新 更多