Code details: Java Monkey King selection (Joseph Ring), java monkey

Source: Internet
Author: User

Code details: Java Monkey King selection (Joseph Ring), java monkey

Basic knowledge about Joseph's ring:

The Romans captured jotabat, and 41 people hid in a cave to escape the catastrophe. Among the 41, including the historian Joseph PHUs and one of his friends. The 39 remaining members decided to commit suicide collectively to show that they did not give in to the Romans. Everyone decided on a suicide plan. All the 41 people were surrounded by a circle, and the first person started to report the number clockwise. Those who did not report the number as 3 immediately committed suicide, then, the next person starts reporting the number again. The next person who reports the number 3 immediately commits suicide ,......, we know all of them are killed by suicide. joseph and his friends didn't want to commit suicide, so Joseph thought of a plan. The two of them had the same parameters in the suicide plan, but finally escaped suicide. How is it done?

Code sharing:

Import java. util. hashMap; import java. util. map; public class MonkeyKing {public static void main (String args []) {int n = 100; // total number of monkeys int m = 3; // Number of outgoing messages @ SuppressWarnings ("rawtypes") Map map = new HashMap (); int nn = 1; // Number of outgoing messages No. int mm = 1; // Number of outgoing messages System. out. println ("-----------------------" + n + "select the Monkey King and start -----------------------"); for (int I = 1; I <n + 1; I ++) {map. put (I, I);} while (map. si Ze ()> 1) {if (mm = 3) {map. remove (nn) ;}nn ++; if (nn = n + 1) {nn = 1;} if (map. get (nn )! = Null) {mm ++;} if (mm = m + 1) {mm = 1 ;}} String result = map. values (). toString (); System. out. println ("Number" + result. substring (1, result. length ()-1) + "monkey Election ");}}

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.