Php implements Monkey King election algorithm instance, Monkey King. Php implements an example of Monkey King election algorithm. this example describes how php implements the Monkey King election algorithm. Share it with you for your reference. The specific analysis is as follows: 1. ask php to implement the Monkey King election algorithm instance.
This example describes how to implement the Monkey King election algorithm in php. Share it with you for your reference. The specific analysis is as follows:
I. problems:
N monkeys sat in a circle and numbered from 1 to n clockwise.
Then, the number of monkeys started to report data from 1 clockwise and reported to m's monkeys for exit. then, the number of monkeys started to report data again from the next position,
Repeat this until there is one monkey left. it is the king.
Design and write programs to implement the following functions:
(1) the number of monkeys starting from the user input is required $ n, and the last number of records $ m.
(2) give the initial number of the Monkey King.
II. solution:
/*** @ Param int $ n indicates the number of monkeys at the beginning * @ param int $ m indicates the last number of monkeys reported * (the monkeys reported for this number are eliminated, then the next monkey returns the count from ①) * @ return int the initial number of the Monkey */function monkeySelectKing ($ n, $ m) {// The initial number of monkeys cannot be less than 2 if ($ n <2) {return false;} $ arr = range (1, $ n ); // divide the monkey into an array. the array value corresponds to the monkey's initial number $ unsetNum = 0; // defines a variable and records the monkey's report number for ($ I = 2; $ I <= $ n * $ m; $ I ++) // You do not know how to calculate the total number of cycles. {// however, because return is set in the loop, so $ m * $ len efficiency can also be foreach ($ arr as $ k => $ v) {$ unsetNum ++; // Every monkey, monkey Report + 1 // when the monkey report number is equal to the number of the eliminated Monkey: The monkey is eliminated (the array element is deleted) // The Report number is 0 (the next monkey starts from 1) if ($ unsetNum = $ m) {// echo""; // Open the comment and you can see the specific elimination process // print_r ($ arr); unset ($ arr [$ k]); // kill the monkey $ unsetNum = 0; // return to zero if (count ($ arr) = 1) // judge the length of the array. if only one monkey is left, returns its value {return reset ($ arr) ;}}} var_dump (monkeySelectKing (6, 3 ));Supplement the improved algorithm (this algorithm is more concise and clear !) :
function yuesefu($n,$m) { $r=0; for($i=2; $i<=$n; $i++) { $r=($r+$m)%$i; } return $r+1; } print_r(yuesefu(3,3));I hope this article will help you design php programming algorithms.
The example in this article describes how to implement the Monkey King election algorithm in php. Share it with you for your reference. The specific analysis is as follows: 1. ask...