This article mainly introduced the PHP implementation of the Joseph ring problem method, combined with an example of PHP using the loop and recursive implementation of Joseph Ring related operation skills, the need for friends can refer to the next
In this paper, we describe the method of implementing the Joseph ring problem in PHP. Share to everyone for your reference, as follows:
I. Overview
Let's take a look at the usual Joseph ring problem description on the Internet: Joseph Ring (Josephson question) is a mathematical application problem: known n individuals (denoted by number 1,2,3...N respectively) sit around a round table. From the person numbered K began to count, the number to m of the person out of the man, and his next person from 1 began to count, the number to m of the person again, according to this rule repeat until the round table all the people out. Usually solve this kind of problem when we put the number from 0~n-1, the last result +1 is the solution of the original problem.
Second, the implementation of the Code
1. Cycle
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);
Operation 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);
Operation Result:
7 11 3 8 1 6 2 10 9 12 5 4
Articles you may be interested in:
The method of using Passport to realize auth certification in Laravel5.5
Performance optimizations you might miss in PHP: What's relevant to the generator
Implementation of composer automatic loading in laravel framework