Choose a Winner at Random: The Salesforce Way (Part 2)

Choose a Winner at Random: The Salesforce Way (Part 2)

In my previous article, I discussed how to generate a random number using Apex and how to best approach it with the method math.random() that is available to us.

Now, let's take it a step further and expand its functionality to receive a lower and upper value and generate a random number between these two values.

Now you cannot just math.mod() the randomly generated value with the number of entries as the lowest value can be zero. You also cannot just add your result with the lower value as that can result in possibly getting a value bigger than your upper value.

So how do we go about doing it?

The formula to use boils down to:

math.mod((math.random() * MULTIPLIER), upperValue - lowerValue + 1) + lowerValue

Let’s use example inputs of lowerValue = 3 and upperValue = 8 .

So then the equation changes to:

math.mod((math.random() * MULTIPLIER), 8 - 3 + 1) + 3

which is basically:

math.mod((math.random() * MULTIPLIER), 6) + 3

For any arbitrary random value that math.random() generates the math.mod() operator will always provide a value between 0 and 5. Adding 3 to that will then always give you a value between 3 and 8!

Adding this logic to a standalone Apex Class gives us:

public with sharing class RandomNumberGenerator {

    public static Integer generateRandomNumber(Integer lowerValue, Integer upperValue){

        Integer MULTIPLIER = 1000000;
        Double randomDouble = Math.random();
        Integer randomNumberMultiplied = (Integer)(MULTIPLIER * randomDouble);
        Integer randomNumber = math.mod(randomNumberMultiplied,upperValue-lowerValue+1)+lowerValue; 

        return randomNumber;
    }

Having the logic in an Apex Class ensures that we can use it either in other Apex Classes or in Invocable Actions (almost like a sub-flow 🙂)

Congratulations! Now we have the tools to choose a winner at random in our Salesforce org. Be that either for a given number of entries or for a situation where it needs to be between two numbers.

By leveraging our RandomNumberGenerator class and the concept of generating random numbers, we can add an element of excitement and fairness to your contests and giveaways that we run in Salesforce.