Forceea Tip: Random values with specific probability

Use case 1

Sometimes we want to create random values which have a specific probability. For example, let's say we need to create random values for a picklist field of 3 picklist values One, Two and Three, with:

  • probability 25% for One

  • probability 50% for Two

  • probability 25% for Three

Solution 1

The definition will always be random type(list). In this case, the value parameter should be

value(One, Two, Two, Three)

Since we have 4 value arguments, the picklist value Two exists 2 times, so its probability will be twice as the probability of the other values One and Three. The probability of all is 100%, so the probability for One is 25% and for Two is 50%, as required.

This logic can be expanded to as many values we want. So, the following definition

random type(list)
    value(One, One, One, Two, Two, Two, Two, Three, Three, Four)

will generate random picklist values with :

  • probability 30% for One

  • probability 40% for Two

  • probability 20% for Three

  • probability 10% for Four

Use case 2

If you notice that this technique is not scalable, you are right - it isn't! For example, we may require to have 10 picklist values with probability 15% for the first, 8% for the second, 23% for the third, and so on. How can we do this?

Solution 2

The answer is: with variables! But we need some development to achieve this. Let's see how.

The first step is to create a List<String> items which will contain the number of each picklist value, based on the required probability. In our example, it will have 10 times the picklist value One, 8 times the picklist value Two, etc. It doesn't matter where in the list the values will be. As long as we have the correct number of occurrences, we are fine.

The second step is to convert the list to a comma-separated string. This is easy:

String str = String.join(items, ',');

And finally, the last step is to create the Forceea variable (we called it picklistValues) and assign it:

.setVariable('picklistValues', str)
.setDefinition(MyPicklist__c, 'random type(list) value(@picklistValues)