function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ChowChow 

Generate random accounts

Hi,

 

I have a 80 Accounts in my Account Object, where i need to display all the Accounts on Visualforce Page.

I used dataList Component and displayed all the 80 Accounts.

 

But the main requirement is, i need to select only 20 Accounts randomly and display those random 20 Accounts on Visualforce Page.

 

So, how do i write a random function in Apex in order to pick 20 random Accounts out of 80?

Ritesh AswaneyRitesh Aswaney

By random do you mean that the displayed Accounts are different each time the page is loaded ? Or just any random 20 ?


True randomness is a very hard to achieve phenomenon even for some of the worlds most powerful supercomputers :)

ChowChow

It is just picking any 20 out of 80.

Ritesh AswaneyRitesh Aswaney

Give this a go.... :) Brought back memories of University Assignments. You'll have to house this in a method of your VF COntroller or such....

I've randomised the field by which it sorts, the LIMIT to the number of records it selects, and then whether it shaves records off the top or bottom of the selected records. Hopefully enough randomness.

.
.
String querySeed = 'Select Id, Name, CreatedDate from Account ORDER BY _ORDERBYFIELD_ _SORTORDER_ LIMIT _LIMITNO_' ;
String[] sortOrderArr = new String[]{'ASC', 'DESC','ASC', 'ASC','ASC', 'DESC','DESC','ASC', 'DESC','ASC', 'DESC','ASC','DESC','DESC', 'ASC','ASC', 'DESC','ASC','ASC', 'DESC','ASC','ASC', 'DESC','ASC'};
Datetime thisMoment = Datetime.now();
integer randomPos = Math.Abs(Math.ROUND(thisMoment.hour() - Math.Floor(Math.Random() * 10)));
String sortOrder = sortOrderArr[randomPos];
Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
Map<String, Schema.SObjectField> field_map = R.fields.getMap();
String sortingField = field_Map.values()[Math.abs(randomPos - Math.mod(randomPos,6))].getDescribe().getName();
querySeed = querySeed.replace('_ORDERBYFIELD_', sortingField);
querySeed = querySeed.replace('_SORTORDER_', sortOrder);
while(randomPos < 20)
randomPos += randomPos;
querySeed = querySeed.replace('_LIMITNO_',randomPos+'');
System.debug(querySeed);
Account[] accs = Database.query(querySeed);
integer elementsToRemove = accs.size() - 20;
if (Math.mod(thisMoment.minute(), 2) == 0)
{
for (integer i = 0; i< elementsToRemove; i++)
accs.remove(i);
}
else
{
integer sizeAcc = accs.size() - 2;
for (integer i = 0; i< elementsToRemove; i++)
accs.remove(sizeAcc);
sizeAcc -= 1;
}
System.debug (' >>>>>>>>>>>>>>>>>>>>>>>>>>>>' + accs.size());

 

 

ChowChow

Ritesh,

 

Thanks alot....

i'll give it a try and post whether working or not.

 

Thanks!

suman@thylaksoft.comsuman@thylaksoft.com

Hi Chow i understand your Problem you want see 20 Account Records at a time in visualforce. solution is in Apex class you use this code. i.e

 

 

   List<Account> LdList = new List<Account>();
    List<Account> LdList_Next = new List<Account>();
    Integer next =20, count = 20;

 

if you want see  the 25  Records at a time you change  integer next=' ' , count=' '  here only .

ChowChow

Hi,

 

Acually the business is, i need to develop a Application which is an Online Test.

I have set of 100 questions, where an exam consists of 25 questions. So, system need to pick 25 random questions out of 100 for everytime the exam is started.

 

Now, i have the custom objects such as Question__c and Answer__c.

Where Question Object consists of a

         q_id,question(Exact Question, example "Who is the current President  of US ?"), options(4, such as opt1__c,opt2__c,opt3__c,opt4__c), type blah blah blah....

Answer Object consists of

        q_id(Lookup to Question Object),Answer("OBAMA").

 

 

Now for this i did in this way,

 

VISUALFORCE PAGE:

 

<apex:page controller="YellowRecertTestCls"
           showHeader="false"
           sidebar="false">     
              

<apex:form >
 <apex:dataList value="{!method1}" var="q">
  <!--apex:dataList value="{!method1}" var="q"-->
      <apex:outputText value="{!q.Question_Desc__c}"/><br/><br/>
          <input style="display:{!IF(q.Question_Type__c == 'Radio','','none')}"/>
          <input style="display:{!IF(q.Question_Type__c == 'Checkbox' ,'',IF(q.No_of_Options__c == '4','', 'none'))}"/>
      <apex:outputText value="{!q.opt1__c}" /><br/>
          <input style="display:{!IF(q.Question_Type__c == 'Radio' ,'', 'none')}"/>
          <input style="display:{!IF(q.Question_Type__c == 'Checkbox' ,'', 'none')}"/>   
      <apex:outputText value="{!q.opt2__c}" /><br/>
          <input style="display:{!IF(q.Question_Type__c == 'Radio' ,IF(q.No_of_Options__c == '2' ,'none', ''), 'none')}"/>
          <input style="display:{!IF(q.Question_Type__c == 'Checkbox' ,'', 'none')}"/>  
      <apex:outputText value="{!q.opt3__c}" /><br/>
          <input style="display:{!IF(q.Question_Type__c == 'Radio' ,IF(q.No_of_Options__c == '2' ,'none', ''), 'none')}"/>
          <input style="display:{!IF(q.Question_Type__c == 'Checkbox' ,'', 'none')}"/>
      <apex:outputText value="{!q.opt4__c}" /><br/><br/>         
  <!--/apex:dataList-->
 </apex:dataList>
 
 <!--apex:outputText value="{!random}"/-->
 
</apex:form>          
</apex:page>

 

 

 CONTROLLER CLASS:

 

public class YellowRecertTestCls
{
    public YellowRecertTestCls()
    {
    }
    public YellowRecertTestCls(ApexPages.StandardController controller)
    {       
    }
   
    List<Question__c> method1;
    List<Integer> ques = new List<Integer>();
    List<Question__c> ques1 = new List<Question__c>();
   
    public List<Question__c> getMethod1()
        {
           for(Integer i=0; i<5; i++)
           {
               Integer QId = getrandom();
               System.debug('$$$$$$$$$$$$$$$$$$' + QId);
               ques.add(QId);
               System.debug('@@@@@@@@@@@@@@@@@@' + ques[i]);
           }
          
           for(Integer j=0; j<ques.size(); j++)
           {
                method1 = [SELECT Question_Desc__c,No_of_Options__c, Question_Type__c, opt1__c,opt2__c,opt3__c,opt4__c
                           FROM Question__c where Q_ID__c =: ques[j]];
                        //method1.add(ques1);
                //ques1.add(method1);   ----------->   (Here i am getting an Error: Compile Error: Incompatible   element type LIST<Question__c> for collection of SOBJECT:Question__c at line 29 column 17 )                 
           }                                         
         //return ques1;
          // method1 = [SELECT Question_Desc__c, No_of_Options__c, Question_Type__c, opt1__c,opt2__c,opt3__c,opt4__c
          //            FROM Question__c  order by name    ];
          return method1;
        }
       
    public Integer getrandom()
        {
          Double x = math.random() * 10; //Give the range
          return x.intValue();
        }                    
}

 

 

If anyone find the mistake, please post back what's wrong in it.

 

Thanks.

 

 

 

Nick00000Nick00000

To add a List to another List, try addAll() instead of add().