知恵袋の条件付き確率の問題をJavaで解いてみた。

 知恵袋の条件付き確率の問題Javaで解いたみました。

 a,b,c,d,e,f,gの7人が横一列に並ぶ。aがbより右に並ぶ事象をA、bがcより右に並ぶ事象をB、
cがdより右に並ぶ事象をCとする。Aが起こった時の、次の事象の起こりうる条件付き確率を求めよ。
(1)B (2)C (3)B∩C

※参考URL
http://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q10107605665
http://okwave.jp/qa/q550328.html
条件付き確率

● ConditionalProb1.java

/* 
 * ConditionalProb1.java
 * 
 */

class ConditionalProb1 {
    // 順列生成
    static boolean nextPerm(char[] p, int n, int r) {
        int i, j;
        char t;
        
        if(r <= 0 || n < r) return(false);
        for(i = r + 1; i <= n-1; i++)
            for(j = i; j >= r + 1 && p[j-1] < p[j]; j--){
                t = p[j]; p[j] = p[j-1]; p[j-1] = t;    // swap(p,j,j-1);
            }
        for(i = n - 1; i > 0 && p[i-1] >= p[i]; i--);
        if(i==0) return(false);
        for(j = n - 1; j > i && p[i-1] >= p[j]; j--);
        t = p[j]; p[j] = p[i-1]; p[i-1] = t;            // swap(p,j,i-1);
        for(j = n - 1; i < j; i++, j--){
            t = p[i]; p[i] = p[j]; p[j] = t;            // swap(p,i,j);
        }
        return(true);
    }
    
    // xがa[]の何番目にあるか調べるメソッド
    static int getPos(char[] a, char x) {
        for(int i=0; i<a.length; i++)
            if(a[i]==x) return(i);  // あるときは、0〜a.length-1を返す. 
        return(-1);                 // ないときは、-1を返す. 
    }
    
    static int gcd(int a, int b){
        return( b == 0 ? a : gcd(b, a % b) );
    }
    
    public static void main(String[] args) {
        final String P = "abcdef";
        final int N = P.length();
        
        char[] p = P.toCharArray();     // 順列生成用
        int iCntA = 0, iCntB = 0, iCntC = 0, iCntBC = 0;
        int g;
        
        long tm=System.nanoTime();      // Timer Start
        do{
            if(getPos(p,'b')< getPos(p,'a')) {
                iCntA++;
                boolean b = (getPos(p,'c')< getPos(p,'b'));
                boolean c = (getPos(p,'d')< getPos(p,'c'));
                if(b)       iCntB++;
                if(c)       iCntC++;
                if(b && c)  iCntBC++;
            }
        }while(nextPerm(p,N,N));
        
        g = gcd(iCntA,iCntB);
        System.out.println("(1) "+ iCntB  +"/"+ iCntA +" = "+ (iCntB /g) +"/"+ (iCntA/g));
        
        g = gcd(iCntA,iCntC);
        System.out.println("(2) "+ iCntC  +"/"+ iCntA +" = "+ (iCntC /g) +"/"+ (iCntA/g));
        
        g = gcd(iCntA,iCntBC);
        System.out.println("(3) "+ iCntBC +"/"+ iCntA +" = "+ (iCntBC/g) +"/"+ (iCntA/g));
        
        tm=System.nanoTime()-tm;        // Timer Stop
        System.out.printf("Runtime : %.3f [sec]\n",(double)tm/1e9);
    }
}

●実行結果

(1) 120/360 = 1/3
(2) 180/360 = 1/2
(3) 30/360 = 1/12
Runtime : 0.001 [sec]