tornadofx控制檯輸出「三門問題」,蒙特卡洛算法

import tornadofx.*

fun main() {
    val wins = intProperty()
    val lose = intProperty()
    val Msg = stringProperty()

//    1000萬次
    val n = 10000000
    (1..n).forEach {
        if (play(true))
            wins.value++
        if (play(false))
            lose.value++
    }
    Msg.value = "總次數:${n} -換門贏得次數:${wins.value}- 贏得機率:${wins.value.toDouble() / n} "
    println(Msg.value)
    Msg.value = "總次數:${n} -不換門贏得次數:${lose.value}- 贏得機率:${lose.value.toDouble() / n} "
    println(Msg.value)
}

fun play(changeDoor: Boolean): Boolean {
    val prizeDoor = (0..2).random()
    val playerChoice = (0..2).random()
    if (prizeDoor.equals(playerChoice)){
        if (changeDoor){
            return false
        }else{
            return true
        }
    }else{
        if (changeDoor){
            return true
        } else{
            return false
        }
    }
}

 

相關文章
相關標籤/搜索