知恵袋の色玉の確率の問題をJavaで解いてみた。(3)

 前回、Python で解いてみた知恵袋の色玉の確率の問題を今回は Java で解き直してみました。(^_^;

 黒玉3個、赤玉4個、白玉5個が入っている袋から玉を1個ずつ取り出し、取り出した玉を順に横一列に12個すべて並べる。ただし、袋から個々の玉が取り出される確率は等しいものとする。
(1) どの赤玉も隣り合わない確率を求めよ。
(2) どの赤玉も隣り合わないとき、どの黒玉も隣り合わない条件付き確率を求めよ。

 確率は同じものでも区別して考えるの基本なので、Java で 12 個の順列(約 4.8 億回ループ)を回すことにしました。色玉に次のように番号をつけると、番号を5で割った整数の商がそれぞれの色を表します。

白玉(0) 0,1,2,3,4
赤玉(1) 5,6,7,8
黒玉(2) 10,11,12

● BallsPro1.java

/**
 * BallsPro1.java
 * 
 * N=12, R=12, Q=5
 * 白玉(0) 0,1,2,3,4
 * 赤玉(1) 5,6,7,8
 * 黒玉(2) 10,11,12
 */

public class BallsPro1 {
	// 順列生成
	static boolean nextPerm(int[] p, int n, int r) {
        int i, j;
        int 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 int N = 12, R = 12, Q = 5;
		char[] C  = "WRB".toCharArray();
		int[] p = {
			 0, 1, 2, 3, 4,
			 5, 6, 7, 8,
			10,11,12,
		};
		int iCount = 0, iCount1 = 0, iCount2 = 0, g = 1;
		
		long tm=System.currentTimeMillis();	// Timer Start
		do{
			iCount++;
			String s = "";
			for (int i = 0; i< N; i++) s += C[p[i]/Q];
			// System.out.printf("%s\n",s);
			if(! s.contains("RR")) {
				iCount1++;
				if(! s.contains("BB"))
					iCount2++;
			}
		}while(nextPerm(p,N,R));
		
		if(iCount1!=0) g=gcd(iCount1, iCount);
		System.out.printf("(1) %3d / %d = %d / %d\n",iCount1,iCount,iCount1/g,iCount/g);
		if(iCount2!=0) g=gcd(iCount2, iCount1);
		System.out.printf("(2) %3d / %d = %d / %d\n",iCount2,iCount1,iCount2/g,iCount1/g);
		tm=System.currentTimeMillis()-tm;	// Timer Stop
		System.out.printf("Runtime : %.3f [sec]\n",(double)tm/1000.0);
	}
}

●実行結果

(1) 121927680 / 479001600 = 14 / 55
(2) 74753280 / 121927680 = 103 / 168
Runtime : 783.570 [sec]

 さすがに遅いので、Gemini に相談して、12 個の順列を回すことを条件に高速化してもらいました。(^_^;
 凄く速くなりました。(約15倍速)o(^-^)o
 ちなみに、C++ では、こちらの環境 (Core2Duo: Deep Blue の約 2 倍の処理能力) で、約43秒ぐらいでした。(^_^;
 Gemini による説明と高速化のポイントは以下の通りです。

 提示されたプログラムの最大のボトルネックは、ループ(約4.8億回)の中で毎回 String オブジェクトの結合(s += ...)を行い、さらに contains による文字列検索を行っている点です。Javaにおいて、ループ内での頻繁な文字列生成はガベージコレクション(GC)の多発を引き起こし、著しくパフォーマンスを低下させます。
 「ループ回数を変えない(全順列を走査する)」という制約を維持したまま高速化するには、文字列の生成を一切やめ、数値の配列と直前の状態の比較(プリミティブ型のみの処理)に置き換えるのが最も効果的です。

・高速化のポイント
1. 文字列操作(String / contains)の完全な排除
 元のコードで行っていた s += C[p[i]/Q] による文字列の新規生成と、s.contains("RR") による文字探索をすべて廃止しました。代わりに、1つのループ内で「1つ前の球の色(prevColor)」を保持し、現在の色と比較するフラグ管理(hasRR, hasBB)に切り替えたことで、メモリ消費量(ヒープ割り当て)がほぼゼロになり、CPUの演算効率が最大化されます。
2. 割算のキャッシュ化(colorMap の導入)
 ループ内で毎回 p[i] / Q(整数の割り算)を行うのはCPUにとって比較的重い処理です。あらかじめ 0 ~ 12 の数値がどの色(0, 1, 2)に対応するかを colorMap 配列に格納しておくことで、ループ内は配列のインデックス参照(超高速)のみで済むようにしました。

● BallsPro1a.java

/**
 * BallsPro1a.java
 */

public class BallsPro1a {
    // 順列生成 (変更なし)
    static boolean nextPerm(int[] p, int n, int r) {
        int i, j;
        int 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;
            }
        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;
        for(j = n - 1; i < j; i++, j--){
            t = p[i]; p[i] = p[j]; p[j] = t;
        }
        return(true);
    }
    
    static int gcd(int a, int b){ return( b == 0 ? a : gcd(b, a % b) ); }
    
    public static void main(String[] args) {
        final int N = 12, R = 12, Q = 5;
        int[] p = {
             0, 1, 2, 3, 4,
             5, 6, 7, 8,
            10,11,12,
        };
        int iCount = 0, iCount1 = 0, iCount2 = 0, g = 1;
        
        // 【高速化1】p[i]/Q の除算をなくすため、あらかじめ球の値に対する「色(0:W, 1:R, 2:B)」を配列にキャッシュ
        int[] colorMap = new int[13];
        for (int i = 0; i < colorMap.length; i++)
            colorMap[i] = i / Q;
        
        long tm=System.currentTimeMillis(); // Timer Start
        do{
            iCount++;
            
            // 【高速化2】文字列を作らず、配列の隣り合う要素をチェックする
            boolean hasRR = false;
            boolean hasBB = false;
            int prevColor = -1; // 直前の球の色
            
            for (int i = 0; i < N; i++) {
                int currentColor = colorMap[p[i]];
                
                if (prevColor == 1 && currentColor == 1) hasRR = true;
                if (prevColor == 2 && currentColor == 2) hasBB = true;
                prevColor = currentColor;
            }
            
            if (!hasRR) {
                iCount1++;
                if (!hasBB) {
                    iCount2++;
                }
            }
        }while(nextPerm(p,N,R));
        
        if(iCount1!=0) g=gcd(iCount1, iCount);
        System.out.printf("(1) %3d / %d = %d / %d\n",iCount1,iCount,iCount1/g,iCount/g);
        if(iCount2!=0) g=gcd(iCount2, iCount1);
        System.out.printf("(2) %3d / %d = %d / %d\n",iCount2,iCount1,iCount2/g,iCount1/g);
        tm=System.currentTimeMillis()-tm;   // Timer Stop
        System.out.printf("Runtime : %.3f [sec]\n",(double)tm/1000.0);
    }
}

●実行結果

(1) 121927680 / 479001600 = 14 / 55
(2) 74753280 / 121927680 = 103 / 168
Runtime : 51.045 [sec]

※参考URL
●Google Gemini
●知恵袋の色玉の確率の問題をPythonで解いてみた。 - rscのブログ
●知恵袋の色玉の確率の問題をJavaで解いてみた。 - rscのブログ
●知恵袋の色玉の確率の問題をJavaで解いてみた。(2) - rscのブログ

明解Java 入門編

明解Java 入門編

Amazon