<template>
<MyPullRefresh @clickRequest="">
<template #default>
<div class="base_div">
<div class="title">三门问题</div>
<div>
<van-field
class="base_input"
v-model="count"
label="门的个数"
placeholder="请输入门的数量"
/>
<van-field
class="base_input"
v-model="num"
label="执行次数"
placeholder="请输入执行次数"
><template #button>
<van-button size="small" type="primary" @click="runGetResult"
>执行</van-button
>
</template></van-field
>
</div>
<div class="title">
不换门中奖次数{{ noChange }}次,不换门中奖概率{{
noChange + change == 0 ? 0 : noChange / (noChange + change)
}}
</div>
<div class="title">
换门中奖次数{{ change }}次,换门中奖概率{{
noChange + change == 0 ? 0 : change / (noChange + change)
}}
</div>
</div>
</template>
</MyPullRefresh>
</template>
<script setup lang="ts">
import { useStore } from '@/store'
const store = useStore()
let count = ref(3)
// 模拟次数
let num = ref(3)
const runGetResult = () => {
for (let i = 0; i < num.value; i++) {
random()
}
}
interface countList {
index: number
value: number
}
let countList = ref<countList[]>([])
// 随机选一个门
const selectIndex = ref(0)
// 不换门中奖次数
let noChange = ref(0)
// 换门中奖次数
let change = ref(0)
const random = () => {
countList.value = []
let flag = true
for (let i = 0; i < count.value; i++) {
if (Math.random() > 0.1 && i < count.value - 1) {
countList.value.push({ index: i, value: 0 })
} else if (flag) {
countList.value.push({ index: i, value: 1 })
flag = false
} else {
countList.value.push({ index: i, value: 0 })
}
}
selectIndex.value = Math.floor(Math.random() * count.value)
// 删除 count - 2 个错误的门后剩下选择后的另一扇门
countList.value = countList.value.filter((item, i) => {
if (i == selectIndex.value) return true
if (item.value == 1) return true
})
let flags = true
for (let i = 0; i < countList.value.length; i++) {
if (
countList.value[i].value === 1 &&
countList.value[i].index == selectIndex.value
) {
noChange.value++
flags = false
break
}
}
if (flags) change.value++
}
</script>
<style scoped lang="less">
@import url('../../assets/base.less');
.van-cell {
align-items: center;
}
</style>
vue3 + ts + vite +vant 实现模拟三门问题
最新推荐文章于 2024-06-07 15:21:44 发布