我对JavaScript很陌生,我一直在制作while循环,掷骰子并在你滚动6时突破循环。
var rollDice = function() {
var dice = Math.floor(Math.random() * 6 + 1);
while (dice !== 6) {
console.log("A " + dice + " was rolled!");
var dice = Math.floor(Math.random() * 6 + 1)
}
console.log("Lucky! You rolled a 6!");
}
现在我想循环遍历一个项目数组,并在找到所需项目时突破它。我希望能够像这样声明所需的项目:
var desiredItem = "Diamond";
但是,每个项目都有自己的概率值,我想在此while循环中包含它。这意味着你有25%的机会获得生锈的钉子,而只有5%的机会获得钻石。从统计上来说,你会得到比钻石更生锈的指甲。我也想在循环内向用户输出所有内容,如下所示:
console.log("Dang! A " + lootedItem + " was found...");
当你最终收到所需的项目并打破循环时:
console.log("Lucky! A" + desiredItem + "was found!");
我现在已经尝试了一段时间,但似乎无法得到它,所以任何帮助都会受到赞赏。谢谢!
答案 0 :(得分:1)
以下是ES6的实现:
var findItem = function(desiredItem) {
var items = [
{ item: "rusty nail", probability: 0.25 },
{ item: "stone", probability: 0.23 },
{ item: "banana", probability: 0.20 },
{ item: "leaf", probability: 0.17 },
{ item: "mushroom", probability: 0.10 },
{ item: "diamond", probability: 0.05 }
];
var possible = items.some( ({item, probability}) =>
item === desiredItem && probability > 0 );
if (!possible) {
console.log('There is no chance you\'ll ever find a ' + desiredItem);
return;
}
var sum = items.reduce( (sum, {item, probability}) => sum+probability, 0 );
while (true) {
var value = Math.random() * sum;
var lootedItem = items.find(
({item, probability}) => (value -= probability) <= 0 ).item;
if (lootedItem === desiredItem) break;
console.log("Dang! A " + lootedItem + " was found...");
}
console.log("Lucky! A " + desiredItem + " was found!");
}
findItem('diamond');
答案 1 :(得分:0)
您可以使用相同的方法处理您在骰子循环中使用的钻石问题。只需在1-20之间生成一个随机数,如果生成的数字为1,告诉用户他们找到了一颗钻石,因为生成1的几率是5%。
答案 2 :(得分:0)
允许任意加权概率的一般答案如下......我已经在我写过的几个游戏中成功地使用了它。
答案 3 :(得分:0)
const DIAMOND = 1,
TRASH = 0;
var treasures = [DIAMOND, TRASH, TRASH, TRASH, DIAMOND],
len = treasures.length;
function searchForDiamond() {
while (true) {
var j = Math.floor(getRandomArbitrary(0, len)),
discovery = treasures[j];
if (discovery === DIAMOND) {
console.log("I am a lucky pirate!");
break;
} else {
console.log("I am a crappy pirate!");
}
}
}
// FROM MDN
// Returns a random number between min (inclusive) and max (exclusive)
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
searchForDiamond();