2

Apex Random Select & Display

  • I have an object named Parts__c.
  • Parts__c has 2 fields: ABC_Code__c and Parts_Number__c.
  • ABC_Code__c is type text and its value range is A, B, or C.
  • Parts_Number__c is type Autonumber.
  • Object Parts__c has 50 records: 5 A's, 15 B's, and 30 C's.

I need help writing an Apex class that grabs only the C's and randomly lists them each time they're selected.

3
  • 2
    general forum policy is for the poster to demonstrate what they've tried before soliciting help
    – cropredy
    Commented Jan 27, 2016 at 22:01
  • 1
    I'll figure it out.
    – Rocket_Izz
    Commented Jan 27, 2016 at 22:03
  • Let me know if you can't and I will be happy to help you. Commented Jan 27, 2016 at 22:26

3 Answers 3

2

You'd probably do something like this - get the records:

Parts__c[] parts = [Select ABC_Code__c, Parts_Number__c From Parts__c Where ABC_Code = 'C'];

Now to randomize, you'll want to loop this list grabbing items randomly and putting them into another list.

First define a function to get a random number based on a supplied max:

public Integer randomWithMax(Integer max){
    Integer rand = Math.round(Math.random()*1000);
    return Math.mod(rand, max);
}

Then loop:

Integer listSize = parts.size();
Integer initialSize = listSize;
Parts__c randomParts = new Parts__c[]{};

for (Integer i = 0 ; i < initialSize ; i++ ){
    Integer rand = randomWithMax(listSize);
    Parts__c part = parts[rand];
    randomParts.add(part);
    parts.remove(rand);
    listSize --;
}
2
  • This should probably be done with a while loop. Also, the only code that's been tested is the randomize part, so proceed with caution. Commented Jan 27, 2016 at 23:06
  • Fixed a couple of bugs, btw Commented Jan 27, 2016 at 23:08
1

I know this is an old thread, but I was trying to figure this out yesterday, and want to share another option that I think solves this. This is for some code that simulates dealing 25 random cards from a deck. I added random numbers to a List at the same time that I added them to a Map, then I sorted the List and used the first 25 values as keys to pull cards from the Map.

public List<Card__c> drawRandomCards() {
    List<Card__c> selectedCards = new List<Card__c>();
    List<Card__c> allCards = [SELECT Id, Name from Card__c];
    Decimal randNum = 0;
    List<Decimal> randNums = new List<Decimal>();
    Map<Decimal,Card__c> randNumsToCards = new Map<Decimal,Card__c>();

    for(Card__c card : allCards) {
        randNum = Math.random();
        randNums.add(randNum);
        randNumsToCards.put(randNum,card);
    }

    randNums.sort();

    for (Integer i=0; i<25; i++) {
        selectedCards.add(randNumsToCards.get(randNums[i]));
    }

    return selectedCards;
}
1
  • Also late to this party, but this is neat, I found this useful.. thanks :) Commented Aug 20, 2022 at 1:10
0

I figured it out. Thanks for the response. I used a nested for loop, and a random generator, to randomly grab elements from List1, sequentially assign them to List2, and then print List2 using VisualForce.

public sortController()
{
    sortparts=[SELECT ABC_Code__c, Name FROM sm1e_smPart__c WHERE ABC_Code__c = 'C'];  
    count = (integer)aggResult[0].get('expr0'); //Convert number of Cs to integer
    randomized = new List<sm1e_smPart__c>(count);
    for(Integer i = 0; i < count; i++)
    {
        for(Integer j = 0; j < count; j++)
        {
            Integer rand = Math.round(Math.random()*1000);
            while(rand > count-1){rand = Math.round(Math.random()*1000);}
            randomized[j] = sortparts[rand];
        }
    }
}
2
  • There is a problem with doing it this way - you will end up with duplicates in your array and probably won't get all the elements into the randomized array. This is because you need to remove the item from the source array so it can't be added again. Hmm, of course you could define randomized as a set, but even then there is no guarantee that you'll get all items from the source -just no dupes in the destination. Commented Jan 28, 2016 at 20:30
  • I understand your concern with duplicates. I asked this question to my coworkers before I took on this task. Their response was "for something to truly be random, it should possibly repeat." This is what they asked for.
    – Rocket_Izz
    Commented Jan 28, 2016 at 22:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .