gpt4 book ai didi

javascript - 我怎样才能运行一段代码直到得到相同的结果 3 次?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:57:58 25 4
gpt4 key购买 nike

如何让这段代码运行直到连续获得 3 个“蓝色”卷?

var cards = ['Blue', 'Yellow'];
var currentCard = 'Yellow';
while (currentCard !== 'Blue') {
console.log(currentCard);
var randomNumber = Math.floor(Math.random() * 2);
currentCard = cards[randomNumber]
}
console.log('Blue')

最佳答案

您可以只使用一个变量来计算蓝色已经滚动了多少次,然后在达到该数量时停止

如果你希望它在你得到黄色时重置,就像你在下面的评论中所说的那样,添加一个 else 来重置计数 :)

I need a block that increases a variable each time I get a blue card and when you get a yellow card you reset it

const cards = ['Blue', 'Yellow'];
let currentCard = 'Yellow',
blueCount = 0;

while (blueCount < 3) {
const randomNumber = Math.floor(Math.random() * 2);
console.log(currentCard);
currentCard = cards[randomNumber];

if (currentCard === 'Blue') {
blueCount++;
} else {
blueCount = 0;
}
}

console.log('Blue')

您可以在没有 while 循环的情况下完成此操作,也可以使用递归。我下面的功能不是处理它的最佳方式,但应该给你一个想法

var cards = ['Blue', 'Yellow'];

function recursiveRoll3(max = 3, target = 'Blue', count = 0, card = getRandomCard()) {
if (count === max) return;

console.log(card)

return card === target ?
recursiveRoll3(max, target, count += 1) :
recursiveRoll3(max, target);
}

function getRandomCard() {
return cards[Math.floor(Math.random() * 2)];
}

console.log('Find 3 blue rolls then stop')
recursiveRoll3()
console.log('Find 1 yellow roll then stop')
recursiveRoll3(1, 'Yellow')

这是一个使用 es6 类的完全顶级版本,希望任何人都应该能够阅读并猜测发生了什么。

class RollTimes {
constructor({ max = 0, target = null, possibilities = [] }) {
this.max = max;
this.target = target;
this.possibilities = possibilities;

this.count = 0;
this.currentCard = null;
}

roll() {
while (this.notDone) {

this.currentCard = this.getRandomCard();

console.log(this.currentCard);

this.count = this.hitTarget ? this.count + 1 : 0;
}
}

get notDone() {
return this.count < this.max;
}

get hitTarget() {
return this.currentCard === this.target;
}

get randomNumber() {
return Math.floor(Math.random() * this.possibilities.length);
}

getRandomCard() {
return this.possibilities[this.randomNumber];
}
}

const roller = new RollTimes({
max: 3,
target: 'Blue',
possibilities: ['Blue', 'Yellow']
});

roller.roll();

关于javascript - 我怎样才能运行一段代码直到得到相同的结果 3 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49858122/

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