知恵袋で見つけたトランプの確率の問題をJavaで解いてみました。
ジョーカーを除いた52枚のトランプから2枚を引くとき 2枚ともスペードかまたは2枚とも3以下の札である確率
カードに、0〜51の整数値を与えて、13で割った商でスート(絵柄マーク)、13で割った余りに1を加えてランク(番号)を得ることにします。ここでは、13で割った商が0のものをスペードとしました。
● ProbOfCards1.java
/* * ProbOfCards1.java * * # A 2 3 4 5 6 7 8 9 10 J Q K * S 0 1 2 3 4 5 6 7 8 9 10 11 12 * H 13 14 15 16 17 18 19 20 21 22 23 24 25 * D 26 27 28 29 30 31 32 33 34 35 36 37 38 * C 39 40 41 42 43 44 45 46 47 48 49 50 51 * */ class ProbOfCards1 { // 順列生成 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 boolean nextComb(int[] p, int n, int r) { int i; do{ if(!nextPerm(p,n,r)) return(false); for(i=0; i< r-1; i++) if(p[i]> p[i+1]) break; } while (i< r-1); 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 = 52, R = 2; int count=0, total=0; int[] c = new int[N]; // 組合せ生成用 for(int i=0; i< N; i++) c[i]=i; long tm=System.nanoTime(); // Timer Start do{ if((c[0]/13==0 && c[1]/13==0)||(c[0]%13+1<=3 && c[1]%13+1<=3)) count++; total++; }while(nextComb(c,N,R)); int g = (count!=0 ? gcd(count,total) : 1); System.out.println(count+"/"+total+"="+(count/g)+"/"+(total/g)); tm=System.nanoTime()-tm; // Timer Stop System.out.printf("Runtime : %.3f [sec]\n",(double)tm/1e9); } }
●実行結果
141/1326=47/442 Runtime : 0.016 [sec]
- 作者: 中山清喬,国本大悟
- 出版社/メーカー: インプレス
- 発売日: 2011/10/07
- メディア: 単行本(ソフトカバー)
- 購入: 6人 クリック: 28回
- この商品を含むブログ (24件) を見る
- 作者: 高橋麻奈
- 出版社/メーカー: SBクリエイティブ
- 発売日: 2013/08/29
- メディア: 単行本
- この商品を含むブログ (5件) を見る