순열 - 모든 가능한 숫자 세트
PHP순열 - 모든 가능한 숫자 세트
나는 0에서 8까지의 숫자를 가지고있다. 나는 그 숫자의 모든 가능한 세트, 각 세트는 모든 숫자를 사용해야하며, 각 숫자는 한 세트에서만 한 번만 발생할 수있다.
결과를 인쇄 할 수있는 PHP 솔루션을보고 싶습니다. 또는, 나는 오랫동안 그것을 잊어 버렸기 때문에, 적어도 combinatorics의 이론에서 약간의 다과를 원합니다. 순열의 수를 계산하는 공식은 무엇입니까?
예제 세트 :
해결법
-
==============================
1.당신은 순열 공식을 찾고 있습니다 :
당신은 순열 공식을 찾고 있습니다 :
nPk = n!/(n-k)!
귀하의 경우 9 개의 항목이 있으며 모두 선택할 수 있습니다. 9P9 = 9입니다! = 362880
O'Reilly의 "PHP Cookbook"의 레시피 4.26에서 PHP 알고리즘을 찾을 수 있습니다.
pc_permute(array(0, 1, 2, 3, 4, 5, 7, 8));
오라일리에서 복사 :
function pc_permute($items, $perms = array( )) { if (empty($items)) { print join(' ', $perms) . "\n"; } else { for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); pc_permute($newitems, $newperms); } } }
-
==============================
2.PHP 5.5 이후 Generators를 사용할 수 있습니다. 생성기는 많은 메모리를 절약하고 속도가 빠릅니다 (pc_permute ()와 비교하여 절반 이상). 따라서 PHP 5.5를 설치할 수있는 기회가 있다면 확실히 Generators가 필요합니다. 이 조각은 파이썬에서 이식되었습니다 : https://stackoverflow.com/a/104436/3745311
PHP 5.5 이후 Generators를 사용할 수 있습니다. 생성기는 많은 메모리를 절약하고 속도가 빠릅니다 (pc_permute ()와 비교하여 절반 이상). 따라서 PHP 5.5를 설치할 수있는 기회가 있다면 확실히 Generators가 필요합니다. 이 조각은 파이썬에서 이식되었습니다 : https://stackoverflow.com/a/104436/3745311
function permutations(array $elements) { if (count($elements) <= 1) { yield $elements; } else { foreach (permutations(array_slice($elements, 1)) as $permutation) { foreach (range(0, count($elements) - 1) as $i) { yield array_merge( array_slice($permutation, 0, $i), [$elements[0]], array_slice($permutation, $i) ); } } } }
샘플 사용법 :
$list = ['a', 'b', 'c']; foreach (permutations($list) as $permutation) { echo implode(',', $permutation) . PHP_EOL; }
산출:
a,b,c b,a,c b,c,a a,c,b c,a,b c,b,a
-
==============================
3.이 질문은 종종 Google 검색 결과에 나타나므로 배열의 모든 조합을 반환하고 함수의 반환 값으로 전달하는 허용 된 답변의 수정 된 버전을보실 수 있습니다.
이 질문은 종종 Google 검색 결과에 나타나므로 배열의 모든 조합을 반환하고 함수의 반환 값으로 전달하는 허용 된 답변의 수정 된 버전을보실 수 있습니다.
function pc_permute($items, $perms = array( )) { if (empty($items)) { $return = array($perms); } else { $return = array(); for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); $return = array_merge($return, pc_permute($newitems, $newperms)); } } return $return; }
사용:
$value = array('1', '2', '3'); print_r(pc_permute($value));
-
==============================
4.네가 좋아할만한 뭔가가있어.
네가 좋아할만한 뭔가가있어.
function combination_number($k,$n){ $n = intval($n); $k = intval($k); if ($k > $n){ return 0; } elseif ($n == $k) { return 1; } else { if ($k >= $n - $k){ $l = $k+1; for ($i = $l+1 ; $i <= $n ; $i++) $l *= $i; $m = 1; for ($i = 2 ; $i <= $n-$k ; $i++) $m *= $i; } else { $l = ($n-$k) + 1; for ($i = $l+1 ; $i <= $n ; $i++) $l *= $i; $m = 1; for ($i = 2 ; $i <= $k ; $i++) $m *= $i; } } return $l/$m; } function array_combination($le, $set){ $lk = combination_number($le, count($set)); $ret = array_fill(0, $lk, array_fill(0, $le, '') ); $temp = array(); for ($i = 0 ; $i < $le ; $i++) $temp[$i] = $i; $ret[0] = $temp; for ($i = 1 ; $i < $lk ; $i++){ if ($temp[$le-1] != count($set)-1){ $temp[$le-1]++; } else { $od = -1; for ($j = $le-2 ; $j >= 0 ; $j--) if ($temp[$j]+1 != $temp[$j+1]){ $od = $j; break; } if ($od == -1) break; $temp[$od]++; for ($j = $od+1 ; $j < $le ; $j++) $temp[$j] = $temp[$od]+$j-$od; } $ret[$i] = $temp; } for ($i = 0 ; $i < $lk ; $i++) for ($j = 0 ; $j < $le ; $j++) $ret[$i][$j] = $set[$ret[$i][$j]]; return $ret; }
사용 방법은 다음과 같습니다.
조합 수를 얻으려면 다음을 수행하십시오.
combination_number(3,10); // returns number of combinations of ten-elements set.
모든 가능한 조합을 얻으려면 :
$mySet = array("A","B","C","D","E","F"); array_combination(3, $mySet); // returns all possible combinations of 3 elements of six-elements set.
희망을 사용하십시오.
-
==============================
5.이것이 나의 수업이다. 이 클래스는 순열 된 배열을 결과로 빌드하여 반환합니다.
이것이 나의 수업이다. 이 클래스는 순열 된 배열을 결과로 빌드하여 반환합니다.
class Permutation { private $result; public function getResult() { return $this->result; } public function permute($source, $permutated=array()) { if (empty($permutated)){ $this->result = array(); } if (empty($source)){ $this->result[] = $permutated; } else { for($i=0; $i<count($source); $i++){ $new_permutated = $permutated; $new_permutated[] = $source[$i]; $new_source = array_merge(array_slice($source,0,$i),array_slice($source,$i+1)); $this->permute($new_source, $new_permutated); } } return $this; } } $arr = array(1,2,3,4,5); $p = new Permutation(); print_r($p->permute($arr)->getResult());
수업을 테스트하기위한 마지막 세 줄.
-
==============================
6.이것은 순열 (pseudocode)로 쓰여진 모든 순열 (permutations)을 출력하는 간단한 재귀 함수이다.
이것은 순열 (pseudocode)로 쓰여진 모든 순열 (permutations)을 출력하는 간단한 재귀 함수이다.
function rec(n, k) { if (k == n) { for i = 0 to n-1 print(perm[i], ' '); print('\n'); } else { for i = 0 to n-1 { if (not used[i]) { used[i] = true; perm[k] = i; rec(n, k+1); used[i] = false; } } } }
그리고 이렇게 호출됩니다 :
rec(9, 0);
-
==============================
7.사전 순서. 재귀가 없습니다. 배열 길이에 거의 제한이 없습니다. 아무 종류도 없다. 오히려 빨리 달리고 있어요. 이해하기 쉽습니다. 빼기 : 경고를 표시하지만 조건을 추가하여 두 번째 요소 또는 error_reporting (0)과 비교를 시작할 수 있습니다.
사전 순서. 재귀가 없습니다. 배열 길이에 거의 제한이 없습니다. 아무 종류도 없다. 오히려 빨리 달리고 있어요. 이해하기 쉽습니다. 빼기 : 경고를 표시하지만 조건을 추가하여 두 번째 요소 또는 error_reporting (0)과 비교를 시작할 수 있습니다.
$a = array( 1, 2, 3, 4, 5 ); $b = array_reverse($a); print_r($a); //here need "br" while ($a != $b) { foreach(array_reverse($a, true) as $k => $v) { if ($v < $a[$k + 1]) { foreach(array_reverse($a, true) as $ka => $val) { if ($val > $v) break; } $ch = $a[$k]; $a[$k] = $a[$ka]; $a[$ka] = $ch; $c = array_slice($a, 0, $k + 1); print_r($a = array_merge($c, array_reverse(array_slice($a, $k + 1)))); //here need "br" break; } } }
-
==============================
8.나는 여기에 나열된 파이썬 itertools 코드 (생성자 사용)를 포팅했다. 지금까지 게시 된 솔루션의 장점은 r (순열 크기)을 지정할 수 있다는 것입니다.
나는 여기에 나열된 파이썬 itertools 코드 (생성자 사용)를 포팅했다. 지금까지 게시 된 솔루션의 장점은 r (순열 크기)을 지정할 수 있다는 것입니다.
function permutations($pool, $r = null) { $n = count($pool); if ($r == null) { $r = $n; } if ($r > $n) { return; } $indices = range(0, $n - 1); $cycles = range($n, $n - $r + 1, -1); // count down yield array_slice($pool, 0, $r); if ($n <= 0) { return; } while (true) { $exit_early = false; for ($i = $r;$i--;$i >= 0) { $cycles[$i]-= 1; if ($cycles[$i] == 0) { // Push whatever is at index $i to the end, move everything back if ($i < count($indices)) { $removed = array_splice($indices, $i, 1); array_push($indices, $removed[0]); } $cycles[$i] = $n - $i; } else { $j = $cycles[$i]; // Swap indices $i & -$j. $i_val = $indices[$i]; $neg_j_val = $indices[count($indices) - $j]; $indices[$i] = $neg_j_val; $indices[count($indices) - $j] = $i_val; $result = []; $counter = 0; foreach ($indices as $indx) { array_push($result, $pool[$indx]); $counter++; if ($counter == $r) break; } yield $result; $exit_early = true; break; } } if (!$exit_early) { break; // Outer while loop } } }
그것은 나를 위해 작동하지만 약속은 없습니다! 사용 예 :
$result = iterator_to_array(permutations([1, 2, 3, 4], 3)); foreach ($result as $row) { print implode(", ", $row) . "\n"; }
-
==============================
9.당신은 기본적으로 n과 k가 모두 9 인 퍼뮤 테이션에 대해 말합니다. 따라서 9를 가질 것입니다! 다른 순열; http://en.wikipedia.org/wiki/Permutation을 참조하십시오.
당신은 기본적으로 n과 k가 모두 9 인 퍼뮤 테이션에 대해 말합니다. 따라서 9를 가질 것입니다! 다른 순열; http://en.wikipedia.org/wiki/Permutation을 참조하십시오.
-
==============================
10.여기 제 제안이 있습니다, 받아 들여진 대답보다 조금 더 명확하게되기를 바랍니다.
여기 제 제안이 있습니다, 받아 들여진 대답보다 조금 더 명확하게되기를 바랍니다.
function permutate($elements, $perm = array(), &$permArray = array()) { if(empty($elements)) { array_push($permArray,$perm); return; } for($i=0;$i<=count($elements)-1;$i++) { array_push($perm,$elements[$i]); $tmp = $elements; array_splice($tmp,$i,1); permutate($tmp,$perm,$permArray); array_pop($perm); } return $permArray; }
및 사용 :
$p = permutate(array('a','b','c')); foreach($p as $perm) print join(",",$perm)."|\n";
-
==============================
11.이 시도...
이 시도...
//function to generate and print all N! permutations of $str. (N = strlen($str)) function permute($str,$i,$n) { if ($i == $n) print "$str\n"; else { for ($j = $i; $j < $n; $j++) { swap($str,$i,$j); permute($str, $i+1, $n); swap($str,$i,$j); // backtrack. } } } // function to swap the char at pos $i and $j of $str. function swap(&$str,$i,$j) { $temp = $str[$i]; $str[$i] = $str[$j]; $str[$j] = $temp; } $str = "0123"; permute($str,0,strlen($str)); // call the function.
from https://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers by cc-by-sa and MIT license
'PHP' 카테고리의 다른 글
어떤 입력 파일을 지정하지 (0) | 2018.09.14 |
---|---|
header ()를 사용하여 PHP로 파일 다운로드 강제 실행 (0) | 2018.09.14 |
Jquery Ajax를 사용하여 MySQL에서 데이터 검색 (0) | 2018.09.14 |
PHP 문자열의 유니 코드 문자 (0) | 2018.09.14 |
SimpleXMLElement 객체에서 값 가져 오기 (0) | 2018.09.14 |