Php 如何使数组组合具有唯一值和有限字符?
我有一个这样的数组 ['1', '2', '3', '4']; 我想让数组的结果像这样 [‘123’、‘124’、‘132’、‘134’、‘142’、‘143’、‘213’、‘214’、‘231’、‘234’、‘241’、‘243’、‘312’、‘314’、‘321’、‘324’、‘341’、‘342’、‘412’、‘413’、‘421’、‘423’、‘431’、‘423’] 这是我的密码Php 如何使数组组合具有唯一值和有限字符?,php,arrays,Php,Arrays,我有一个这样的数组 ['1', '2', '3', '4']; 我想让数组的结果像这样 [‘123’、‘124’、‘132’、‘134’、‘142’、‘143’、‘213’、‘214’、‘231’、‘234’、‘241’、‘243’、‘312’、‘314’、‘321’、‘324’、‘341’、‘342’、‘412’、‘413’、‘421’、‘423’、‘431’、‘423’] 这是我的密码 <?php ini_set('memory_limit', '-1'); function pe
<?php
ini_set('memory_limit', '-1');
function permute($arg) {
$array = is_string($arg) ? str_split($arg) : $arg;
if(1 === count($array))
return $array;
$result = array();
foreach($array as $key => $item)
foreach(permute(array_diff_key($array, array($key => $item))) as $p)
$result[] = $item . $p;
return $result;
}
$array = array('1','2','3','4');
var_dump(permute($array));
?>
我想把结果的字符限制为3个字符。怎么做
<?php
function combination($chars, $size, $combinations = array()) {
if (empty($combinations)) {
$combinations = $chars;
}
# we're done if we're at size 1
if ($size == 1) {
return $combinations;
}
$new_combinations = array();
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
return combination($chars, $size - 1, $new_combinations);
}
function permute($array, $numberOfChar)
{
$output = combination($array, $numberOfChar);
$result = array_values(array_filter($output,function($str){
for($i = 0; $i < strlen($str); $i++)
{
for($j = $i + 1; $j < strlen($str); $j++)
{
if($str[$i] == $str[$j])
{
return false;
}
}
}
return true;
}));
return $result;
}
$array = array(1,2,3,4);
print_r(permute($array, 3)); // pass an array an num of permute char
<?php
function combination($chars, $size, $combinations = array()) {
if (empty($combinations)) {
$combinations = $chars;
}
# we're done if we're at size 1
if ($size == 1) {
return $combinations;
}
$new_combinations = array();
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
return combination($chars, $size - 1, $new_combinations);
}
function permute($array, $numberOfChar)
{
$output = combination($array, $numberOfChar);
$result = array_values(array_filter($output,function($str){
for($i = 0; $i < strlen($str); $i++)
{
for($j = $i + 1; $j < strlen($str); $j++)
{
if($str[$i] == $str[$j])
{
return false;
}
}
}
return true;
}));
return $result;
}
$array = array(1,2,3,4);
print_r(permute($array, 3)); // pass an array an num of permute char