Java实现约瑟夫环
什么是约瑟夫环呢?
约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
我们用程序说话,实现约瑟夫环:eclipse jdk1.6
1 package code; 2 3 import java.awt.PointerInfo; 4 import java.util.Random; 5 import java.util.Scanner; 6 7 public class Josephus { 8 private static class Node{ 9 public int no; 10 public Node next; 11 12 public Node(int no){ 13 this.no = no; 14 this.next =null; 15 } 16 } 17 public static void main(String[] args){ 18 /* 19 Scanner input = new Scanner(System.in); 20 System.out.println("taotal nums"); 21 int totalNum = input.nextInt(); 22 System.out.println("size"); 23 int cycleNum = input.nextInt();*/ 24 25 26 Random rand = new Random(); 27 int totalNum = rand.nextInt(30); 28 int cycleNum =rand.nextInt(5); 29 if(cycleNum <=1 || cycleNum >= totalNum){ 30 System.out.println("error"); 31 return ; 32 } 33 Node header = new Node(1); 34 Node pointer = header; 35 for(int i = 2 ;i<= totalNum ;i++){ 36 pointer.next = new Node(i); 37 pointer = pointer.next; 38 } 39 pointer.next = header ; 40 41 System.out.println(totalNum +" " + cycleNum); 42 System.out.println("order output"); 43 while(pointer != pointer.next){ 44 for ( int i =1 ;i <cycleNum ;i++){ 45 pointer =pointer.next; 46 } 47 System.out.println(pointer.next.no); 48 pointer.next = pointer.next.next; 49 } 50 System.out.println(pointer.next.no); 51 } 52 }
努力学习
雨,静静的飘扬;
心,慢慢的行走;
程序人生,人生迈进。