25 Apr 2013

Random number in JavaScript

Have you ever to use a random number in your application? Of course it depends on the application or program you are in to. Recently I was  working on a mobile application in which i had to rate the movies between 1 to 5 . Since the backend data was not ready i had to use static code in development phase. So the question was how to rate movies,  In other words  i had to assign a random number between 1 to 5 to a movie.

Lets first try Math.random()
Math.random() returns the a floating point number between 0 and 1. It could return anything like 0.9876567876 or 0.4232457568.
It would not work since i need real number between 1 to 5.


Variant of Math.random()
                           Math.random() * (max - min) + min
This would return a floating point random number between min (inclusive) and max (exclusive).
To rate 1 to 5 , i have to use 1 as a min  to 6 as a max. Not 5 as a max because it is exclusive
                    r =   Math.random() * (6 - 1) + 1
r can be 2.2.711616653897717 or 4.5043663586648925

Yes I want something like this , which would return a random number between two given numbers.
But the problem is it is returning a floating number.
Note that r is real.float. where real part would be always be a random number between min and max.
My problem would be solved if i could get only real part out of it.


Will Math.floor(x) help ?
It would returns the nearest largest integer of x.

So if i pass x as 2.2.711616653897717 i can get 2 (real part).
   e.g.   2 = Math.floor(2.2.711616653897717)


No, I need both random() and floor().
Step 1: get floating point random number
               float_random = Math.random() * (6-1) + 1
Step 2: round off floating number to get real integer
              integer_random = Math.floor(float_random)

integer_random would always be between 1 and 5.

Now i can use this integer_random number to rate the movies. Next time you looking for random number in JavaScript , you know the steps.

16 Apr 2013

Mapping a key to many values in javascript

The concept of mapping arises when requires to bind a pair of values together like name:'john'. here name is a key and 'john' is value of key. Generally for mapping unique keys are used to identify particular value.
What if one wants to identify many values with same key ?

Real world example
One of my recent software project , it is required to access the weather feed for particular city. We are using yahoo developer api for that. First you have to get the id of a city , woied, you can can get this id for your city  by searching the http://weather.yahoo.com/.
Now use  this link http://weather.yahooapis.com/forecastrss?w=woeid   to get the data for the particular city. where woeid is the id of the city.

Problem
Lets get back to the mapping question, To describe the weather condition they have specified the description.of condition ( http://developer.yahoo.com/weather/#codes).
For example, All following four weather condition can be characterized as a 'rain'
              mixed rain and sleet
              mixed rain and snow
              drizzle rain
              heavy rain
So whenever either of four conditions are there , application requires to display as a 'rain'.
It was required to map 'rain '(key) to above four conditions (values)

Wrong solution
i created a dictionary having 'rain' as a key and a weather conditions.This wayi created four 'rain' key and map each of weather condition.


var dict = {     mixed rain and sleet,    
                       mixed rain and snow,   
                       drizzle rain,                  
                       heavy rain                    
                 }                                        

When i iterated over dict it show only last mapping.
                for(item in dict){                                   
                      Ti.API.info(item+"....."+dict[item])
                   }                                                          

Wrong Output:    
          rain......mixed rain and sleet.
But it supposed to show all four conditions, what happened? I realized that the dictionary key must be unique.what i was doing wrong? I was mapping multiple keys having same name which is being treated as a one single key.  So i have to map all four weather conditions against only one 'rain' key.



Right Solution
Created a dictionary, this time, with only one key and assigning all four weather conditions as an  array.
                 var dict = {                                                    
                                    'rain' : [   mixed rain and sleet  , 
                                                   mixed rain and snow,  
                                                   drizzle rain,                  
                                                   heavy rain                    
                                           ]                                            
                     }                                                                 
Iterating over dict
            for(item in dict){                                                                  
                        array_values = dict[item]                                         
                         for(ele in array_values){                                         
                               Ti.API.info(item+"......"+array_values[ele])     
                         }                                                                               
            }                                                                                            

Although above code is self explanatory, i'm going to explain anyhow. 'item' is a key which is 'rain'  and for dict['rain'] you get the array of values. Now you can  simply iterate over array, where 'ele' will give weather conditions.
  
Right Output:
         rain..... mixed rain and sleet,
         rain..... mixed rain and sleet,
         rain..... drizzle rain,
         rain..... heavy rain 

Now i can correctly use 'rain' in place of those four weather conditions.





11 Apr 2013

Reverse in python


Reverse using reversed(seq) function
To reverse a sequence one can use the reversed(seq) built-in-function. what is sequence ? str, list and tuple are sequence. This function can take a sequence as a argument and returns an iterator. Lets dig deep into it.
reversed(seq) method will call the __reversed__() method of sequence which will reverse the elements of sequence and  and return a iterator for reverse sequence. So the reversed(seq) not just return a iterator but a reverse iterator.
 Feel from example:
>>list=[1,2,3,4,5]
>>reverse_iterator =  reversed(list)
>>for ele in reverse_iterator:
>>....    print ele                         // 5,4,3,2,1


We can also use the next() method of reverse_iterator object to call 'successive' elements.
>>reverse_iterator.next()         //5
>>reverse_iterator.next()         //4
>>reverse_iterator.next()         //3
>>reverse_iterator.next()         //2
>>reverse_iterator.next()         //1
>>reverse_iterator.next()         //StopIteration exception, since no more elements are left


Reverse using extended slice, [start:end:step]
Extended slice is another way to reverse str, list and tuple. First, lets get familiar with what extended slice is all about.  
Sometimes it may be desirable to iterate over only certain elements of a type. for example,
L = [11 22, 33, 44, 55, 66, 77, 88, 99, 100] , it may be required that one wants to iterate over only even or odd numbers thereby skipping certain elements from the list.
>>L = [11 22, 33, 44, 55, 66, 77, 88, 99, 100]
>>L[1:10:2]       -----> 2,4,6,8,10     // all even numbers of L
>>L[0:10:2]       ------> 1,3,5,7,9      // all odd numbers of L

Now let answer,  how ?
Syntax for extended slice is [start:end:step]. start specifies the index (of first element) from which it will start picking the elements, end specifies upto which index (of last element) it will pick elements and step specifies the number of elements to skip.

The default value of start is 0, of end is length of item in used ( length of L) and of step is 1.
So if you try like L[::] it will print the L as it is, assuming it as L[0:10:1]
Note that the step cannot be 0  because you have to take step to iterate (i made that up ). Therefore following will give error.
>>> L[0:10:0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: slice step cannot be zero




Here is important thing, the step part also defines the order in which an item is iterated. if you provide a negative value then it start iterating in reverse order.
>>> L[::-1]
[100, 99, 88, 77, 66, 55, 44, 33, 22, 11]

what L[::-1] means ?
It means that Iterate over L from 0 to length of L in reverse order.

So that all about reverse in python, i hope you find it useful.