2013-04-09 2 views
0

공백이있는 문자열이 있습니다. 나는 그것을 분해 (폭발)시켜야하고 그로부터 모든 변형 된 변이가있다. 예를 들면 :PHP에서 배열의 문자열의 모든 변형

나는 그것을 분석하고이 같은 출력을 얻을 필요가
string1 string2 string3

:

string1 string2 string3 
string1 string3 string2 
string2 string1 string3 
string2 string3 string1 
string3 string2 string1 
string3 string1 string2 

이 작업을 수행하는 가장 효율적인 방법은 무엇입니까?
편집 : 실제로 내가 최대 3 문자열을 구문 분석해야합니다. 그래서 나는 이것을 (하드 코딩 된) 예쁜 방법이 아니다.

 
$exploded_query = explode(' ', $query); 
if(count($exploded_query) == 2) { 
//2 variants 
} 
if(count($exploded_query) == 3) { 
//6 variants 
} 

그래서 나는 그것을 할 수있는 좋은 방법을 찾고있다.

+0

나는이 접근법으로 당신이 대답하려고하는 질문이 무엇이든간에 정말로 물어야한다고 생각합니다. 당신이 이미 모든 조합을 필요로한다고 명시했기 때문에 이것을 수행하는 효율적인 방법은 없습니다 * (특정 알고리즘의 가장 효율적인 구현은 실제로 실행해야하는 조합을 지능적으로 선택합니다. 가능한 경우 단락시킵니다). 즉, 이것에 대한 "가장 효율적인"접근법은 여전히 ​​n입니다! (n 계승). 단 10 개의 단어가 이미 3 백만 조합입니다. –

+0

게시 할 코드가 있습니까? – afuzzyllama

+0

예, 코드를 게시했습니다. – UnstableFractal

답변

1

이고, 그렇지 않으면

$index = 0; 
array_values(array_filter($words, function($key, &$index) { return !($key == $index++); })); 

: 당신이 (성능의 가능성이 약간의 비용으로) 약간의 팽창을 제거하려는 경우, 당신은 함께 getRemainingWords 함수 호출을 대체 할 수 배열의 순열

여기를보세요 ->Finding All Permutations of an Array, 그게 도움이됩니다.

0

나는 이것이 효율적이거나 최적이라고 주장하지 않습니다. 거기에 훨씬 더 나은 솔루션이 있습니다. 그러나 이것은 귀하의 질문에 대한 직접적인 대답 일뿐입니다. 여기 그것은이다

function getPossibleCombinations($words) { 
    $combinations = array(); 
    $count = count($words); 

    // Base case: if there's only 1 word, there's only one combination 
    if ($count == 1) { 
     return array($words); 
    } 

    // Otherwise, loop over each words 
    foreach ($words as $key=>$word) { 

     // For each item, get all of the remaining items in the array (all except the current one) 
     $otherWords = getRemainingWords($words, $key); 

     // And recursively permute them 
     $otherCombinations = getPossibleCombinations($otherWords); 
     foreach ($otherCombinations as $otherCombination) { 
      $combinations[] = array_merge(array($word), $otherCombination); 
     } 
    } 

    return $combinations; 
} 


function getRemainingWords($array, $index) { 
    $results = array(); 

    foreach ($array as $key=>$value) { 
     if ($key == $index) { 
      continue; 
     } 

     $results[] = $value; 
    } 

    return $results; 
} 
관련 문제