Java - 趣味题(2) --- 约瑟夫环

//约瑟夫环问题总结
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

可以参照http://baike.baidu.com/link?url=gEHOUvebJJpHjtByuBtthE3qvwIgtADWOCowK7p_4F3gKP_nxJ05waKiCTQoTO88t38_kolAFpKGssT-swyl5K#2_4


//问题1:只需要求出最后剩余的人的序号(0 ~ n-1)

/* If number = 3
     * f(1) = 0
     * f(2) = 1 = (f(1) + 3) % 2
     * f(3) = 1 = (f(2) + 3) % 3
     * f(4) = 0 = (f(3) + 3) % 4
     * f(5) = 3 = (f(4) + 3) % 5
     * ...
     * f(n) = x = (f(n-1) + 3) % n
     * */

public class Java_YSF
{
    public static void main(String arg[]){
        System.out.println("\t\tYSF问题总结1");

        Scanner sc = new Scanner(System.in);
        System.out.println("please input the Total num:");
        int total = sc.nextInt();

        System.out.println("Please input the kill poll num:");
        int number = sc.nextInt();

        int last = 0;
        for(int i = 2;i <= total; i++)
        {
            last = (last + number) % i;
        }

        System.out.println("The index of Last is " + last);
    }
}


//问题2:有条件的打印出出队的顺序(从第K个开始数数,每数数number就出队,并且最终打印出队的顺序)
public class Java_YSF{
    public static void main(String args[])
    {
        System.out.println("\t\tYSF问题总结2");

        Scanner sc = new Scanner(System.in);
        System.out.println("please input the Total num:");
        int total = sc.nextInt();

        System.out.println("Please input the kill poll num:");
        int number = sc.nextInt();

        System.out.println("Please input the first kill people number : (0,1,2.....)");
        int K = sc.nextInt();

        //构造0 1 2 3 4 5 ........
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i = 0; i < total; i++)
        {
            list.add(i);
            System.out.print(list.get(i) + " ");
        }
        System.out.println();



        int account = 1;
        int i = K;
        while(list.size() > i)
        {
            i++;
            if(i == list.size())
            {
                i = 0;
            }

            account++;
            if(account == number)
            {   
                System.out.print(list.get(i) + "*");
                list.remove(i);
                account = 0;
                i--;
            }
        }
        System.out.println();
        for(i = 0; i < list.size(); i++)
        {
            System.out.print(list.get(i) + " ");

        }
        System.out.println("此处应该无内容,因为List的内容已经全部删掉了~~");

    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值