Java实现约瑟夫环

时间:2022-06-24 22:21:40

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

 package code;

 import java.awt.PointerInfo;
import java.util.Random;
import java.util.Scanner; public class Josephus {
private static class Node{
public int no;
public Node next; public Node(int no){
this.no = no;
this.next =null;
}
}
public static void main(String[] args){
/*
Scanner input = new Scanner(System.in);
System.out.println("taotal nums");
int totalNum = input.nextInt();
System.out.println("size");
int cycleNum = input.nextInt();*/ Random rand = new Random();
int totalNum = rand.nextInt(30);
int cycleNum =rand.nextInt(5);
if(cycleNum <=1 || cycleNum >= totalNum){
System.out.println("error");
return ;
}
Node header = new Node(1);
Node pointer = header;
for(int i = 2 ;i<= totalNum ;i++){
pointer.next = new Node(i);
pointer = pointer.next;
}
pointer.next = header ; System.out.println(totalNum +" " + cycleNum);
System.out.println("order output");
while(pointer != pointer.next){
for ( int i =1 ;i <cycleNum ;i++){
pointer =pointer.next;
}
System.out.println(pointer.next.no);
pointer.next = pointer.next.next;
}
System.out.println(pointer.next.no);
}
}

努力学习