Skip to content

Instantly share code, notes, and snippets.

@elmariachi111
Created February 25, 2022 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elmariachi111/c41edfda676de3786e61faa874360e83 to your computer and use it in GitHub Desktop.
Save elmariachi111/c41edfda676de3786e61faa874360e83 to your computer and use it in GitHub Desktop.
create NFT traits with given probability
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()
}
@elmariachi111
Copy link
Author

elmariachi111 commented Feb 25, 2022

Usage

$ node traits.js

{ trait_type: 'Food', value: 'Marshmallow' }

API

const trait = generateTrait("Food", [1000, 2500, 6500], ["Broccoli", "Avocado", "Marshmallow"]);

Testing

uncomment test() to check that it works:

[
  { Marshmallow: { count: 649944, prob: 64.9944 } },
  { Avocado: { count: 249800, prob: 24.98 } },
  { Broccoli: { count: 100256, prob: 10.025599999999999 } }
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment