Fixed Bias in ReturnNRandomRecords When Selecting Random Records
Problem: The current implementation of the random number generation in the ReturnNRandomRecords flow action uses the following code:
Integer randomNumber = (Integer)Math.round(Math.random() * (inputCollection.size() - 1));
This approach favors middle numbers because they have a higher range for being picked. For example:
0 = 0 to 0.499, 1 = 0.5 to 1.499, 2 = 1.5 to 2 This results in a biased distribution, where middle indices are selected more frequently.
Example Distribution Before Change: Test Account 0: 253 Test Account 1: 493 Test Account 2: 254 Test Account 0: 247 Test Account 1: 514 Test Account 2: 239
Replacing with
Integer randomNumber = (Integer)Math.floor(Math.random() * inputCollection.size());
Test Account 0: 1714 Test Account 1: 1608 Test Account 2: 1678
Impact: This change ensures that each index in the collection has an equal probability of being selected, thus removing any bias and improving the fairness of the random selection process.
Below image shows the problem over time (top three lines are tasks being created with ReturnNRandomRecords)
@BlenderItUp Did you also run the Test Class multiple times to make sure that it behaved as expected?
@BlenderItUp Did you also run the Test Class multiple times to make sure that it behaved as expected?
Yes
Here is the change in our production org. As you can see from the 28th, one is no longer created more than the others
Thanks for spotting and fixing!