Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- How this works
- 1. Given a data set with weighted probability such as:
- const items = [
- { Name: "NoDrop", Weight: 500 },
- { Name: "IronBlade", Weight: 50 },
- { Name: "MithrilBlade", Weight: 25 },
- { Name: "SoulSword", Weight: 5 },
- { Name: "BloodSword", Weight: 3 },
- { Name: "Excalibur", Weight: 1 }
- ];
- The "NoDrop" item tells us it is 500x more likely to occur
- than "Excalibur", 10x more likely to occur, than "IronBlade",
- etc.
- 2. Add up all the weights in this data set...
- M = items.reduce()
- 3. Pick a random number between [1, M]...
- P = random([1, M])
- 4. Iterate over the items. For each current item, take its weight (N) and:
- Q = P - N
- 5. If Q <= 0, then choose this item. Else, continue iterating.
- */
- const items = [
- { Name: "NoDrop", Weight: 500 },
- { Name: "IronBlade", Weight: 50 },
- { Name: "MithrilBlade", Weight: 25 },
- { Name: "SoulSword", Weight: 5 },
- { Name: "BloodSword", Weight: 3 },
- { Name: "Excalibur", Weight: 1 }
- ];
- console.log(runModel(items));
- function getSum(items) {
- return items
- .reduce((sum, currItem) =>
- ({ Weight: sum.Weight + currItem.Weight}))
- .Weight;
- }
- function runModel(items) {
- const sum = getSum(items);
- const probMap = {};
- for(let i = 0; i < 100000; i++) {
- const random =
- Math.trunc((Math.random() * sum)) + 1;
- items.forEach(val => {
- if(Math.trunc(random - val.Weight) <= 0) {
- if(probMap[val.Name] === undefined) {
- probMap[val.Name] = 0;
- }
- probMap[val.Name]++;
- }
- });
- }
- return probMap;
- }
- /*
- For 100,000 iterations here is a sample result:
- {
- NoDrop: 85656,
- IronBlade: 8577,
- MithrilBlade: 4241,
- SoulSword: 811,
- BloodSword: 487,
- Excalibur: 159
- }
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement