SoFunction
Updated on 2025-03-02

Example of Joseph's Ring Algorithm Based on Recursive Implementation in PHP

This article describes the Joseph ring algorithm based on recursive implementation of PHP. Share it for your reference, as follows:

Joseph Ring Problem:39 Jews hid in a hole with Josephus and his friends, and 39 Jews decided to die rather than be caught by the enemy. So the method of suicide was decided. 41 people lined up in a circle, and the first person started to report the number. For each time the third person was reported, the person had to commit suicide. Then the next time the count will be re-reported until everyone commits suicide. However, Josephus and his friends did not want to comply. Josephus asked his friends to pretend to comply first. He arranged his friends and himself in the 16th and 31st positions, so he escaped the game of death.

<?php
$num = 41;
$step = 3;
function joseph($arr, $step, $start, $survivors)
{
  foreach($arr as $k => $v)
  {
    if($start % $step === 0)
    {
      unset($arr[$k]);
      $start = 1;
    }
    else
    {
      $start ++;
    }
  }
  if(count($arr) > $survivors)
    return joseph($arr, $step, $start, $survivors);
  else
    return $arr;
}
$i = 0;
$arr = [];
while($i ++ < $num){
  $arr[] = $i;
}
$arr = joseph($arr, 3, 1, 2);
print_r($arr);

Execution results:

Array
(
  [15] => 16
  [30] => 31
)

For more information about PHP related content, please check out the topic of this site:PHP data structure and algorithm tutorial》、《Summary of PHP Programming Algorithm》、《Complete collection of PHP array (Array) operation techniques》、《Summary of usage of php strings》、《Summary of common traversal algorithms and techniques for PHP"and"Summary of PHP mathematical operation skills

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