Java array solves the problem of Joseph (Joseph)

Source: Internet
Author: User

Suppose there are M people, which are arranged in a circle in order with numbers 1-M respectively. Now we will give a definite number N, which will be reported from the first person and listed on the number N, then the next person starts reporting the number from 1st, and the number of people who count to N is listed... Keep repeating until everyone is listed! Simple array can be implemented without using linked lists and multi-dimensional arrays. The code is explained in detail: public class Joseph PHUs {public static void main (String [] args) {// a total of M personal int m = 9; // The number of N people out of the column int n = 4; // start the reporting position int k = 1; // The length of the initial array, which is reduced by 1 int len = m in the next lap; int [] array = new int [m]; // The array value is for (int I = 0; I <m; I ++) {array [I] = I + 1;} www.2cto. comint I = 0; // array subscript int j = 1; // current number of messages to be reported while (len> 0) {if (array [I % m]> 0) {if (j % n = 0) {// find the person in the circle and Output System. out. print (array [I % m] + ""); array [I % m] =-1; j = 1; I ++; len --;} else {I ++; j ++ ;}} else {// skip the I ++ ;}}}}

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.