I'm creating an API server in Perl 6, using the Cro framework! The purpose of this API is to serve data about Pokemon, and provide endpoints for generating Pokemon based on input data. One of the factors in generation is gender
, in my PostgreSQL database each reference Pokemon has a gender-ratio
column which contains a JSON value looking like this:
"gender-ratio": {
"default": {
"Male": 0.25,
"Female": 0.75
},
"alolan": {
"Male": 0.25,
"Female": 0.75
}
},
You'll notice I have two keys there called default
and alolan
, this is because Pokemon can have various forms but it's mostly irrelevant to this question - what is relevant are the actual gender ratio values. Here's what my generation method looks like currently:
method select-gender($pokemon, $form = 'default') {
enum GENDER ( <Male Female> );
return GENDER.pick;
}
By default pick
is random, and in this case 50/50. However I'd like to be able to weight the randomness of each option, based on the results of the ratio returned from the database. One of my ideas was to seed the GENDER
enum with the results of a database query so it would look more like this for the specific example:
enum GENDER ( <Male Female Female Female> );
Unless anyone else has any better ideas about dynamically altering the behaviour of pick
based on the result of my SELECT
statement?
Use a Mix and roll
:
my %gender-ratio = %(default => {
"Male" => 0.25,
"Female" => 0.75
},
alolan => {
"Male" => 0.25,
"Female" => 0.75
}
);
my Mix $default = %gender-ratio<default>.Mix;
for ^10 {
say $default.roll;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With