Let's take a look at the Joseph Ring question first:
Given M-individuals, M-individuals are enclosed in a circle, given a number n, from the first person in the m person each nth person removes it, asking for the number of the last person to go out.
Ideas:
Create an array of length m+1 to initialize its contents to 0 to M
We set the variable I and j,i to represent the following table of the array elements, because I set the array length to m+1, so the array subscript is the number of each person, and when i==m, we set the I to 0, making it convenient from the beginning.
The variable J determines whether the current element is the nth element of the arrangement, and if so, the value of the element currently labeled I is set to 0, no, i++,j++, whenever we traverse to an element with a value of 0, continue,i++ does nothing else.
The specific code is as follows:
Import Java.util.scanner;public class Main {public static void main (string[] args) {//TODO auto-generated method Stubscan NER scanner = new Scanner (system.in); int m=scanner.nextint (); Reads the value of m int n = scanner.nextint (); Read N's value int[] A = new int[m+1]; Set an array of length m+1 for (int i=0;i<=m;i++) {//Initialize the array, corresponding to the value of the array and its subscript one by one, easy to understand convenient operation A[i]=i;} /* * Set variables I and J * I to determine the subscript is the element value * j for determining the element of N, if ==n is about to remove the element of the current I */int i=0,j=1; Boolean flag=false;//sets a flag variable that is used in the loop for break and Continuewhile (true) {i++; A round cycle of the following table after the Flag=false shift; Set the flag variable to Falseif (a[i]==0) {//If the value in the current subscript is 0, skip flag=true, if (i==m)//Determine if I is ==m at this time, or if it is equal to M to reset it to 0i=0;} if (flag)//corresponds to the above function continue;if (j==n) {//if j==n the IF (Panduan (a)) {//determines if there is only one non-0 element in the array, if yes, the current To the element as the last element, otherwise execute elseSystem.out.println (i); flag=true; Because the last element was found, the SET flag variable is true}else {//satisfies only j==n and does not satisfy it as the last element, so the current elementThe content is set to 0, and let j=0, start a new count a[i]=0;j=0;}} if (flag)//finds the last element, jumps out of the Loop break;if (i==m)//If i==m, then let i=0i=0;j++; Round robin, j++}}static boolean Panduan (int [] a) {//Judge a given array of stone no only one non 0 element int count =0;for (int i=0;i<a.length;i++ {if (a[i]!=0) count++;} if (count==1) return True;return false;}}
This method is more problematic for arrays than for collections, but for small partners who have not yet learned the collection API. There's an easier way to communicate with me.
J using arrays to implement Joseph ring Java