vikas rathi
vikas rathi

Reputation: 31

How to shuffle a list in apex salesforce

I want to shuffle a list record , I am create a VF page to show the Question on that. when page is reload then every time want Another Question on the page randomly. I am using

Integer count = [SELECT COUNT() FROM Question__c ];
Integer rand = Math.floor(Math.random() * count).intValue();
List<Question__c > randomQuestion = [SELECT Id, Question__c  
                                    FROM Question__c 
                                    LIMIT 1000 OFFSET :rand];

system.debug('<<<<<<<<<>>>>>>>>>'+randomQuestion);

in developer console its going good but on vf page its not working Question not showing or limited Question showing

Any one suggest me better way to show the Question on the vf page

Thanks In Advance

Upvotes: 1

Views: 2177

Answers (1)

vikas rathi
vikas rathi

Reputation: 31

I built a solution that users the Fishe-Yates shuffle:

 list<Question__c> quesLst = [select id, Question__c, RecordType.Name,  Answer__c, Option_A__c, Option_B__c, Option_C__c, Option_D__c from
                           Question__c limit 1000];
 randomize(quesLst);

 private list<Question__c> randomize(list<Question__c> lst){
                integer currentIndex = lst.size();
                Question__c Question;
                integer randomIndex;
                // While there remain elements to shuffle...
                while (0 != currentIndex) {
                    // Pick a remaining element...
                    randomIndex = integer.valueOf(Math.floor(Math.random() * currentIndex));
                    currentIndex -= 1;
                    // And swap it with the current element.
                    Question = lst[currentIndex];
                    lst[currentIndex] = lst[randomIndex];
                    lst[randomIndex] = Question;
                }
            return lst;
        }

Upvotes: 2

Related Questions