Saturday, July 5, 2014

Point in Polygon Algorithm


In computational geometry, the point-in-polygon (PIP) problem asks whether a given point in the plane lies inside, outside, or on the boundary of a polygon.

Thinking..





in this case, how to prove that (2,5) is inside the polygon and (7,5) is outside?

1st Approach
if we get minX , maxX , minY , maxY of the polygon. then we check if this point within this area or not.

minX = 1 , maxX = 5 
minY = 1 , maxY = 6 

(2,5)         1 < 2 <5 ?  and  1< 5 <6 ?  Inside 
(7,5)         1 < 7 <5 ?   and  1< 5 <6 ?  Outside 

 but if we have more than 4 vertices like the following shape, this check will fail. as some points will seem to be inside but  it is actually outside.


minX = 1 , maxX = 4 
minY = 0 , maxY = 5 

(2.9 , 1.2 )         1 < 2.9 <4 ?  and  0< 1.2 <5 ?  Inside 
(3.7 , 4 )            1 < 3.7 <4 ?   and  0< 4 <5 ?  Inside   X

so, this approach needs improvements with shapes with more than 4 vertices.

2nd approach called Ray Casting 
The easiest way to determine if the point is inside the complex polygon is  to test how many times a ray, starting from the point and going any fixed direction, intersects the polygon sides. The number of intersections is an even number if the point is outside, and it is odd if inside.

Here, we have a complex polygon with the point located in one of the holes inside (the red dot is the selected point :)


check this link for the source code point-in-polygon-and-ray-casting  
also, if you have any problems in the link check this link RayCasting C#Project .

Thanks to Alex :)

Friday, March 28, 2014

Lecture 2 | Programming Methodology (Stanford)


Hii all , can't wait to attend the second lecture with Prof. Mehran. Let's start!

Lecture Notes:

- we saw karel and tried to play with it using a small program.
- we've to start solving, check  Assignment 1 PDF. and Project Files.
- Be sure that you installed Eclipse Standard and JRE before starting this Assignment.

karel
karel is a robot needs to be controled to finish its tasks. we are going to use karel to enter the programming world.

commands that karel understands easily:
- move          -> move one step 
- turnLeft      -> turn 90 degree to the left
- pickBeeper  -> catch a candy
- putBeeper   -> put a candy from its candy bag

these commands called methods in programming world. we use them to control karel in its virtual world. 

first, we tried a simple program that control karel.


                                              2

Import stanford projects:

- File -> Import -> Existing Projects in Workspace -> select archive file .. browse .. select your project. this is the program code in case you want to give it a try.
   move( );
   pickBeeper( );
   move( );
   turnLeft( );
   move( );
   turnRight( );
   move( );
   putBeeper( );
   move( );
as you can see each method ended with ( ). this is important to be a valid command for karel. also at the end of each statement/command in programming world you need to end it with a semicolon ' ; '.

Run Method

we put all these method in a bigger method called run which is the start point of karel. karel read run method line by line and achieve it.



            4 

 Tabs

 you need to take care of putting tabs for code readability.

How is eclipse organized ?

                              حشؤنشل

each project in eclipse contains a set of packages. each package contains a set of classes. each class contains a set of methods.

why ?- it's a way for organizing your code, but it's also made like this to use it easily in the future. don't worry if you can't understand it clearly, soon we will try everything practically.  

what does extends means?

 it means that you're going to use other properties from another class. our program needs to extend from karel to use its commands.

what is import stanford.karel.* ?

telling the program to get everything related to karel from stanford library.

creating New Methods : TurnRight ( ) , TurnAround( )

we need to add a new method as karel doesn't have this behavior. 

private void turnRight ( ){
          turnLeft( );      
          turnLeft( );
          turnLeft( );
}

private void turnAround( ) {
          turnLeft( );      
          turnLeft( ); 
}

after that we found out that there is another class called superkarel which contains more methods, so we decided to extends superkarel instead of karel.

SNOOZE story :D
this was an introductory story to a programming concept called "For Loop", which means doing something multiple times as much as you want.

For loop syntax
for ( int i = 0 ; i < Ntimes ; i++){

   body that will be executed Ntimes
}

while loop syntax 
when you want to do something many times but you do know how much, you can use a while loop. karel want to move till it hits a wall.
while ( frontIsClear ) {

        body


IF condition 
in case you want to execute a command once upon a condition.
if( beeperPresent ) {
    
    pickBeeper( );
}
else {

    putBeeper( );
}

Nested If
also you can put another condition inside the if command.

Readable code
write a code for people to read not only for computers to execute.

the last minutes of the lecture was very FUNNY :D:D ,The End for today :), see you in the next lecture! and i will try to think out loud while solving my first assignment :).

Wednesday, March 26, 2014

Lecture 1 | Programming Methodology (Stanford)


Hiii all, this is our first lecture in programming methodology series, let's start! :). we're going to start with the video.








Lecture Notes:

 this lecture is just an introduction to the course and how you get your section, deliver your assignments and so on. i know it doesn't contain much information but we need to act like a student in there :). okay, see you next lecture :).

 

Saturday, November 2, 2013


Pair Programming



I always had some problems in delivering this idea to others. i'm sure that working individually unlike working in a team. Team equals to multiple decisions , ideas and many cool staff. i might have experience A in something and another partner has B experience, if we work together we both will have A&B experience. sharing experience with time saving is totally generated from working in teams.

i had a problem last week in my work, A friend asked me to read about pair programming and here is what i found.

Tom Dommett wrote in to share his positive experience with pair programming:

The idea is two developers work on the same machine. Both have keyboard and mouse. At any given time one is driver and the other navigator. The roles switch either every hour, or whenever really. The driver codes, the navigator is reading, checking, spell-checking and sanity testing the code, whilst thinking through problems and where to go next. If the driver hits a problem, there are two people to find a solution, and one of the two usually has a good idea.

Other advantages include the fact that where two people have differing specialities, these skills are transferred. Ad-hoc training occurs as one person shows the other some tricks, nice workarounds, etcetera.
The end result is that both developers are fully aware of the code, how it works, and why it was done that way. Chances are the code is better than one developer working alone, as there was somebody watching. It's less likely to contain bugs and hacks and things that cause maintenance problems later.
In a bigger team, the pairing can change each week so each team member is partnered with somebody different. This is a huge advantage, as it gets developers talking and communicating ideas in the common language of code.
We found this to be as fast as working separately. The code got written quicker and didn't require revisiting. And when it did need to change, more than one person was familiar with the code.

It's an encouraging result. I applaud anything that gets teams to communicate better.
i really liked , and i thought it worth sharing :).

Saturday, March 16, 2013

Dynamic Programming

Dynamic programming is a powerful technique for solving problems that might otherwise appear to be extremely difficult to solve in polynomial time. Algorithms built on the dynamic programming paradigm are used in many areas of CS, including many examples in AI (from solving planning problems to voice recognition). 

Dynamic programming works by solving subproblems and using the results of those subproblems to more quickly calculate the solution to a larger problem. Unlike the divide-and-conquer paradigm (which also uses the idea of solving subproblems), dynamic programming typically involves solving all possible subproblems rather than a small portion. 

Often, dynamic programming algorithms are visualized as "filling an array" where each element of the array is the result of a subproblem that can later be reused rather than recalculated. One way of calculating Fibonacci numbers is to use the fact that
fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
And then write a recursive function such as
int fibonacci(int n)
{
    if(n == 0)
    {
        return 0;
    }
    if(n == 1)
    {
        return 1;
    }
    else
    {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}
This algorithm is excruciatingly slow (it will take exponential time to run) because every time fibonacci(n - 1) is calculated, it will recalculate every value of fibonacci(n - 2) to fibonacci(0). The heart of dynamic programming is to avoid this kind of recalculation by saving the results. In the case of fibonacci numbers, other, even simpler approaches exist, but the example serves to illustrate the basic idea. 

One use of dynamic programming is the problem of computing "all pairs shortest paths" in a weighted graph. Although Dijkstra's algorithm solves the problem for one particular vertex, it would be necessary to run it for every vertex, and would be a somewhat complicated algorithm. Dynamic programming produces a simpler, cleaner algorithm (though one that is not inherently faster). 

The trick here is to find a useful subproblem that, by solving, we can use to solve a larger problem. In this case, it turns out that a useful subproblem is to consider the shortest path for any pair of vertices that goes through only the first k vertices. For simplicity, we'll just number each vertex 1 through n, where n is the total number of vertices. Now, each subproblem is just to find the distance from vertex i to vertex j using only the vertices less than k. 

We'll store the distances of all the shortest paths from i to j that don't use k in a two-dimensional array, D_k, indexed by the start and end vertices, storing the value of the shortest path using only vertices numbered less than k as intermediate nodes. (It's OK for one of the vertices to be numbered greater than or equal to k.)
D_k[i, j] = length of shortest path from i to j going through intermediate vertices
            less than k 
Now, let's say that we've already processed D_k for k from 1 to n. That means we have all of the shortest paths from any two nodes i and j where that path doesn't include any vertex labeled greater than n. Now, we know that any path for vertices i to j that may include node n+1 is either going to be the same as before, or it will include the vertex n+1, in which case the path must be a combination of the shortest path from i to n+1 and from n+1 to j; both of these paths, of course, using intermediate nodes less than n+1 (i.e., using D_n[i, n+1] and D_n[n+1, j]. 

We can express the definition of D_k in the following form (notice that anything in braces is just being grouped together -- D_{k-1} is the distance array for k-1, for instance).
D_k[i, j] = min(D_{k-1}[i, j], D_{k-1}[i, k] + D_{k-1}[k, j])
Once the definition is expressed in this recursive format, it should be easy to see how this could be coded up -- we just fill a three-dimensional array with rows and columns for each vertex and a depth equal to the number of vertices. But we can actually do a bit better than this! Notice that we never need to keep around more than the current array being calculated and the last array calculated. (In fact, it turns out that all we really need is one array, so we can get away with using O(|V|^2) space.) (By the way, it turns out that this algorithm has a name--it's called the Roy-Floyd algorithm or sometimes the Floyd-Warshall algorithm.) 

The key point to take away is that using dynamic programming, we can reduce the problem of finding all of the shortest paths to solving a series of subproblems that can be reused again and again to solve larger problems. Whenever you try to solve a problem using dynamic programming, think about how you can break the problem up into subparts--perhaps you really only need to computer a small number of subparts (in which case you might be able to use a divide-and-conquer approach, a la merge sort)--but if you find that you need to know every possible subproblem, then dynamic programming may be the right solution. 

Another point to keep in mind is that it often helps to solve simpler versions of the same problem before trying to tackle the full task at hand. For instance, you might have noticed that in the all-pairs shortest paths problem, we actually solved a slightly simpler problem: what is the distance of the shortest path from i to j. This problem is a bit easier to conceptualize and write a recurrence for. But now that we have the idea, it's easy to turn it into a solution to the actual problem in question--we just add in a new array that stores the intermediate node, k, through which the shortest path extends. In this way, the problem is reduced to finding the shortest path from i to k and from k to j, which we can again solve. (The base case here is just when the route between two nodes is a direct path that goes through no additional vertices.) 

Moreover, the code for dynamic programming can be surprisingly simple. The pseudocode for the above example can be written in only a few lines, and it turns out that we only need to fill a single array (as long as we fill in a reasonable order).
/* Note that this is c-like pseudo-code */
int D[n][n];

/* initialize D so that each edge, (i, j), has the correct weight at D[i][j]
 * and all other elements of the array are set to INFINITY */

/* n is the number of vertices */
for(int k = 0; k < n; k++)
{
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            if(D[i][j] > D[i][k] + D[k][j])
            {
                D[i][j] = D[i][k] + D[k][j];
            }
        } 
    } 
}

for more Dynamic programming problems check this link http://people.csail.mit.edu/bdean/6.046/dp/

Recursion


C Programming Recursion

A function that calls itself is known as recursive function and the process of calling function itself is known as recursion in C programming.

Example of recursion in C programming


Write a C program to find sum of first n natural numbers using recursion. Note: Positive 

integers are known as natural number i.e. 1, 2, 3....n



#include <stdio.h>
int sum(int n);
int main(){
    int num,add;
    printf("Enter a positive integer:\n");
    scanf("%d",&num);
    add=sum(num);
    printf("sum=%d",add);
}
int sum(int n){
    if(n==0)
       return n;
    else
       return n+sum(n-1);    /*self call  to function sum() */
}
Output

Enter a positive integer:
5
15

In, this simple C program, sum() function is invoked from the same function. If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous argument it was called with. Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1.

For better visualization of recursion in this example:


sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15

Every recursive function must be provided with a way to end the recursion. In this example when, n is equal to 0, there is no recursive call and recursion ends.

Advantages and Disadvantages of Recursion


Recursion is more elegant and requires few variables which make program clean. Recursion can be used to replace complex nesting code by dividing the problem into same problem of its sub-type.

In other hand, it is hard to think the logic of a recursive function. It is also difficult to debug the code containing recursion.

More Examples on Recursive Function


  • C program to Calculate Factorial of a Number Using Recursion

    This program takes a positive integer from user and calculates the factorial of that number. Instead of loops to calculate factorial, this program uses recursive function to calculate the factorial of a number.

    Source Code to Calculate Factorial Using Recursion


    
    /* Source code to find factorial of a number. */
    
    #include<stdio.h>
    int factorial(int n);
    int main()
    {
        int n;
        printf("Enter an positive integer: ");
        scanf("%d",&n);
        printf("Factorial of %d = %ld", n, factorial(n));
        return 0;
    }
    int factorial(int n)
    {
        if(n!=1)
         return n*factorial(n-1);
    }
    Output

    Enter an positive integer: 6
    Factorial of 6 = 720

Functions

The C language is similar to most modern programming languages in that it allows the use of functions, self contained "modules" of code that take inputs, do a computation, and produce outputs. C functions must be TYPED (the return type and the type of all parameters specified).


Functions in C

As always, a function is a module of code that takes information in (referring to that information with local symbolic names called parameters), does some computation, and (usually) returns a new piece of information based on the parameter information.


A Function Prototype

In C, all functions must be written to return a specific TYPE of information and to take in specific types of data (parameters). This information is communicated to the compiler via a function prototype.
Here is the syntax for the function declaration or Prototype:
         
          RETURN_TYPE name_of_function ( PARAMETER_TYPE name_of_param,PARAMETER_TYPE name_of_param, etc); 
 
          // here are some examples of prototypes used at the top of a file: 
          float sqrt( float x ); 
 
          float average( int grades[], int length ); 
        
      
A Prototype can occur at the top of a C source code file to describe what the function returns and what it takes (return type and parameter list). When this is the case (occuring at the top of the file), the function prototype should be followed by a semi-colon
The function prototype is also used at the beginning of the code for the function. Thus the prototype can occur twice in a C source code file. When the prototype occurs with the code NO semicolon is used.


The Main Function

In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts.
         
 
 int                       // the main function will usually returns a 0 if successful 
 main()                    // this is the name, in this case: main 
 { 
                           // this is the body of the function (lots of code can go here) 
 } 
        
      

Examples of C Functions:

         
 
 double                                 // this is the return type  
 max( double param1, double param2)     // this is the name, followed by the parameters 
 { 
   if (param1 > param2) 
     { 
       return param1;  // Notice: that param1 is of type double and the return 
                       //         type is also of type double 
     } 
   else 
     { 
       return param2; 
     } 
 } 
 
 
 
void         // This is the return type (void means no value is computed and returned by the function!) 
print_happy_birthday( int age ) 
{ 
   printf("Congratulations on your %d th Birthday\n", age); 
   return;  // you can "terminate" a void function by using return. 
   // HERE it is REDUNDANT because the function is over anyway. 
} 
        
      

Return Type of a C function

Every C function must specify the type of data that is being generated. For example, the max function above returns a value of type "double". Inside the function, the line "return X;" must be found, where X is a value or variable containing a value of the given type.

The return statement

When a line of code in a function that says: "return X;" is executed, the function "ends" and no more code in the function is executed. The value of X (or the value in the variable represented by X) becomes the result of the function.

Calling a C function (aka invoke a function)

When one piece of code invokes or calls a function, it is done by the following syntax:
         
         
        variable = function_name ( args, ...); 
         
        
        
      
The function name must match exactly the name of the function in the function prototype. The args are a list of values (or variables containing values) that are "passed" into the function.
The number of args "passed" into a function must exactly match the number of parameters required for the function. The type of each arg must exactly match the type of each parameter. The return variable type must exactly match the return type of the function.
The "variable" in the example above must have a type equivalent to the return type of the function. Inside the function, somewhere will be the line "return X". The value of X is then copied into the "variable".

Parameters in C functions

A Parameter is the symbolic name for "data" that goes into a function. There are two types of parameters in C: Pass by Value, Pass by Reference.
  • Pass by Value

    Pass by Value, means that a copy of the data is made and stored by way of the name of the parameter. Any changes to the parameter have NO affect on data in the calling function.
  • Pass by Reference

    reference parameter "refers" to the original data in the calling function. Thus any changes made to the parameter are ALSO MADE TO THE ORIGINAL variable.
    There are two ways to make a pass by reference parameter:
    1. ARRAYS
      Arrays are always pass by reference in C. Any change made to the parameter containing the array will change the value of the original array.
    2. The ampersand used in the function prototype.
      function ( & parameter_name )
      To make a normal parameter into a pass by reference parameter, we use the "& param" notation. The ampersand (&) is the syntax to tell C that any changes made to the parameter also modify the original variable containing the data.

Pass by Value Example:

In C, the default is to pass by value. For example:
         
 
        // 
        // C function using pass by value. (Notice no &) 
        // 
        void 
        doit( int x ) 
        { 
             x = 5; 
        } 
 
        // 
        // Test function for passing by value (i.e., making a copy) 
        // 
        int 
        main() 
        { 
          int z = 27; 
          doit( z ); 
          fprintf('z is now %d\n', z); 
 
          return 0; 
        } 
        
      

Pass by Reference Example:

Again, remember the Syntax is to use the '&' in front of the variable. For example:
         
 
        // 
        // C using Reference Parameter! 
        // 
        void 
        doit( int & x ) 
        { 
             x = 5; 
        } 
 
 
        // 
        // Test code for passing by a variable by reference 
        // 
        int 
        main() 
        { 
          int z = 27; 
          doit( z ); 
          fprintf('z is now %d\n', z); 
 
          return 0; 
        } 
        
      
In summary, if you use a reference parameter, any changes to the parameter inside the function are reflected "outside" of the function! If you don't use the & (pass by reference), then we get the same behavior as in Matlab.
Reference parameters are used to make programs more "efficient". Consider passing in a structure as a parameter. If the structure is very big, and we copy all of it, then we are using a lot of unnecessary memory.

Array Parameter Example (ALWAYS pass by reference)

Arrays are always passed by reference in C. They do not use the '&' notation, but are pass by reference none the less. For example:
         
 
        // 
        // Initialize an array with values 1,2,3,...,length_of_array 
        // 
        // Notice: Any changes made to "array_variable" are reflected in 
        //         the calling code! Arrays are pass by reference! 
        // 
        // Notice: There is no return statement, but still the array is changed 
        //         and can be said to be "returned" to the calling function. 
        // 
        void 
        build_array( int array_variable[], int length_of_array ) 
        { 
            for (int i=0; i<length_of_array; i++) 
              { 
                array_variable[i] = i; 
              } 
        } 
 
 
        // 
        // Test code for passing an array by reference 
        // 
        int 
        main() 
        { 
          int values[50]; 
 
          fprintf('the value at location 7 starts as %d\n', values[7]); 
 
          build_array(values, 50); 
 
          fprintf('the value at location 7 is now %d\n', values[7]); 
 
          return 0; 
        } 
        
      

Constant Reference

To protect from accidentally changing a reference parameter, when we really want it not to be changed (we just want to save time/memory) we can use the C keyword const. For example:
         
 
        // 
        // C Code using a CONSTANT reference Parameter 
        // 
        void 
        doit( const int & x ) 
        { 
            x = 5// ILLEGAL 
        } 
 
        // 
        // Main Function 
        // 
        int 
        main() 
        { 
          int z = 27; 
          doit( z ); 
          fprintf('z is now %d\n', z); 
 
          return 0; 
        } 
        
      

Void Functions

If a function does not return a value, then a special "TYPE" is used to tell the computer this. The return type is "void" (all lower case).
Void functions are mostly used in two classes of functions.
  1. The first is a function that prints information for the user to read. For example (for our purposes), the printf function is treated as a void function. (In actuality, printf returns an integer which is the number of characters printed... but we almost always ignore this value.)
  2. The second use of void functions is with "reference" parameters (e.g., Arrays). A reference parameter is not a copy of the input data, as is so often the case. A reference parameter is an "alias" for the same bucket in memory as the input data. Thus any change made to a reference parameter is in fact made to the original variable!