PHP Joseph Problem Solving algorithm for the execution of prisoners, PHP Joseph prisoner algorithm
This article describes the PHP Joseph problem solving algorithm for the execution of prisoners. Share to everyone for your reference. The specific analysis is as follows:
A judge in ancient times had to sentence the death of IV prisoners, and he had an absurd law that stood the prisoner in a circle, starting from the first individual, and then pulling out every d person, then counting D, then pulling out to execute ... Until the last one can be forgiven.
function Getnum ($n, $m) { //For depositing all the numbers into the array initialization $a = array (); Iterate, deposit array for ($i =1; $i <= $n; $i + +) { $a [$i] = $i; } The pointer is 0 reset ($a); while (count ($a) >1) { //If the item in the array is greater than 1, continue the loop culling element //culling rule for ($j =1; $j <= $m; $j + +) { //If the last item of the array is not reached if (next ($a)) { if ($j = = $m) { //delete m-item unset ($a [Array_search (prev ($a), $a)]);} } else{ //If Next does not exist, then the pointer is 0 reset ($a); if ($j = = $m) { unset ($a [Array_search (end ($a), $a)]); Reset ($a); }}} return current ($a);} echo Getnum (5,3);
I hope this article is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/972650.html www.bkjia.com true http://www.bkjia.com/PHPjc/972650.html techarticle PHP Joseph Problem Solving algorithms for the execution of prisoners, PHP Joseph prisoner algorithm This article describes the PHP Joseph problem solving algorithm for the execution of prisoners. Share to everyone for your reference ...