约瑟夫环算法Java实现代码

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。


2B求解:

    private void myJosf(int teamLength, int baoshu) {  
        int[] team = new int[teamLength];  
      
        for (int n = 1; n < teamLength + 1; n++) {  
            team[n - 1] = n;  
        }  
      
        int index = 0;  
      
        for (int n = 0; n < teamLength; n++) {  
            for (int k = 0; k < baoshu;) {  
                if (index > teamLength - 1) {  
                    index = 0;  
                }  
      
                if (team[index] > 0) {  
                    if ((k + 1) % baoshu == 0) {  
                        System.out.println(index + 1);  
                        team[index] = 0;  
                    }  
                    k++;  
                }  
                index++;  
            }  
        }  
      
    }  

文艺求解:
    public void josephCircle(int n, int k) {  
            int flag = 0;  
            boolean[] kick = new boolean[n];  
            // set kick flag to False;  
            for (int i = 0; i < n - 1; i++) {  
                kick[flag] = false;  
            }  
      
            int counter = 0;  
            int accumulate = 0;  
            while (true) {  
                if (!kick[flag]) {  
                    accumulate++;  
                    if (counter == n - 1) {  
                        System.out.println("kick last person====" + (flag + 1));  
                        break;  
                    }  
                    if (accumulate == k) {  
                        kick[flag] = true;  
                        System.out.println("kick person====" + (flag + 1));  
                        accumulate = 0;  
                        counter++;  
                    }  
                }  
                flag = (flag + 1) % n;  
            }  
      
        }