我怎样才能改变php字符串? 我想在洗牌输出中显示所有字符串。
示例输入:abc
输出:
abc
acb
bac
bca
cab
cba
我的代码:
function permutations() {
global $running;
global $characters;
global $bitmask;
if (count($running) == count($characters)) {
printf("%s\n", implode($running));
} else {
for ($i=0; $i<count($characters); $i++) {
if ( (($bitmask>>$i)&1) == 0 ) {
array_push($running, $characters[$i]);
$bitmask |= (1<<$i);
permutations();
array_pop($running);
}
}
}
}
fscanf(STDIN, '%s', $raw_input);
$characters = str_split($raw_input);
$running = array();
$bitmask = 0;
permutations();
始终会收到fscanf()
答案 0 :(得分:2)
这是用于改组任何字符的示例函数。您只能使用shuffle_string函数。
// direct function for shuffling characters of any string
function shuffle_string ($string) {
$string_len = strlen($string);
permute($string, 0, $string_len);
}
// to generate and echo all N! permutations of $string.
function permute($string, $i, $n) {
if ($i == $n) {
echo "$string\n";
} else {
for ($j = $i; $j < $n; $j++) {
swap($string, $i, $j);
permute($string, $i+1, $n);
swap($string, $i, $j); // backtracking.
}
}
}
// to swap the character at position $i and $j of $string.
function swap(&$string, $i, $j) {
$temp = $string[$i];
$string[$i] = $string[$j];
$string[$j] = $temp;
}
shuffle_string('Hey');
答案 1 :(得分:1)
希望这会有所帮助:
<?php
function permutations($set)
{
$solutions=array();
$n=count($set);
$p=array_keys($set);
$i=1;
while ($i<$n)
{
if ($p[$i]>0)
{
$p[$i]--;
$j=0;
if ($i%2==1)
$j=$p[$i];
//swap
$tmp=$set[$j];
$set[$j]=$set[$i];
$set[$i]=$tmp;
$i=1;
$solutions[]=$set;
}
elseif ($p[$i]==0)
{
$p[$i]=$i;
$i++;
}
}
return $solutions;
}
$string = 'abc';
$string = str_split($string);
$all_per = permutations($string);
foreach($all_per as $key => $value){
$str[]= implode(',',$value);
}
print_r($str);