PHP implements the analysis of the Joseph Ring problem, and php implements the Joseph Ring

Source: Internet
Author: User

PHP implements the analysis of the Joseph Ring problem, and php implements the Joseph Ring

This article describes how to implement the Joseph Ring in PHP. We will share this with you for your reference. The details are as follows:

I. Overview

First, let's take a look at the common questions about Joseph's ring on the Internet. Description: Joseph's ring (Joseph's problem) is a mathematical application problem: n people are known (numbered 1, 2, 3... n represents respectively) sitting around a round table. The number of people numbered k starts to report, and the person counting m is listed; the next person reporting the number from 1, and the person counting m is listed again; repeat this rule, until all the people around the Round Table are listed. When solving such problems, we usually change the number from 0 ~ N-1. The final result + 1 is the solution of the original problem.

II. Implementation Code

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

Running result:

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

Running result:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.