Method Analysis of Realizing Joseph Ring Problem by PHP

  • 2021-08-21 19:53:03
  • OfStack

In this paper, an example is given to describe the method of realizing Joseph ring problem by PHP. Share it for your reference, as follows:

1. Overview

Let's take a look at the description of Joseph's ring problem, which is common on the Internet. Joseph's ring (Joseph's problem) is a mathematical application problem: known n individuals (denoted by numbers 1, 2, 3... n respectively) sit around a round table. Start counting from the person numbered k, and the person who counts to m is listed; His next person started counting from 1, and the person who counted to m went out again; Repeat this rule until all the people around the round table are out of line. Usually, when solving this kind of problem, we change the number from 0 to n-1, and the final result +1 is the solution of the original problem.

2. Implementation code

STEP 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);

Run results:


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);

Run results:


7 11 3 8 1 6 2 10 9 12 5 4

For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: