简体   繁体   中英

Shuffling php string

How can I shuffle the php string? I want to show all of the string in the shuffled output.

example input : abc

output :

abc
acb
bac
bca
cab
cba

my code :

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

always get error for the fscanf()

This is sample function for shuffling any characters. You can use only shuffle_string function for your purpose.

// 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');

Hope this will help:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM