Php solves Joseph ring and php Joseph Ring
Today I met an algorithm question
"Joseph's ring" is a mathematical application problem: a group of monkeys are arranged in a circle, which is divided into 1, 2 ,..., N is numbered in sequence. Then start counting from 1st, count to m, kick it out of the circle, start counting from behind it, count to m, and kick it out ..., The monkey is called the King until there is only one monkey. Programming to simulate this process, input m, n, and output the number of the last king.
Method 1: Recursive Algorithms
1 function killMonkey ($ monkeys, $ m, $ current = 0) {2 $ number = count ($ monkeys); 3 $ num = 1; 4 if (count ($ monkeys) = 1) {5 echo $ monkeys [0]. "Become Monkey King"; 6 return; 7} 8 else {9 while ($ num ++ <$ m) {10 $ current ++; 11 $ current = $ current % $ number; 12} 13 echo $ monkeys [$ current]. "The monkey is kicked off <br/>"; 14 array_splice ($ monkeys, $ current, 1); 15 killMonkey ($ monkeys, $ m, $ current ); 16} 17} 18 $ monkeys = array (1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ); // monkeys No. 19 $ m = 3; // The number of monkeys to be kicked out is 20 killMonkey ($ monkeys, $ m );Method 2: Linear table Application
The best algorithm at last,
Oh, well, after each monkey is listed, the rest of the monkeys constitute another sub-problem. But their numbers have changed. The first monkey to be listed must be a [1] = m (mod) n (remainder of m/n). The other monkey to be removed is a [1] + 1, a [1] + 2 ,..., N, 1, 2 ,... A [1]-2, a [1]-1, corresponding to the new numbers 1, 2, 3... N-1. Assume that the new ID of a monkey is I, and the original ID is (I + a [1]) % n. Therefore, this forms a recursive problem. If we know that the solution of this Sub-problem (n-1 monkeys) is x, then the solution of the original problem (n monkeys) is: (x + m % n) % n = (x + m) % n. Start condition of the problem: If n = 1, the result is 1.
1 function yuesefu ($ n, $ m) {2 $ r = 0; 3 for ($ I = 2; $ I <= $ n; $ I ++) {4 $ r = ($ r + $ m) % $ I; 5} 6 return $ r + 1; 7} 8 echo yuesefu (10, 3 ). "Is Monkey King ";