Beginning
The company organizes the examination. Once it gets the examination question, it's Joseph Ring in the algorithm. Think carefully about what the teacher forgot before, or do you think about it
package basic.gzy; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; /** * Joseph Ring number game, for example, 5, 3, the last one to quit the game is number 4 * Five people siege ring, count to three, quit the game, then turn down, the last one is the survivor * To meet the requirement that the number reported is less than the number of people * @author mac * */ public class BSYX { public static void main(String[] args) { // System.out.println("--- Survivor" + baoshu1(5,3)); // System.out.println("--- Survivor" + baoshu1(12,3)); System.out.println("---Survivor"+baoshu2(5,3)); } public static int baoshu1(int num, int count) { // The last to quit is the n th person int n = 0; // The rest of us int rest = num; // Using array initialization to 0 as identity bit int[] arr = new int[num + 1]; // Initialization times int index = 1; for (int i = 1, j = 1; i < num + 1; i++, j++) { //Skip exited data while (arr[i] == 1) { if(i<num) { i++; }else { i=1; } } if (rest == 1) { n = i; break; } if (j == 1) { System.out.println(); System.out.print("The first" + index + "Second game," + i + "[" + j + "],"); } else if (j < count ) { System.out.print(i + "[" + j + "],"); } else { System.out.print(i + "[" + j + "]--" + i + "Quit game"); // Reset j will + + to 0, game times + 1, array marker bit exited, 1 less people left j = 0; index++; rest--; arr[i] = 1; } if (i == num ) { // Back to the header, + + will be set to 0 i = 0; } } return n; } /** * Using queues * @param num * @param count * @return */ public static int baoshu2(int num, int count) { int n = 0; int rest = num; int index = 1; int l = 0; Queue<Integer> list = new LinkedList<Integer>(); for(int i=1;i<num+1;i++) { list.add(i); } while(!list.isEmpty()) { Integer poll = list.poll(); l++; if(rest == 1) { n=poll; break; } // Flexible use of surplus if(l%count == 1) { System.out.println(); list.add(poll); System.out.print("The first" + index + "Second game," + poll + "[" + 1 + "],"); }else if(l%count==0) { System.out.println(poll + "[" + count + "]--" + poll + "Quit game"); rest --; index++; }else { list.add(poll); System.out.print(poll + "[" + poll%count + "],"); } } return n; } }
Conclusion: the first one is the low way of writing, which is redundant and easy to read. The second one makes use of LinkedList, which is also a ring feature, and is quite ingenious. Another is the idea of object-oriented, which is still improving