Play Games

Search This Blog

Thursday, February 17, 2022

How to generate random numbers with in the range in Salesforce - Salesforce Globe For You

How to generate random numbers with in the range in Salesforce - Salesforce Globe For You

Solution: For example the random numbers with in the range 995-1000 needs to be generated.

Apex Class:RandomNumberGenerator

Public class RandomNumberGenerator {

    public static List<Integer> generateRandomNumbers(Integer Min,Integer Max) {

        List<Integer> lstRandomNumber = new List<Integer>();

        Integer totalNumber = Max-Min;

        Integer len = string.valueOf(Max).length();

        Integer maxRange = 1;

        for(integer i=0; i<len; i++) {

            maxRange = maxRange *10;

        }

        while(lstRandomNumber.size() <= totalNumber){

            Integer randomNumber;

            Boolean doWhileCondition = true;

            do {

                randomNumber = (math.random() * maxRange).intValue();

                if(randomNumber >= Min && randomNumber <= Max && !lstRandomNumber.contains(randomNumber)) {

                    lstRandomNumber.add(randomNumber);

                    doWhileCondition = false;

                }

            } while (doWhileCondition);

             }

        return lstRandomNumber;

    }

}

Output: run the following code in Developer console

List<Integer> lstRandomNumber = new List<Integer>();

lstRandomNumber = RandomNumberGenerator.generateRandomNumbers(995,1000);

system.debug('Random Numbers: '+lstRandomNumber);



No comments:

Post a Comment