LoginSignup
1
2

Julia で,「モンティ・ホール問題を愚直にやってみる」

Posted at

Julia でやってみると以下のようになる。

元記事
モンティ・ホール問題を愚直にやってみる
https://qiita.com/bkh4149/items/93adeaa46c77efb8ae73

using Random

# モンティ・ホール問題のシミュレーション

function monty_hall_simulation(num_trials::Int)
    stay_wins = 0 # ドアを変えない場合の勝利回数
    switch_wins = 0 # ドアを変えた場合の勝利回数
    
    for _ in 1:num_trials
        # 3つのドアと1つの正解ドアをランダムに配置
        doors = Random.shuffle([false, false, true])
        
        # プレイヤーが最初にランダムに1つのドアを選択
        player_choice = rand(1:3)
        
        # ホストが正解ドア以外かつプレイヤーが選んでいないドアを開ける
        host_choices = [i for i in 1:3 if i != player_choice && !doors[i]]
        host_open = rand(host_choices)
        
        # プレイヤーがドアを変えない場合
        stay_choice = player_choice
        
        # プレイヤーがドアを変える場合
        switch_choice = [i for i in 1:3 if i != player_choice && i != host_open][1]
        
        # 勝敗を判定
        stay_wins += doors[stay_choice]
        switch_wins += doors[switch_choice]
    end
    
    stay_win_percentage = stay_wins / num_trials * 100
    switch_win_percentage = switch_wins / num_trials * 100
    
    println("ドアを変えない場合の勝率: $stay_win_percentage%")
    println("ドアを変えた場合の勝率: $switch_win_percentage%")
end

# シミュレーションを実行
monty_hall_simulation(10000000) # 10000000回試行

ドアを変えない場合の勝率: 33.33347%
ドアを変えた場合の勝率: 66.66653%
1
2
0

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
1
2