約瑟夫環(約瑟夫問題)是一個數學的應用問題:已知n我的(以編號1,2,3…n分別表示)圍坐在一張圓桌周圍。從編號爲k的人開始報數,數到m的那我的出列;他的下一我的又從1開始報數,數到m的那我的又出列;依此規律重複下去,直到圓桌周圍的人所有出列。一般解決這類問題時咱們把編號從0~n-1,最後結果+1即爲原問題的解
引用別人的一個圖:直觀說明問題node
第一步:從1開始報數爲3的時候就刪除3號結點
第二步:從4號結點開始報數,當爲3的時候刪除6號結點;
第三步:從7號結點開始報數,當爲3的時候刪除1號結點;
第四步:從2號結點開始報數,當爲3的時候刪除5號結點;
第五步:從7號結點開始報數,當爲3的時候刪除2號結點;
第六步:從4號元素開始報數,當爲3的時候刪除8號結點;
第七步:又從4號開始報數,當爲3的時候刪除4號結點,此時鏈表中只有一個7號結點,因此最後的結點就是7號結點;
spa
public class 模擬 { public static void main(String[] args) { Scanner in=new Scanner(System.in); //總人數 int n=in.nextInt(); // 數到m的那我的出列 int m=in.nextInt(); // 初始化爲0 都沒有出去 int [] arr=new int[n]; //剩下的人數 int peopleLeft=n; //初始化下標 int index=0; // 下標計算器 int count=0; // >0 出循環爲負 while (peopleLeft>1){ if(arr[index]==0){ // count爲計步器 不是下標指向 count++; if(count==m){ arr[index]=1; count=0; peopleLeft--; } } index++; if(index==arr.length){ index=0; } } for (int i = 0; i < arr.length; i++) { if(arr[i]==0){ System.out.println(i+1); } } } }
/** * 遞歸式: * f(1)=0; 第一個位置永遠爲0 * f(i)=f(i)+m%n; */ public static int yuesefu(int n,int m){ if(n==1){ return 0; }else { return (yuesefu(n-1,m) + m) % n; } } public static void main(String[] args) { System.out.println(yuesefu(41,3)+1); vailCode(41,3); } //逆推驗證代碼 public static void vailCode(int a,int b){ System.out.print(b); int reslut; for (int i = a; i >=2 ; i--) { reslut=2; for (int j = i; j <=a ; j++) { reslut=(reslut+b)%j; } System.out.printf("->%d",reslut+1); } }
public class CircularLinkedList { public static void main(String[] args) { /** * 節點類 */ class Node{ private int data=1; private Node next; Node(){ next=null; } } Node head,temp; head=new Node(); head.data=1; int a=41; int b=3; // 臨時節點 temp=head; for (int i = 0; i < a; i++) { Node new_node=new Node(); new_node.data=i+1; temp.next=new_node; temp=new_node; } temp.next=head.next; while (head.next!=head){ for (int i = 0; i < b-1; i++) { head=head.next; } System.out.print("->"+(head.data+1)); head.next=head.next.next; } System.out.println(head.data); } }
解法一.net
public static void main(String[] args) { int a=41; int b=3; LinkedList<Integer> list = new LinkedList<>(); for (int i = 0; i < a; i++) { list.add(i+1); } while (list.size()>1){ for (int i = 0; i < b-1; i++) { list.add(list.remove()); } System.out.print("->"+list.getFirst()); list.remove();//remve head } System.out.println(list.getFirst()); }
解法二code
1: remove() 移除空間減一 i--;blog
2: 須要控制邏輯下標的值 惟一性遞歸
public static int getLucklyNum(int num) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= num; i++) { list.add(i); } System.out.println(list); int count = 1; for (int i = 0; list.size() != 1; i++) { if (i == list.size()) { i = 0; } if (count % 3 == 0) { list.remove(i--); // i-- 因爲ArrayList 具備resize()的內部功能維持,remove() 操做之後 size() 自動減一, 若是i不減一,將表示約瑟夫環 從下一個的下一個從新開始數,結果確定是錯誤的 count = 0; } count++; } return list.get(0); }