1 public class Josephus { 2 public static int[] arrayOfJosephus( int number, int per) { 3 4 int[] man = new int[number]; 5 6 for(int count = 1, i = 0, pos = -1; 7 count <= number; count++) { 8 do { 9 pos = (pos+1) % number; // 環狀處理 10 if(man[pos] == 0) 11 i++; 12 13 if(i == per) { // 報數為3了 14 i = 0; 15 break; 16 } 17 } while(true); 18 19 man[pos] = count; 20 } 21 22 return man; 23 } 24 25 public static void main(String[] args) { 26 int[] man = Josephus.arrayOfJosephus(41, 3); 27 int alive = 3; 28 29 System.out.println("約瑟夫排列:"); 30 for(int i = 0; i < 41; i++) 31 System.out.print(man[i] + " "); 32 33 34 System.out.println("\nL表示3個存活的人要放的位置:"); 35 for(int i = 0; i < 41; i++) { 36 if(man[i] > alive) 37 System.out.print("D"); 38 else 39 System.out.print("L"); 40 41 if((i+1) % 5 == 0) 42 System.out.print(" "); 43 } 44 45 System.out.println(); 46 } 47 }
时间: 2024-10-25 21:21:13