• 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 }

    努力学习

  • 相关阅读:
    Maximum Flow Exhaustion of Paths Algorithm
    ubuntu下安装java环境
    visualbox使用(二)
    vxworks一个超级奇怪的错误(parse error before `char')
    February 4th, 2018 Week 6th Sunday
    February 3rd, 2018 Week 5th Saturday
    February 2nd, 2018 Week 5th Friday
    February 1st, 2018 Week 5th Thursday
    January 31st, 2018 Week 05th Wednesday
    January 30th, 2018 Week 05th Tuesday
  • 原文地址:https://www.cnblogs.com/xuddong/p/3296355.html
Copyright © 2020-2023  润新知