PHP implements the analysis of the Joseph Ring problem, and php implements the Joseph Ring
This article describes how to implement the Joseph Ring in PHP. We will share this with you for your reference. The details are as follows:
I. Overview
First, let's take a look at the common questions about Joseph's ring on the Internet. Description: Joseph's ring (Joseph's problem) is a mathematical application problem: n people are known (numbered 1, 2, 3... n represents respectively) sitting around a round table. The number of people numbered k starts to report, and the person counting m is listed; the next person reporting the number from 1, and the person counting m is listed again; repeat this rule, until all the people around the Round Table are listed. When solving such problems, we usually change the number from 0 ~ N-1. The final result + 1 is the solution of the original problem.
II. Implementation Code
1. Loop
function circle($arr,$idx,$k){ for($i=0;$i<$idx;$i++){ $tmp = array_shift($arr); array_push($arr,$tmp); } $j = 1; while(count($arr) > 0){ $tmp = array_shift($arr); if($j++%$k == 0){ echo $tmp."\n"; }else{ array_push($arr,$tmp); } }}$arr = array(1,2,3,4,5,6,7,8,9,10,11,12);$idx = 3;$k = 4;circle($arr,$idx,$k);
Running result:
7 11 3 8 1 6 2 10 9 12 5 4
2. Recursion
function circle($arr,$idx,$k){ $len = count($arr); $i = 1; if($len == 1){ echo $arr[0]."\n"; return ; } else { while($i++ < $k){ $idx++; $idx = $idx%$len; } echo $arr[$idx]."\n"; array_splice($arr,$idx,1); circle($arr,$idx,$k); }}$arr = [1,2,3,4,5,6,7,8,9,10,11,12];$idx = 3;$k = 4;circle($arr,$idx,$k);
Running result:
7 11 3 8 1 6 2 10 9 12 5 4