Java学习之约瑟夫环的两中处理方法
生活随笔
收集整理的這篇文章主要介紹了
Java学习之约瑟夫环的两中处理方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 package day_2;
2
3 import java.util.Scanner;
4
5 /**
6 * @author Administrator
7 * 約瑟夫環問題: 設編號為 1,2,3,....n的N個人圍坐一圈,約定編號為k(1<=k<=n)
8 * 的人從1開始報數,數到m的那個人出列,它的下一位又從1開始報數,數到m的那個人又出列,依次
9 * 類推,直到所有人出列為止,由此產生一個出隊編號的序列。
10 * 方法一:數組取模法、(模擬)
11 */
12
13 public class Demo_1 {
14 public static void main(String args [])
15 {
16 int n,m;
17 Scanner cin;
18 while(true)
19 {
20 cin = new Scanner(System.in);
21 n=cin.nextInt();
22 m=cin.nextInt();
23 if( 0==n+m ) break;
24 fun_2(n,m);
25 }
26 // cin.close();
27 }
28 //方法一: 數組模擬
29 static void fun_1(int n ,int m){
30 boolean [] arr = new boolean [n+1];
31 for(int i=0;i<=n;i++)
32 arr[i]=true;
33 //雙親數組法
34 int pos=1;
35 m--;
36 while(true){
37 int cnt=pos;
38 while(!arr[(pos+m)%(n+1)==0?1:(pos+m)%(n+1)]){
39 ++pos;
40 if(pos-cnt>=n) return ;
41 }
42 pos=(pos+m)%(n+1)==0?1:(pos+m)%(n+1);
43 arr[pos]=false;
44 System.out.println(pos);
45 ++pos;
46 }
47 }
48
49 /**
50 * 方法二: 循環鏈表模擬
51 */
52 static void fun_2(int n , int m){
53 class child{
54 int id ;
55 child next ;
56 public child(){};
57 int getId() {
58 return id;
59 }
60 child getNext() {
61 return next;
62 }
63 } ;
64
65 //模擬c循環鏈表
66 child head,a;
67 a = new child() ;
68 a.id = 1 ;
69 head = a ;
70 for(int i=2 ; i<=n ; i++ ){
71 child b = new child() ;
72 b.id = i ;
73 head.next = b ;
74 head = b ;
75 }
76 head.next = a;
77 while(a!=a.next){
78 child b=head.next;
79 for(int i=1; i<m ;i++ ){
80 b=a;
81 a=a.next;
82 }
83 System.out.println(a.id);
84 a=a.next;
85 b.next=a;
86 System.gc();
87 }
88 if(m>1) System.out.println(a.id);
89 }
90 }
?
轉載于:https://www.cnblogs.com/gongxijun/p/4107691.html
總結
以上是生活随笔為你收集整理的Java学习之约瑟夫环的两中处理方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有趣的平方和的推导
- 下一篇: 《Java程序员面试宝典》读书笔记1