【问题标题】:Shuffling php string改组php字符串
【发布时间】:2017-10-25 07:15:01
【问题描述】:

我怎样才能打乱 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() 总是出错

【问题讨论】:

  • 如果您曾想过使用global - 请改用参数。 global 不被认为是好的做法。
  • 随机播放或所有可能的变化?
  • @Andreas 是的,对于所有可能的但仅适用于输入的许多字符,例如 abc 它不能是 aab 但 abca 它可以是 aabc。

标签: php shuffle


【解决方案1】:

这是洗牌任何字符的示例函数。您只能将 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');

【讨论】:

    【解决方案2】:

    希望这会有所帮助:

    <?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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 2015-05-02
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多