Example of an algorithm used by PHP to solve Joseph's ring problem using stack, and Joseph's example
This example describes how PHP uses the stack to solve the Joseph Ring problem algorithm. We will share this with you for your reference. The details are as follows:
Joseph's ring problem:39 Jews hid in a cave with Joseph and his friends, and 39 Jews decided to die rather than be captured by the enemy. Therefore, the method of suicide was decided. 41 people were arranged in a circle, and the number of reports started from 1st. Each report to 3rd people had to commit suicide. Next, report the number again until everyone commits suicide. However, Joseph and his friends didn't want to follow suit. He asked his friends to pretend to follow suit first. He arranged his friends and himself in 16th and 31st positions, so he escaped the death game.
<?phpclass ArrayStack{ private $size; private $stack = []; public function __construct(){} public function buildStack($num){ $this->size = $num; $index = 0; while($index ++ < $this->size) { $this->stack[] = $index; } } public function pop(){ $item = array_shift($this->stack); $this->size = count($this->stack); return $item; } public function push($item) { $this->stack[] = $item; $this->size = count($this->stack); } public function size() { return $this->size; } public function stack() { return $this->stack; }}interface Joseph{ public function handle($num = 0, $step = 0, $survivors = 0);}class StackJoseph implements Joseph{ protected $stack; protected $num; protected $step; public function __construct(ArrayStack $stack) { $this->stack = $stack; } public function handle($num = 0, $step = 0, $survivors = 0) { // TODO: Implement handle() method. $this->stack->buildStack($num); $i = 0; while($this->stack->size() > $survivors) { $pop = $this->stack->pop(); if(($i + 1) % $step !== 0) { $this->stack->push($pop); $i ++; } else { $i = 0; } } return $this->stack->stack(); }}function joseph($num, $step, $survivorsNum){ $arrayStack = new ArrayStack(); $joseph = new StackJoseph($arrayStack); return $joseph->handle($num, $step, $survivorsNum);}print_r(joseph(41, 3, 2));
Execution result:
Array( [0] => 16 [1] => 31)