View Single Post
Old 01-25-2013, 02:35 PM   PM User | #13
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,469
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by Old Pedant View Post
And you really thing that is simpler and easier to understand than my table-based scheme?
.
it's not easier to understand, it's easier to maintain. in a table, adding a new class or changing a value almost guarantees that you'll need to edit several cells to "reCalc" the table.

with an iterative counter, you let the JS do the work.

i admit the tokens are a little simplistic for precise or complex calculations, but for many simple problems, it's a workable design pattern.


you can use an object instead of an array, you would have to sum all the values in the object, and then you have the same info as my item counter:


Code:
// util pure functions:
function sum(a,b){return a+b;}
function lut(key){return this[key];}


//object-based calculator:
function combinedProb(rareness, weapon){
  return (rarity[rareness] / rarity.sum) *
       (weapons[weapon] / weapons.sum);
}

//new data structure:
var rarity ={ common: 6,  uncommon:2, rare:2 };
var weapons ={ sword:4, bow:2,  staff:2 };

//pre-calc the whole to assist calcing the part each time:
rarity.sum=Object.keys(rarity).map(lut,rarity).reduce(sum);
weapons.sum=Object.keys(weapons).map(lut,weapons).reduce(sum);


//test it:
combinedProb("common", "staff"); //0.15
combinedProb("uncommon", "staff"); //0.05
combinedProb("common", "sword"); //0.3
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%
rnd me is offline   Reply With Quote