Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. /*
  2. How this works
  3.  
  4. 1. Given a data set with weighted probability such as:
  5.  
  6. const items = [
  7. { Name: "NoDrop", Weight: 500 },
  8. { Name: "IronBlade", Weight: 50 },
  9. { Name: "MithrilBlade", Weight: 25 },
  10. { Name: "SoulSword", Weight: 5 },
  11. { Name: "BloodSword", Weight: 3 },
  12. { Name: "Excalibur", Weight: 1 }
  13. ];
  14.  
  15. The "NoDrop" item tells us it is 500x more likely to occur
  16. than "Excalibur", 10x more likely to occur, than "IronBlade",
  17. etc.
  18.  
  19. 2. Add up all the weights in this data set...
  20.  
  21. M = items.reduce()
  22.  
  23. 3. Pick a random number between [1, M]...
  24.  
  25. P = random([1, M])
  26.  
  27. 4. Iterate over the items. For each current item, take its weight (N) and:
  28.  
  29. Q = P - N
  30.  
  31. 5. If Q <= 0, then choose this item. Else, continue iterating.
  32. */
  33.  
  34. const items = [
  35. { Name: "NoDrop", Weight: 500 },
  36. { Name: "IronBlade", Weight: 50 },
  37. { Name: "MithrilBlade", Weight: 25 },
  38. { Name: "SoulSword", Weight: 5 },
  39. { Name: "BloodSword", Weight: 3 },
  40. { Name: "Excalibur", Weight: 1 }
  41. ];
  42.  
  43. console.log(runModel(items));
  44.  
  45. function getSum(items) {
  46. return items
  47. .reduce((sum, currItem) =>
  48. ({ Weight: sum.Weight + currItem.Weight}))
  49. .Weight;
  50. }
  51.  
  52. function runModel(items) {
  53. const sum = getSum(items);
  54. const probMap = {};
  55.  
  56. for(let i = 0; i < 100000; i++) {
  57. const random =
  58. Math.trunc((Math.random() * sum)) + 1;
  59.  
  60. items.forEach(val => {
  61. if(Math.trunc(random - val.Weight) <= 0) {
  62. if(probMap[val.Name] === undefined) {
  63. probMap[val.Name] = 0;
  64. }
  65. probMap[val.Name]++;
  66. }
  67. });
  68. }
  69.  
  70. return probMap;
  71. }
  72.  
  73.  
  74. /*
  75. For 100,000 iterations here is a sample result:
  76.  
  77. {
  78. NoDrop: 85656,
  79. IronBlade: 8577,
  80. MithrilBlade: 4241,
  81. SoulSword: 811,
  82. BloodSword: 487,
  83. Excalibur: 159
  84. }
  85. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement