Created
February 25, 2022 11:37
-
-
Save elmariachi111/c41edfda676de3786e61faa874360e83 to your computer and use it in GitHub Desktop.
create NFT traits with given probability
This file contains 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
function generateTrait(trait_type, distributions, values) { | |
const sum = distributions.reduce((prv,cur) => (cur + prv), 0); | |
if (sum !== 10000) throw ("probabilites don't add up to 100%"); | |
const traitRandomness = 10000 * p5.random(); | |
let probability = 10000; | |
for (const i in distributions) { | |
probability -= distributions[i] | |
if (traitRandomness > probability) { | |
return { trait_type, value: values[i] } | |
} | |
} | |
return { trait_type, value: values[distributions.length -1]} | |
} | |
//10% probability of Broccoli... | |
const trait = generateTrait("Food", [1000, 2500, 6500], ["Broccoli", "Avocado", "Marshmallow"]); | |
console.log(trait); | |
//test(); | |
// ---- | |
function test() { | |
const histogram = {}; | |
for(let i=1_000_000;i-->0;) { | |
const trait = generateTrait("Food", [1000, 2500, 6500], ["Broccoli", "Avocado", "Marshmallow"]); | |
if (!histogram[trait.value]) histogram[trait.value] = 0; | |
histogram[trait.value] = histogram[trait.value] + 1 | |
} | |
const total = Object.values(histogram).reduce((prv, cur) => cur + prv, 0); // 100000 | |
const prob = Object.keys(histogram).map(k => ({[k]: {count: histogram[k], prob: 100 * (histogram[k]/total)}}) ) | |
console.log(prob); | |
} | |
const p5 = { | |
random: () => Math.random() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
$ node traits.js
API
Testing
uncomment test() to check that it works: