上周我遇到了一些我正在做的简单程序的问题,而且有人帮我了。现在我遇到了另一个问题。 我目前有这个代码:
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 === 'diamond') break;
console.log("Dang! A " + lootedItem + " was found...");
}
console.log("Lucky! A " + desiredItem + " was found!");
}
findItem('diamond');
&#13;
现在,我想通过向category
数组添加另一个名为items
的值来扩展此功能。我希望类别的值为2
,5
或10
。因此,我们假设diamond
项属于category: 10
,执行findItem
时,只能找到属于同一类别的项目。我现在已经尝试了几天,但似乎无法理解它。也许有人可以帮我推动正确的方向?提前致谢
答案 0 :(得分:3)
您可以将此更新用于该代码:
example.domain.tld to domain.tld/foo/example-foo.html
变化是:
example.domain.tld/foo/
测试的问题 - 它有“钻石”硬编码。答案 1 :(得分:1)
你想要这样的东西吗?
var items = [ { item: "rusty nail", probability: 0.25, category: 10 }
, { item: "stone", probability: 0.23, category: 5 }
, { item: "banana", probability: 0.20, category: 2 }
, { item: "leaf", probability: 0.17, category: 5 }
, { item: "mushroom", probability: 0.10, category: 2 }
, { item: "diamond", probability: 0.05, category: 10 }
];
findItem("diamond", items);
function findItem(needle, haystack) {
var item = haystack.find(thing => thing.item === needle &&
thing.probability > 0);
if (item) {
var category = item.category;
var items = haystack.filter(thing => thing.category === category);
var sum = items.reduce((sum, thing) => sum + thing.probability, 0);
var value = sum * Math.random();
var loot = items.find(thing => (value -= thing.probability) <= 0).item;
while (loot !== needle) {
value = sum * Math.random();
console.log("Dang! A " + loot + " was found...");
loot = items.find(thing => (value -= thing.probability) <= 0).item;
}
return console.log("Lucky! A " + needle + " was found!");
}
console.log("There's no chance that you'll ever find a " + needle);
}
&#13;
与您的代码唯一的主要区别是我使用filter
来限制搜索。