Title: m monkeys around in a circle, reported that the monkey automatically left, and then the next one to restart from 1, has been circulating, the last Monkey is Monkey King, write procedures to find out the last is the king of the monkey's original position.
Package learn;
Import java.util.ArrayList;
public class Main {
public static void Main (string[] args) {
Create a list collection to hold the Monkey object (for ease of deduction, tentative total number of monkeys M is 6, each number to number n is 3)
arraylist<string> list = new arraylist<string> ();
for (int i=0; i<6;i++) {
List.add ("monkey" +i);
}
Total number of monkeys, M
int total = 6;
Number of targets per count, n
int target = 3;
Array table below
int index = 0;
Counter
int count = 0;
Number of remaining monkeys, initial value equals total
int remiander = total;
Be judged, as long as the remaining quantity is greater than 1, it is executed
while (remiander>1) {
/* If the number subscript equals the remaining quantity, the description has been traversed to the end of the array, you need to reset the array subscript to 0
The equivalent of a monkey standing in a row, to the last report after the number, the rest of the first followed by continue to count, with a siege of the same effect * *
if (Index==remiander) {
index=0;
}
If the subscript pair should have a value, the description should be counted once
if (list.get (index) = null) {
Count Flag plus 1
count++;
If the continuation flag is equal to the target number
if (count==target) {
Remove data from the corresponding location
List.remove (index);
The remaining quantity minus one
remiander--;
Resets the counter to 0
count=0;
Start the Next loop
Continue
}
}
After each calibration, execute here, subscript plus 1
index++;
}
Print out the last remaining monkey information
for (String monkey:list) {
System.out.println (monkey);
}
}
}
Operation Result: m=6,n=3, the result is monkey0;
M=8, n=5, the result is monkey2;
M=10,n=4, the result is monkey4;
Java implementation of the monkey selection King question (Joseph question)