0

(I don't think my question is clear enough to explain my needs. Apologize for my English for that.)

I want to shuffle the number to the last possibility. I can only think of this. It seems working but it's not give me all the number as a loop runs.

$num="123";//given number
for($i=0;$i<10;$i++){
    $num2[$i]=str_shuffle($num);            
}//for
print_r($num2);
print_r(array_unique($num2));

As a result.

print_r($tod);//Array ( [0] => 132 [1] => 123 [2] => 321 [3] => 231 [4] => 312 [5] => 231 
[6] => 231 [7] => 231 [8] => 312 [9] => 312 )

And I want only the unique array. So I put array_unique(). Then I got...

print_r(array_unique($tod));//Array ( [0] => 132 [1] => 123 [2] => 321 [3] => 231 [4] => 312 )

I want the loop (or not) to give me all possible number from the $num everytime. Or is there any function/method to get me this result more accurate?

As you see $num="123". I expect the result are 123, 132, 213, 231, 321 and 312.

Wilf
  • 2,297
  • 5
  • 38
  • 82
  • So you need all permutations of a number? – nice_dev Oct 27 '21 at 18:20
  • I don't know what to call but as you see `$num="123"`. I expect the result are `123`,`132`,`213`,`231`,`321` and `312`. – Wilf Oct 27 '21 at 18:22
  • Not sure about any inbuilt function but you can create your own. str_shuffle will just shuffle the string. It may or may not generate all the unique permutations all the time, hence it isn't correct. – nice_dev Oct 27 '21 at 18:24
  • The problem is the loop. Sometimes it gives me complete shuffle. But mostly not. – Wilf Oct 27 '21 at 18:24
  • Because you are running 10 times and randomly shuffling and hoping to get the 6 numbers in 10 tries. – AbraCadaver Oct 27 '21 at 18:31
  • https://en.wikipedia.org/wiki/Heap%27s_algorithm – Sammitch Oct 27 '21 at 19:54
  • Got answered here: https://stackoverflow.com/a/18853960/1620626 It's about permutations of a string in PHP. Thanks for every suggestions! – Wilf Oct 27 '21 at 18:31
  • https://sandbox.onlinephpfunctions.com/code/cb8bf4c5ca7b2a1f4e7da53754531e99b149ce8c – nice_dev Oct 28 '21 at 03:03

0 Answers0