//约瑟夫环问题总结
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的内容已经全部删掉了~~");
}
}
Java - 趣味题(2) --- 约瑟夫环
最新推荐文章于 2021-02-24 15:28:36 发布