java 约瑟夫问题

题目:

给定一个数组及数组的长度,另外给定一个数m,从数组的第一个元素出发,数到第m个元素出列(如果到最后则回到第一个元素)。出列元素的值作为m的新值,从出列元素的下一元素继续开始数下去,直到所有元素出列。要求给出由出列元素按顺序形成的新数组。

解答:

    static void func(int len, int[] input_array, int m, int[] output_array) {
        int ptr = -1;
        int ptr2 = 0;
        
        for (int i = 0; i < len; i++) {
            int step = 0;
            while (step < m) {
                ptr = (ptr + 1) % len;
                if (input_array[ptr] != -1) {
                    step++;
                }
            }
            m = input_array[ptr];
            output_array[ptr2++] = m;
            input_array[ptr] = -1;
        }
    }

测试代码为:

    public static void main(String[] args) {

        int[] arr1 = {3,1,2,4};
        int m = 7;
        int[] arr2 = new int[4];
        func(arr1.length,arr1,m,arr2);
        
        for(int i: arr2)
            System.out.print(i+" ");

    }

题目也不难,作为一道笔试题,我不禁把它做成了博客。

原文地址:https://www.cnblogs.com/shuada/p/3608647.html