Random number in Flex
Line Break
Author: Arjan (36 Articles) - Author Website
Arjan is a SAP Consultant specialized in ABAP and Front End development techniques like Web Dynpro, Adobe Interactive Forms, Flex and AIR. In his free time he likes to create examples for Flex-Blog and other applications using Flex, AIR and PHP. Other hobbies are movies and music. He is also the co-owner of Flex-Blog.com.
Every now and then you need to do something at random in your application (i.e. pick a random item from a collection). For that, you’re probably need some random number to decide which option to choose. Here is a simple example that shows you how to generate random numbers in Flex.
To do this, you can you can use the static method random() in the Math class. Math.random gives you a random number between 0 and 1. To get a whole random number between, for example 0 and 100, just multiply the Math.random() result by 100 and round the outcome of that calculation.
Example Application:
Source code for the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" baseColor="0xCCCCFF" xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768" viewSourceURL="srcview/index.html"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <fx:Script> <![CDATA[ private function generateRandomNumber( start:Number, end:Number ):void { var randomNum:Number; if( end == 1 ) { // Number is between 0 and 1, don't round. randomNum = Math.random(); } else{ // Number is between 0 and 100 or 1000, round the number randomNum = Math.round( Math.random() * end ); } // Show random number in TextInput randomNumber.text = randomNum.toString(); } ]]> </fx:Script> <s:layout> <s:VerticalLayout paddingLeft="5" paddingRight="5" paddingTop="5" paddingBottom="5" /> </s:layout> <s:VGroup id="hgroup"> <s:Button label="Number between 0 and 1" click="generateRandomNumber(0,1)" width="250"/> <s:Button label="Number between 0 and 100" click="generateRandomNumber(0,100)" width="250"/> <s:Button label="Number between 0 and 1000" click="generateRandomNumber(0,1000)" width="250"/> </s:VGroup> <s:TextInput id="randomNumber" width="{hgroup.width}" editable="false" textAlign="center" height="60" fontSize="20" fontWeight="bold"/> </s:Application> |
Related posts:
- Easy Unix Time Function
- Data Dependant Tree Icon with Tree in AdvancedDataGrid with iconFunction
- Flex Custom Event Example
- Progressbar in Datagrid Example
Comments
One Response to “Random number in Flex”


(
Your code for generating random integer number between 0 and a number different from 1 is not entirely correct. For example we want to generate an integer random number in the interal [0, 2]. Following yor example the probabilities for getting a 0 and a 1 are not equal. To get 0 (Math.random() * end) has to return a number in the interval [0, 0.5) so when rounded it will return 0. But to get 1, the number generated by (Math.random() * end) has to be in the interval [0.5, 1.5) which as you can see is two times bigger that the previous one. So the probability to get 1 compared to 0 is bigger. The same happens at the end of our wanted interval (in this example 2).
The easiest way to get equal probability is with this function:
private function rand(start:Number, end:Number):Number
{
return Math.ceil(Math.random()*(end-start+1)) % (end-start+1);
}
Note that this function too doesn't generate numbers with mathematically equal probability but it's close enough.
Note2: This function also work if you pass it start=0, end=1
To test that your example is not correct you can try this example:
<![CDATA[
private function rand(start:Number, end:Number):Number
{
return Math.ceil(Math.random()*(end-start+1)) % (end-start+1);
}
private function test_rand():void
{
var tmp:Array = new Array(0, 0, 0);
var i:Number;
var count:Number = 1000000;
for( i = 0; i < count; i++ ) {
//tmp[rand(0, 2)]++;
tmp[Math.round(Math.random()*2)]++;
}
lbl_test_rand.text = "";
for( i = 0; i
With your algorithm you will get probabilities such as:
0 -> 25%
1 -> 50%
2 -> 25%
with the function rand() (uncomment it in the loop and comment out the line below it) you will get probabilities such as:
0 -> 33%
1 -> 33%
2 -> 33%