2011-02-15 6 views
0

잘못된 용어를 사용하는 경우 여기에 사용할 단어가 너무 실용적이지 않으므로 실례합니다.모든 (다음) 부분 집합 또는 순열 가져 오기

나는 순열 문자열을 현재 문자열과 허용되는 문자열을주는 함수를 만들려고합니다. 예를

를 들어

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

내가 그래서 감사 것 PHP와 자바 스크립트 모두에서이 작업을 수행하기 위해 노력하고있어

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

... 그래서

에 반환해야합니다 각 언어로 도움을 청하십시오.

+0

'next()'는 PHP의 빌드 - 인 함수 이름이므로 확실히 사용할 수 없습니다. – Spudley

+0

@ Spudley, 어떤 네임 스페이스가 필요한가요? – Petah

답변

0
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; 
} 
관련 문제