A java algorithm problem

12 people form a circle, followed by the serial number from 1-12, clockwise from start No. 1 according to the number of times the number of people 7 to exit, then the next number in sequence from the beginning, to find the last person to leave the original number.

public static void joseph(int[] array,int n) {
        for (int i = 0; i < array.length; i++) {
            array[i] = i+1;
        }
        // 计数器
        int counter = 0;
        // 剩余人数
        int leftCount = array.length;
        // 索引
        int index = 0;
        while (leftCount > 1) {
            if (array[index]>0) {
                counter++;
                if (counter == n) {
                    counter = 0;
                    array[index] = 0;
                    leftCount--;
                }
            }
            index++;
            if (index == array.length) {
                index = 0;
            }
        }   
        for (int i = 0; i < array.length; i++) {
            if (array[i]>0) {
                System.out.println("剩余人员的位置是" + (i + 1));
            }
        }
    }

    public static void main(String[] args) {
        int [] array = new int[12];
        joseph(array,7);
    }

 

Published 55 original articles · won praise 31 · views 80000 +

Guess you like

Origin blog.csdn.net/zengfanwei1990/article/details/81661299