【作业】约瑟夫环

题目:
古代某法官要判决n个犯人死刑,他有一条荒唐的逻辑,将犯人首尾的相接排成圆圈,然后从第s个人开始数起,每数到第m个犯人,就拉出来处决;然后又数m个,数到的犯人又拉出来处决,依次类推。剩下的最后一人可以豁免。


自己智商能理解的写法

public class Josephus {
    public static void main(String[] args) {
        //编号从 0 到 n-1
        //最终输出 最后一个活下来的人的编号
        int n = 5; // 总人数
        int s = 0; // 起始的人的编号
        int d = 3; // 每数到第几个人

        int alive_person = n;
        int[] person_state = new int[n];
        int current_person_index = s;
        int counter = 0;
        while( true ) {
            // count
            counter++;

            // judge current person
            if ( counter==d ) {
                person_state[current_person_index] = 1; // kill this person
                System.out.println("the person whose index is " + current_person_index+" die");
                alive_person--;
                counter = 0; // reset counter
            }

            // should we stop ?
            if( alive_person == 1 ) {
                for(int j=0; j<n; j++) {
                    if (person_state[j] == 0) {
                        System.out.println("The lucky person`s index is " + j);
                    }
                }
                return;
            }

            // go to next alive person
            while(true) {
                // move to next person (alive or dead)
                current_person_index++;
                if(current_person_index == n) {
                    current_person_index = 0;
                }

                // break when this person is alive
                if( 0 == person_state[current_person_index] ) {
                    break;
                }
            }

        }

        
    
    }
}

 

从网上找的以自己智商看不懂的写法

int Joseph(int n, int m)   
{  
    int fn=0;  
    for (int i=2; i<=n; i++)   
    {  
        fn = (fn+m)%i;   
    }  
    return fn;  
}
public int Joseph(int n, int m) {
    if(n == 1)   return n;
    return (Joseph(n - 1, m) + m - 1) % n + 1;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值