Tuesday, December 28, 2010

Generating Distinct Random Numbers @ Runtime - OPTIMIZED Solution!

This is the optimized solution for generating distinct random numbers at runtime.
"getDistinctRandomNumbers" function has the complexity of O(n^2), and "checkForDuplicateNumber" function has complexity of 0(log n), which makes the overall complexity of the algorithm to be O(n^2 log n).

If you would observe the function "checkForDuplicateNumber", its clear that we have used the "Divide and Conquer" strategy to optimize the solution. By this we have reduced 1 while loop, and added recursive calls to the function, optimizing the number of calls at each step.

".sort( )" call in action script, implicitly uses the optimized way to sort the array.

This is obviously better than the previous solution, having complexity of O(n^3).


public function getDistinctRandomNumbers(range, numCount):Array
{
      // NumCount is the count of random numbers to be generated
      // Range is the upper limit of the generated random numbers,  starting from 0.
      var newArray = new Array();
      var randNum2:int;
      var randNum1 = Math.floor(Math.random() * range);

      newArray.push(randNum1);

      for(var k:int = 0; k < numCount - 1; k++)
      {
           randNum2 = Math.floor(Math.random() * range);
           var len = newArray.length;

           var sortArr = newArray.sort();
           var halfLen = Math.ceil(len / 2);
           var flag = checkForDuplicateNumber(0, halfLen, len, sortArr, randNum2);
           while(flag)
           {
                 randNum2 = Math.floor(Math.random() * range);
                 flag = checkForDuplicateNumber(0, halfLen, len, sortArr, randNum2);
           }

           newArray.push(randNum2);
       }

       return newArray;
}

public function checkForDuplicateNumber(minVal, halfLen, len, sortedArr, randNum2):Boolean
{
     if(halfLen == len == 1)
     {
         if(sortedArr[halfLen - 1] == randNum2)
         {
             return true;
         }
         return false;
     }

     if(sortedArr[halfLen - 1] == randNum2)
     {
       return true;
     }

     else if(randNum2 < sortedArr[halfLen - 1])
     {
          checkForDuplicateNumber(minVal, Math.ceil((halfLen + minVal) / 2), halfLen, sortedArr, randNum2);
          return false;
     }

     else if(randNum2 > sortedArr[halfLen - 1])
     {
          checkForDuplicateNumber(halfLen, Math.ceil((len + halfLen) / 2), len, sortedArr, randNum2);
          return false;
     }

     return false;
}

Monday, December 27, 2010

Generating Distinct Random Numbers @ Runtime.

This post has nothing to do with flash, but it is just an algorithm, which generates any number of distinct random integers from a given range. I thought of it, at the time I was to apply it to one of the applications I was working on. And it really worked.


public function getDistinctRandomNumbers(range, numCount):Array
{
// NumCount is the count of random numbers to be generated
// Range is the upper limit of the generated random numbers, starting from 0.

var newArray = new Array();
var randNum2:int;
var randNum1 = Math.floor(Math.random() * range);

newArray.push(randNum1);

for(var k:int = 0; k < numCount - 1; k++)
{
    randNum2 = Math.floor(Math.random() * range);
    var len = newArray.length;

    var count:int = 0;

    while(count < len)

    {
          while(randNum2 == newArray[count])
          {
                randNum2 = Math.floor(Math.random()*range);
                count = 0;
          }
          count++;
    }

    newArray.push(randNum2);
 }

 return newArray
;

}


This algorithm has a worst case complexity of O(n^3), hence it cannot be considered an optimized solution. Will get back with a better solution.

Friday, December 24, 2010

Dynamic Text --- Look and Feel !

Dynamic texts are a high necessity today in many of the flash applications. But do we realize, that because such fields generate texts at run time, there could be issues with their clarity. It is always recommended and suggested to embed the characters explicitly for dynamic text fields. Input text fields too behave in the same way as the dynamic text fields, hence character embedding applies for them as well.


The following screenshots have 2 text fields, first one with character embedding and below that without character embedding. The first one, where the characters are embedded is sharper, consistent in color and texture, and brighter than the second text field.




Such a difference is because without embedding the characters in any text field, the font in use is the system font. Hence smoothing is not applied to it. But once, character embedding is done to it, the font becomes a part of the swf file, and we see a prominent difference in the text rendering.

For embedding the characters, we need to know what all characters to embed, like the alphabets, numerals, or punctuations. Click on the properties panel. Check for the "Character Embedding..." option. Select all options which need to be added. There are a few special characters that we can explicitly add in the "Auto fill" area. Below is the screenshot to explain the same.





It should be noted, that embedding the characters in the text field increase the size of the file. So only those characters should be embedded, which are a necessity for the text field. Unnecessary character embedding serves no good, but only increases the file size.


Sometimes, it is noticed that even you embed the characters, still some junk data is shown in the text field, mostly that of a small rectangle box. This is mainly due to the fact, that the font being used in the text field, doesn't support that character. But how to check whether its actually correct?


The best way to find this out is, (if you are windows user) run 'charmap' command. Go the the font that you are using. Check whether that particular character is present in the character list of that font or not. Like for instance, we are using the font "LCD", and the text is something like "75%", if we would observe the character map of this font, as shown below, the "%" character is missing from it.





So, even if you embed the punctuations to your text field, "%" sign will not appear. It will only appear if you would add the symbol explicitly to this character mapping. Each symbol is mapped to a Unicode, which remains same for all the fonts. Hence, it is necessary to add the symbol at the correct Unicode position, else it will not be reflected in the text field. In our example, the Unicode for "%" symbol is U+0025.



Tuesday, December 21, 2010

Sound Bound!

Working with sounds is a bit tricky, is the notion I used to have earlier. When to use event sound, when to use stream sound, was always a confusing thought. But with time and practice, I could realize when to bound which sound.

Basically, sounds are of two types:

1. Event Sound
2. Stream Sound

Event sounds are those which play in sync to any event. Any sound like that of a music, or a button click, which are animation and timeline independent, are played using event sounds. These sounds continue to play even if the objects (like buttons or the movie clips) are removed. Any successive start of the sound again, like for instance, by clicking the button repeatedly, will start the sound again and again, keeping the old sound play in continuation. Hence we can have multiple instances of these sounds, until and unless they are stopped explicitly. Event sounds start playing only when they are downloaded completely by the swf file.


Stream sounds are those which play in sync to any animation/timeline. If the animation fails to keep up in pace with the sound, it is forced to skip a few frames. These sounds stop when we close the swf file. Any animation will play with only one sound instance. If the animation reaches the last frame, the sound stops, even if it hasn't reached its end. In other words, the stream sounds cannot play longer than the length of the frames that it occupies. Such a sound starts playing as soon as some percentage of it is loaded in the memory. If the loading is interrupted by any chance, the sound play is also interrupted. 

Monday, December 20, 2010

Terrible Timers!!!

I was working on a flash application today, which unfortunately involved a few timers. The code was in AS 2.0 While the application was running, I noticed something was causing a hurdle to the smooth running of the application. I meddled with the whole affair a lot, and finally after an effort of an hour or so, I inferenced that there was a timer which was not getting cleared off, and was causing trouble to the application.


Its useful to use timers in our applications, but at the same time, its really important to "destroy" them after their usage.


Let us begin with a simple example of timers.

var simpleTimer:Number;
simpleTimer = setInterval(simpleFunction, 2000);

function simpleFunction( )
{
       clearInterval(simpleTimer);
       trace("Timer called !");
}

Now let us suppose, we call this timer multiple times in our application. There are chances in which the instances of the timers are still active even when we dont use them. This could be majorly because, the old instance of the timer is not cleared out, and a new is already into action. Another reason is related to the first one, as in, if there are multiple calls to a function which generates any timer, and the application runs fast, then before the first timer gets cleared, succesive calls to that function, re-start the timer again, before destroying the previous timer. Hence , its always recommeded to clear the timer first before starting it afresh.


Revised code for the above simple program, is as follows:

var simpleTimer:Number;
clearInterval(simpleTimer);
simpleTimer = setInterval(simpleFunction, 2000);

function simpleFunction( )
{
       clearInterval(simpleTimer);
       trace("Timer called !");
}


clearInterval(simpleTimer)  before starting the timer again, solves the problem of unused active timers.

Sunday, December 19, 2010

When Does It Make Sense To Use Bitmap Caching?

The basic rule of bitmap caching is to apply it on the objects which do not involve frequent changes in the pixels layout. To explain in a simple language, there should be less scaling and rotation, but any animation or movement is allowed. But why is it required? Let us first understand what bitmap caching is.

Bitmap caching helps in enhancing the performance of any movie clip, which doesn't involve any change in the pixels. Setting the property "cacheAsBitmap" as true, the internal representation of the movie/button is cached by the flash player. So any movement, or animation applied to it, re-uses the cache. 

But any scaling or rotation applied to the movie/button, redraws the complete pixels layout of the original object, hence in this case we are not re-using the cache. So the primary purpose of bitmap caching is not fulfilled here.

Also note that, if there are no movements applied to the object, bitmap caching only uses more memory than which is required and serves nothing good to the performance of the application.

So here are a few points to remember, as to when to apply and when not to apply bitmap caching to any object:

1. Do apply bitmap caching in case of complex images.
2. Do apply bitmap caching where scrolling is involved in the movie clip. When scrolling happens, the new items in the scroll are displayed over the existing pixels layout of the object.
3. Do apply bitmap caching in case where there are multiple windows popping up in any application. If the two popped-up windows occupy the same surface area, the common pixels layout doesn't get regenerated.
4. Do not apply bitmap caching on zoomed surfaces, as it takes a lot of memory and overuse of caching makes the performance very poor.
5. Do not apply bitmap caching if you are not applying any movement to the object, else caching will take unnecessary memory space.
6. Do not apply bitmap caching to more number of objects in one application, as it again takes lot of memory space. Make an optimized usage of bitmap caching.

Saturday, December 18, 2010

Searching outside your limits...

Well, a day before I was struggling to search a movie clip in the FLA library, which also involved a text in it. But having a look at the items in the library, which was almost reaching a number as high as 3000, I thought for a moment, "Is this the only optimized way for a flash developer to find any item in the library, to scroll through each and every item inside the folder and search for the correct one, when there is no linkage given for that in the code?"

Sounds tedious, isn't it? Then after a few discussions with my "Flash Teacher", who is also my Team Lead in the firm where I work, and who is also the major source of encouragement for this blog, I realized life with Flash is not that tough. Applying the following steps reduced a lot of tension which had already taken a good shape after looking at the high number of item list in the library.

1. Press Control+F






2. This window would appear on your screen. Select the "Search in" as current document, "for" as text, and "Text" as whatever the text that you need to find. Now click "find all".






 3. If you would notice the results dialog, you would get all the possible results, which would also include the one which you had been wanting.

Lets add some twist to this search. What if the movie clip that had the text field doesn't lie in the scene 1? How would you reach to it? The solution is the same what you had done just above.

Now, instead of selecting "for" as text, select it as "Symbol".




4. Then you would get a drop down of all the possible symbols present in the library. Just press the starting alphabet of the movie, whose parent movie you want to find, in our case its "m" of "mc_loadingData". Keep pressing "m" till you reach your correct search. Once you reach "mc_loadingData", click on "find all" again.



5. You would get the data of the movie clip that is present in scene 1 and which successively involves the text that you started searching in the beginning.

Wednesday, December 15, 2010

Yet Another Flash Developer

About me: I am a software engineer, B-Tech in computer science and engineering from IIT-BHU. Currently working with a mobile 4G technology company. Earlier was working with a leading online games company,