1. 程式人生 > >Joseph Problem With Passwords In Java

Joseph Problem With Passwords In Java

初始化 num ava 代碼 words port ini lse p s

問題描述:

編號為1,2,......,n的n個人(每個人的信息有編號、姓名和密碼三項)按照順時針方向圍坐一圈,

每個人有且只有一個密碼(正整數,密碼用隨機方式賦值,範圍1-15)。一開始任選一個正整數作為報數

上限值,從第一個人開始順時針方向自1開始報數,報到m時停止報數。報m 的人出列,將他的密碼作為新

的m 值,從他在順時針方向的下一個人開始重新報數,如此下去,直到所有人全部出隊為止。設計一個程

來求出隊順序。

分析:

為解決約瑟夫問題而設計的單向循環鏈表,應實現如下功能 :
1 添加元素
2 擁有指示當前選中元素的遊標
3 遊標可循環訪問鏈表中各元素
4 可將遊標向前移動指定步數


5 可刪除當前遊標所指定的元素
*輸入:每個人的信息;起始m值
*輸出:出隊的人信息。

步驟:

1 確定數據類型
2 建立鏈表
3 實現循環方法
4 輸出結果

 1 import  java.util.*;
 2 import  java.io.*;
 3 
 4 public class JosephProb {
 5     static int N;
 6 
 7     public static void main(String[] args) throws IOException{
 8         CircleLinkList list=new CircleLinkList();
9 Scanner sc=new Scanner(System.in); 10 System.out.print("請輸入參加的總人數N :"); 11 N=sc.nextInt(); 12 13 int i,data[][]=new int [N][2]; 14 String name[]=new String[N]; 15 System.out.println("請輸入每個人的編號和姓名:"); 16 for( i=0;i<N;i++){ 17 data[i][0]=sc.nextInt();
18 name[i]=sc.nextLine(); 19 } 20 System.out.print("請輸入初始密碼值(正整數):"); 21 int m=sc.nextInt(); 22 23 //生成密碼 24 List<Integer> l = new ArrayList<Integer>(); 25 while(l.size()<N){ 26 int j = (int)(Math.random()*15+1); 27 l.add(j); 28 } 29 //初始化 30 for(i=0;i<N;i++){ 31 data[i][1]=l.get(i); 32 list.Init(data[i][0],name[i],data[i][1]); 33 } 34 //出列 35 list.Operation(m); 36 System.out.println("Over!"); 37 } 38 } 39 class Person{ 40 int number; 41 int password; 42 String names; 43 Person next; 44 public Person (int number,String names,int password){ 45 this.number=number; 46 this.names=names; 47 this.password=password; 48 this.next=null; 49 } 50 } 51 class CircleLinkList { 52 Person head;//頭結點 53 Person current; 54 55 public boolean isEmpty(){ return head==null; } 56 57 public void Init(int number,String names,int password) { 58 Person tmp=new Person(number,names,password); 59 if(this.isEmpty()){ 60 head=tmp; 61 current=head; 62 } 63 else{ 64 current.next=tmp; 65 current=tmp; 66 } 67 //最後一個節點的next指向第一個 68 current.next = head; 69 } 70 71 public void Operation(int m){ 72 System.out.println("出列人信息:[編號 姓名 密碼]"); 73 while(current!=current.next){ 74 for(int i=1;i<m;i++){ //從1開始報數,到m時停止報數 75 current=current.next;//指針移動到出列的前一個節點 76 } 77 m=current.next.password;//修改密碼為出列人的密碼 78 //輸出-出隊人的信息 79 System.out.print("["+current.next.number+" "+current.next.names+" "+current.next.password+"]\n"); 80 current.next=current.next.next;//刪除 81 } 82 System.out.println(); 83 System.out.println("最後剩余的是 ["+current.number+" "+current.names+" "+current.password+" ]"); 84 } 85 }

補充:

可以將出隊的人用隊列進行存儲,並輸出。

實現就是新建一個QueueList,添加Insert()輸出Dequeue()即可。

代碼略。

Joseph Problem With Passwords In Java