Skip to content

Instantly share code, notes, and snippets.

@uhyo
Created July 1, 2024 13:35
Show Gist options
  • Save uhyo/cb2e5aae3dbf211c2023b8e4d770ab10 to your computer and use it in GitHub Desktop.
Save uhyo/cb2e5aae3dbf211c2023b8e4d770ab10 to your computer and use it in GitHub Desktop.
// 試合を繰り返して昇格する確率を求める
// ・5勝の貯金を積み上げると昇格
// ・3敗の借金を積み上げると降格
// ・借金中に勝利すると今までの借金がチャラになり+1勝になる
generateCSV();
function generateCSV() {
const header='1試合の勝率,昇格確率,降格確率,合計';
let csv = header + '\n';
for (let p = 0; p <= 100; p ++) {
const result = calculate(p / 100);
csv += `${p / 100},${result.promotionProb.toFixed(4)},${result.demotionProb.toFixed(4)},${result.sum.toFixed(4)}\n`;
}
console.log(csv);
}
/**
* @param p 1試合の勝率
*/
function calculate(p = 0.5) {
let promotionProb = 0;
let demotionProb = 0;
for (const pat of patterns()) {
let prob = 1;
for (const event of pat) {
if (event === 'WIN') {
prob *= p;
} else if (event === 'LOSE') {
prob *= 1 - p;
} else if (event === 'PROMOTE') {
promotionProb += prob;
} else if (event === 'DEMOTE') {
demotionProb += prob;
}
}
}
return {
promotionProb,
demotionProb,
sum: promotionProb + demotionProb,
};
}
/**
* 勝ち負けのパターンを生成する
*/
function* patterns(win = 0, lose = 0) {
if (win === 5) {
yield ['PROMOTE'];
return;
}
if (lose === 3) {
yield ['DEMOTE'];
return;
}
for (const winPat of patterns(win + 1, 0)) {
yield ['WIN', ...winPat];
}
for (const losePat of patterns(win, lose + 1)) {
yield ['LOSE', ...losePat];
}
}
@uhyo
Copy link
Author

uhyo commented Jul 1, 2024

image

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