LightningFlowComponents icon indicating copy to clipboard operation
LightningFlowComponents copied to clipboard

Fixed Bias in ReturnNRandomRecords When Selecting Random Records

Open BlenderItUp opened this issue 1 year ago • 3 comments

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) image

BlenderItUp avatar Jun 24 '24 11:06 BlenderItUp

@BlenderItUp Did you also run the Test Class multiple times to make sure that it behaved as expected?

ericrsmith35 avatar Jun 24 '24 12:06 ericrsmith35

@BlenderItUp Did you also run the Test Class multiple times to make sure that it behaved as expected?

Yes image

BlenderItUp avatar Jun 24 '24 12:06 BlenderItUp

image Here is the change in our production org. As you can see from the 28th, one is no longer created more than the others

BlenderItUp avatar Jul 02 '24 23:07 BlenderItUp

Thanks for spotting and fixing!

alexed1 avatar Jul 05 '24 01:07 alexed1