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

Join Date: Jun 2007
Location: Urbana
Posts: 3,968
Thanks: 10
Thanked 534 Times in 516 Posts
Quote:
 Originally Posted by Old Pedant 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 13/9/26)
BROWSER STATS [% share] (2013/10/31) IE7:0.5, IE8:8.6, IE9:5.3, IE10:12.3, FF:17.7, CH:41.8, SF:8.1, MOBILE:20.4