gpt4 book ai didi

javascript - 如何保证循环中随机出现一定次数?

转载 作者:行者123 更新时间:2023-12-04 14:45:54 25 4
gpt4 key购买 nike

我有一个模拟时钟指针旋转的程序,它随机跳转正常旋转量的 2 倍。我需要保证在一个完整的轮换中,我至少会跳 n 次。我应该如何随机化它但确保至少 n 次跳跃?

我考虑过每 x 次迭代都有一个有保证的跳跃,但它不是随机的。

这是我的旋转循环的代码:

for (let i = 0; i < ticks; i++) {           
// Move the clockhand by a position, sometimes by a greater amount
setTimeout(() => {
let d = Math.random();
jump = false;
// Randomize and keep track of jumps
if (d < (probabilty/100)) {
jump = true;
}
}
}

最佳答案

一种方法是设置每次完整旋转的 MAX_JUMPSMAX_TICKS 数量,然后跟踪每次迭代中执行的跳跃和滴答数量。如果跳跃和刻度仍未达到最大数量,则在它们之间随机选择。如果其中一个达到最大值,则只需选择另一个直到轮换完成。

这是一个工作示例,其中保证正好 5 跳转。请注意,我将 DISTANCE 设置为仅 30,因为代码段控制台不会显示很多行。此外,超时延迟设置为 0 只是为了快速显示完整结果。

const DISTANCE = 30 // change to 60
const MAX_JUMPS = 5
const MAX_TICKS = DISTANCE - 2 * MAX_JUMPS
const PROBABILITY = 0.25

let currentDistance = 0
let normalTicks = 0
let jumps = 0

function oneTick() {
if (currentDistance === DISTANCE) {
// Completed full rotation
console.log('normalTicks = ', normalTicks, ', jumps = ', jumps)
return
}

setTimeout(() => {
if (normalTicks === MAX_TICKS) {
// If we are out of normal ticks then just jump
// to satisfy the MAX_JUMPS amount
jump()

} else if (jumps === MAX_JUMPS) {
// If we run out of jumps, do normal tick
normal()

} else {
// If both ticks and jumps are available then randomly choose one
if (Math.random() > PROBABILITY) {
normal()
} else {
jump()
}

}

console.log(currentDistance)
oneTick()
}, 0 /* change to 1000 */)
}

function normal() {
normalTicks += 1
currentDistance += 1
}

function jump() {
jumps += 1
currentDistance += 2
console.log('JUMPED! Jumps left: ', MAX_JUMPS - jumps)
}

oneTick()
.as-console-wrapper {
min-height: 200px;
top: 0;
}

编辑:要使其至少执行 MAX_JUMPS 并在之后随机执行更多跳跃,只需删除 if (jumps === MAX_JUMPS) 阻止:

const DISTANCE = 30 // change to 60
const MAX_JUMPS = 5
const MAX_TICKS = DISTANCE - 2 * MAX_JUMPS
const PROBABILITY = 0.25

let currentDistance = 0
let normalTicks = 0
let jumps = 0

function oneTick() {
if (currentDistance >= DISTANCE) {
console.log('normalTicks = ', normalTicks, ', jumps = ', jumps)
return
}

setTimeout(() => {
if (normalTicks === MAX_TICKS) {
jump()
} else {
if (Math.random() > PROBABILITY) {
normal()
} else {
jump()
}
}

console.log(currentDistance)
oneTick()
}, 0 /* change to 1000 */ )
}

function normal() {
normalTicks += 1
currentDistance += 1
}

function jump() {
jumps += 1
currentDistance += 2
console.log('JUMPED! Jumps performed: ', jumps)
}

oneTick()
.as-console-wrapper {
min-height: 200px;
top: 0;
}

请注意,这可能会导致它在旋转的最后一个刻度处跳跃,因此您必须决定是否应将其计为单个刻度,或者是否应将额外的刻度添加到下一个旋转中。

关于javascript - 如何保证循环中随机出现一定次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70061397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com