Last active
October 8, 2020 12:40
-
-
Save Ratstail91/3fd051e5f5c3d576b79b571e3c2298b6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const pick = odds => { | |
const total = odds.reduce((a, b) => a + b); //total cards | |
const index = Math.random() * total; //card to choose | |
//NOTE: NOT using Math.floor(), as 'odds' can contain fractional values | |
//find the rarity slot that index falls into | |
let slot; | |
let running = index; //the running total, counting backwards | |
for (let i = 0; i < total; i++) { | |
if (running - odds[i] <= 0) { | |
//found it | |
slot = i; | |
break; | |
} else { | |
//count backwards | |
running -= odds[i]; | |
} | |
} | |
//"remove" the card from the odds by inflating other odds | |
let newOdds = []; | |
const inflation = 1 / (odds.length - 1); //1 / 3 for 4 cards | |
for (let i = 0; i < odds.length; i++) { | |
if (i != slot) { | |
newOdds.push(odds[i] + inflation); | |
} else { | |
newOdds.push(odds[i]); | |
} | |
} | |
//finally | |
return [newOdds, slot]; | |
}; | |
//tests | |
//test it 'amount' times | |
const testBy = (base, amount) => { | |
let odds = [...base]; | |
let slot; //the resulting rarity slot | |
//run it 'amount' times | |
for (let i = 0; i < amount; i++) { | |
[odds, slot] = pick(odds); | |
} | |
//map down the inflated values | |
return odds.map(o => o / amount); | |
} | |
const base = [11, 3, 7/8, 1/8]; //common, uncommon, rare, mythic | |
//show the resulting odds for each run of 'x' iterations | |
console.log(testBy(base, 10)) | |
console.log(testBy(base, 100)) | |
console.log(testBy(base, 1000)) | |
console.log(testBy(base, 10000)) | |
//show the percentage (tends towards 1) | |
console.log(testBy(base, 10).reduce( (a, b) => a + b )); | |
console.log(testBy(base, 100).reduce( (a, b) => a + b )); | |
console.log(testBy(base, 1000).reduce( (a, b) => a + b )); | |
console.log(testBy(base, 10000).reduce( (a, b) => a + b )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment