知恵袋の色玉の確率の問題をJavaで解いてみました。(^_^;
赤球5個,青球4個,白球3個が入っている袋から,1個ずつ3回球を取り出すとき,次の確率を求めよ。ただし,取り出した球は袋の中に戻さないものとする。
(1)取り出される3個の球がすべて同じ色である確率
(2)取り出される3個の球がすべて異なる色である確率
色玉に次のように番号をつけると、番号を5で割った整数の商がそれぞれの色を表します。
赤玉(0): 0,1,2,3,4
青玉(1): 5,6,7,8
白玉(2): 10,11,12
● ProBall2.java
/* * ProBall2.java * * N=12, R=3, Q=5 * 赤玉(0): 0,1,2,3,4 * 青玉(1): 5,6,7,8 * 白玉(2): 10,11,12 * */ public class ProBall2 { // 順列生成 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 = 3, Q = 5; int[] p = {0,1,2,3,4,5,6,7,8,10,11,12}; int iTotal=0, iCount1=0, iCount2=0, g=1; long tm=System.currentTimeMillis(); // Timer Start do{ iTotal++; if(p[0]/Q==p[1]/Q && p[0]/Q==p[2]/Q) iCount1++; if(p[0]/Q!=p[1]/Q && p[0]/Q!=p[2]/Q && p[1]/Q!=p[2]/Q) iCount2++; }while(nextPerm(p,N,R)); System.out.print("(1)"); if(iCount1!=0) g=gcd(iCount1, iTotal); System.out.printf("%3d / %d = %d / %d\n",iCount1,iTotal,iCount1/g,iTotal/g); System.out.print("(2)"); if(iCount2!=0) g=gcd(iCount2, iTotal); System.out.printf("%3d / %d = %d / %d\n",iCount2,iTotal,iCount2/g,iTotal/g); tm=System.currentTimeMillis()-tm; // Timer Stop System.out.printf("Runtime : %.3f [sec]\n",(double)tm/1000.0); } }
●実行結果
(1) 90 / 1320 = 3 / 44 (2)360 / 1320 = 3 / 11 Runtime : 0.016 [sec]