简体   繁体   中英

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

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;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM