Skip to content

Instantly share code, notes, and snippets.

@doraiso
Created March 18, 2022 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doraiso/cd044635678112771a82a80e955fa154 to your computer and use it in GitHub Desktop.
Save doraiso/cd044635678112771a82a80e955fa154 to your computer and use it in GitHub Desktop.
n人中、k人が同じ誕生日である確率p(パーセンテージ)を求める
package algorithm.birthday;
/**
* n人中、k人が同じ誕生日である確率p(パーセンテージ)を求める
* Display the probability p (percentage) that k people out of n have the same birthday.
* @author ryosuke
*
*/
// TODO n人中k人が同じ誕生日である確率を求めたが、n人中2~k人が同じ誕生日を求める確率を求めたい。
// TODO n,kはプログラム中にあるため、汎用化のためinputを工夫する必要がある。mainの引数でn,kが入れられるように
// TODO Pythonのほうが楽だろうなあ
public class GetProvSameBirthday {
// 年 グレゴリオ暦 Wikipedia
private final static Double YEAR = 365.25;
public static void main(String[] args) {
// フォロワー数 n
int n = 100;
// 誕生日がかぶる人 k
int k = 3;
// 組み合わせ nCk
// TODO: importできなかったので再チェック
double nCk = org.apache.commons.math3.util.CombinatoricsUtils.binomialCoefficientDouble(n, k);
// 確率計算 Probability
double p = nCk *
Math.pow((double) (1 / YEAR), (double) k) *
Math.pow((double) (YEAR - 1 / (YEAR)), (double) (n - k));
// change Percentage
double percent = p * 100;
String resultStr = String.valueOf(n).concat("人中、")
.concat(String.valueOf(k)).concat("人の誕生日が一致する確率は")
.concat(String.valueOf(percent)).concat("% です。");
System.out.println(resultStr);
// 階乗の計算 5! ライブラリにこんなのもある
// double reflection = CombinatoricsUtils.factorial(5);
// 参考資料
// https://commons.apache.org/proper/commons-math/javadocs/api-3.6/index.html?overview-tree.html
// https://www.monotalk.xyz/blog/Perform-factorial-permutation-and-combination-calculations-in-Python-Java-JavaScript/
// https://style.potepan.com/articles/27988.html
// https://www.javatpoint.com/float-vs-double-java
}
}
@doraiso
Copy link
Author

doraiso commented Mar 18, 2022

とりあえず作った

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment