论坛首页 综合技术论坛

Josephus 问题相关实现方法

浏览 1548 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-05-28   最后修改:2009-05-28
#include <stdio.h> 
#include <stdlib.h> 
#define N 41 
#define M 3 

int main(void) { 
    int man[N] = {0}; 
    int count = 1; 
    int i = 0, pos = -1; 
    int alive = 0; 

    while(count <= N) { 
        do { 
            pos = (pos+1) % N;  // 環狀處理 
            if(man[pos] == 0) 
                i++; 

            if(i == M) {  // 報數為3了 
                i = 0; 
                break; 
            } 
        } while(1); 

        man[pos] = count; 
        count++; 
    } 

    printf("\n約琴夫排列:"); 
    for(i = 0; i < N; i++) 
        printf("%d ", man[i]); 

    printf("\n\n您想要救多少人?"); 
    scanf("%d", &alive); 

    printf("\nL表示這%d人要放的位置:\n", alive); 
    for(i = 0; i < N; i++) { 
        if(man[i] > alive) 
            printf("D"); 
        else 
            printf("L"); 

        if((i+1) % 5 == 0) 
            printf("  "); 
    } 
    printf("\n"); 

    return 0; 
}

 

public class Josephus {
    public static int[] arrayOfJosephus(
                               int number, int per) {
        int[] man = new int[number]; 

        for(int count = 1, i = 0, pos = -1; 
                count <= number; count++) { 
            do { 
                pos = (pos+1) % number;  // 環狀處理 
                if(man[pos] == 0) 
                    i++; 

                if(i == per) {  // 報數為3了 
                    i = 0; 
                    break; 
                } 
            } while(true); 

            man[pos] = count; 
        } 
        
        return man;
    }

    public static void main(String[] args) {
        int[] man = Josephus.arrayOfJosephus(41, 3);
        int alive = 3;
        
        System.out.println("約琴夫排列:"); 
        for(int i = 0; i < 41; i++) 
            System.out.print(man[i] + " "); 


        System.out.println("\nL表示3個存活的人要放的位置:"); 
        for(int i = 0; i < 41; i++) { 
            if(man[i] > alive) 
                System.out.print("D"); 
            else 
                System.out.print("L"); 

            if((i+1) % 5 == 0) 
                System.out.print("  "); 
        } 

        System.out.println();
    }
}

 

论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics