0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

確率によりいずれかの条件に分岐する

Posted at

#実装

Branch_by_probability.cpp
#include <iterator>
#include <vector>
#include <string>
#include <iostream>
#include <random>
#include <unordered_set>

void Branch_by_probability() {//確率によりいずれかに条件分岐する
    int i;
    std::random_device seed_gen;
    std::mt19937 engine(seed_gen());//シード値は適宜変更してください
    
    std::vector<double> probability = {34.5, 25.1, 10.0, 30.4};
    std::vector<std::string> pitching = {"Fork", "Slider", "Curve", "Straight"};
    double sum = std::accumulate(probability.begin(), probability.end(), 0.0);//各々の確率の合計が100%になるかチェック
    int Psize = probability.size();//条件分岐の種類
   
    std::uniform_real_distribution<> dist(0.0, 100.0);        // [0.0, 100.0] 範囲の一様乱数

    double rand = dist(engine);//0.0~100.0の値がランダムに選ばれる
    if (sum == 100) {
        //例 確率で投球する球を決める
        for (i = 0; i < Psize; i++) {
            if (rand < probability[i]) {
                //処理(例 投球の種類を出力)
                std::cout<<"select"<<pitching[i]<<"\n";
                break;
            }
            rand -= probability[i];
        }
    }
    else {//確率の合計が100%にならないときは実行しない
        std::cout<<"fale\n";  
    }

}

"Fork", "Slider", "Curve", "Straight" のいずれかを確率をもとに選び出力するサンプルです。 "Fork", "Slider", "Curve", "Straight"のいずれかが選ばれる確率はそれぞれ
34.5,  25.1,   10.0,   30.4です。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?