Thanks Shiva Chitta for providing this solution.
Requirement:We need to shuffle the numbers from 0 to 9 .Every time we run the page,different sequence of numbers to be displayed.
Solution:
Apex Class:
public class ShuffleNumbers {
public Set<Integer> alreadyUsed {get;set;}
public List<Integer> shuffledNumbersByCh {get;set;}
public void shuffleNumbers() {
//set the range of numbers from to N
Integer lsitSize = 10;
alreadyUsed= new Set<Integer>();
shuffledNumbersByCh = new List<Integer>();
while(shuffledNumbersByCh .size() < lsitSize){
shuffledNumbersByCh .add(getRandom(lsitSize));
}
system.debug('Final shuffled Numbers'+shuffledNumbersByCh );
}
public Integer getRandom(Integer shuffledMaxNumber){
Integer randomNum;
do {
randomNum = (math.random() * shuffledMaxNumber).intValue();
} while (alreadyUsed.contains(randomNum));
alreadyUsed.add(randomNum);
return randomNum;
}
}
Visualforce Page:
<apex:page controller="ShuffleNumbers" action="{!shuffleNumbers}">
The shuffled Numbers are :{!shuffledNumbersByCh}
</apex:page>
Note :When ever you re-run the page,difference sequence of numbers is given as output.
Output:
Requirement:We need to shuffle the numbers from 0 to 9 .Every time we run the page,different sequence of numbers to be displayed.
Solution:
Apex Class:
public class ShuffleNumbers {
public Set<Integer> alreadyUsed {get;set;}
public List<Integer> shuffledNumbersByCh {get;set;}
public void shuffleNumbers() {
//set the range of numbers from to N
Integer lsitSize = 10;
alreadyUsed= new Set<Integer>();
shuffledNumbersByCh = new List<Integer>();
while(shuffledNumbersByCh .size() < lsitSize){
shuffledNumbersByCh .add(getRandom(lsitSize));
}
system.debug('Final shuffled Numbers'+shuffledNumbersByCh );
}
public Integer getRandom(Integer shuffledMaxNumber){
Integer randomNum;
do {
randomNum = (math.random() * shuffledMaxNumber).intValue();
} while (alreadyUsed.contains(randomNum));
alreadyUsed.add(randomNum);
return randomNum;
}
}
Visualforce Page:
<apex:page controller="ShuffleNumbers" action="{!shuffleNumbers}">
The shuffled Numbers are :{!shuffledNumbersByCh}
</apex:page>
Note :When ever you re-run the page,difference sequence of numbers is given as output.
Output:
No comments:
Post a Comment