質問のくじ引きの確率の問題をJavaで解いてみた。

 質問のくじ引きの確率の問題Javaで解いてみました。(^_^;

10本のくじの中に3本の当たりくじと1本のチャンスくじとがある チャンスくじを引いたときは引き続きもう一度ひくものとする 甲、乙の順でくじをひくとき、それぞれお当たりくじを引く確率を求めよ ただし、1回に1本ずつくじをひき、引いたくじは元に戻さないとする

※参考URL
http://oshiete.goo.ne.jp/qa/8792630.html
http://okwave.jp/qa/q2118560.html

 くじにa〜jの名前を付けて、a,b,cを当たりくじ(○)、dをチャンスくじ(△)、e,f,g,h,i,jをはずれくじ(×)としました。当たりはずれの判定は、char型の大小比較を用いました。a,b,c < d < e,f,g,h,i,j
 また、順列を生成するのに、チャンスくじdを含む場合と含まない場合で引く回数(nPrのrに相当)が異なるので場合分けしました。

● Lottery1.java

/*
 * Lottery1.java
 * 
 */

class Lottery1 {
    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);
    }
    
    static int gcd(int a, int b){
        return( b == 0 ? a : gcd(b, a % b) );
    }
    
    public static void main(String[] args) {
        final String P = "abcdefghij";  // ○a,b,c,△d,×e,f,g,h,i,jとする
        char[] p = P.toCharArray();     // 順列生成用
        int n = p.length;
        int total = 0, countKou = 0, countOtu = 0, g = 1;
        long tm = System.nanoTime();    // Timer Start
        
        //--- チャンスくじ d を含まない場合 ---//
        do{
            if(p[0]=='d' || p[1]=='d') continue;
            total++;
            if(p[0]< 'd') countKou++;
            if(p[1]< 'd') countOtu++;
        }while(nextPerm(p,n,2));
        //--- チャンスくじ d を含む場合 ---//
        p = P.toCharArray();
        do{
            if(p[0]!='d' && p[1]!='d') continue;
            total++;
            if(p[0]< 'd' || p[1]< 'd') countKou++;
            if(p[2]< 'd')              countOtu++;
        }while(nextPerm(p,n,3));        
        g = gcd(total, countKou);
        System.out.printf("(甲) %d / %d = %d / %d\n", countKou, total, countKou/g, total/g);
        g = gcd(total, countOtu);
        System.out.printf("(乙) %d / %d = %d / %d\n", countOtu, total, countOtu/g, total/g);
        tm=System.nanoTime()-tm;        // Timer Stop
        System.out.printf("Runtime : %.3f [sec]\n",(double)tm/1e9);
    }
}

●実行結果

(甲) 72 / 216 = 1 / 3
(乙) 72 / 216 = 1 / 3
Runtime : 0.022 [sec]









スッキリわかるJava入門 第2版 (スッキリシリーズ)

スッキリわかるJava入門 第2版 (スッキリシリーズ)

わかりやすいJava入門編

わかりやすいJava入門編