Monday, 22 December 2014

Geocoding and Reverse Geocoding using JavaScript

geocoding.js
function initialize(lat, lng, address){
     var latlng = new google.maps.LatLng(lat, lng)
     var mapOptions = {
         center: latlng,
         zoom: 4
     };
       
     var map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
       
     var marker = new google.maps.Marker({
          position: latlng,
          title: address,
         map: map,
       draggable: true
     });
    
     var infotext = address + '
' + 'Latitude: '+lat+' Longitude: '+lng; var infowindow = new google.maps.InfoWindow(); infowindow.setContent(infotext); infowindow.setPosition(new google.maps.LatLng(lat, lng)); infowindow.open(map); } function getLatLng(){ var address = document.getElementById("txtAddress").value; var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function(results, status){ if (status == google.maps.GeocoderStatus.OK){ var longaddress = results[0].address_components[0].long_name; initialize(results[0].geometry.location.lat(), results[0].geometry.location.lng(), longaddress); } else{ alert('Geocode error: ' + status); } }); }
reverseGeocoding.js
function getAddress(lat, lng){
    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({ 'latLng': latlng }, function(results, status){
    if (status == google.maps.GeocoderStatus.OK){
        if (results[1]){
            var address = results[1].formatted_address;
            alert(address);
        }
         else{
            alert("No results found");
         }
    }
    else {
        alert("Geocoder failed due to: " + status);
    }
    });
}
    
function getLocation() {
    var x = document.getElementById("btnGetAddress");
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
   getAddress(position.coords.latitude, position.coords.longitude)
}
default.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Search Location</title>
  <link rel="stylesheet" type="text/css" href="Styles/myStyle.css" />
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=">
</script>
  <script type="text/javascript" src="Scripts/geocoding.js">
</script>
  <script type="text/javascript" src="Scripts/reverseGeocoding.js">
</script>
</head>

<body onload="initialize(28.4990296, 77.06971279999993, 'Nagarro Software')">
  <div style="width:1350px">
    <div id="header" style="background-color:#FFA500;">
      <h1 style="margin-bottom:0;"></h1>

      <center>
        <h1 style="margin-bottom:0;">Location Provider</h1>
      </center>
    </div>

    <div id="left-column" style=
    "background-color:#FFD700;height:540px;width:155px;float:left;">
      <a href="default.html">Geocoding</a><br />
      <p><a href="#" onclick="getLocation()">Reverse Geocoding</a><br /></p>
    </div>

    <div id="content" style="background-color:#EEEEEE;float:left;style=" width:=""
    height:="">
      <div style="width:500px;">
        <input id="txtAddress" type="text" class="textbox" placeholder=
        "Enter address here..." /> <input id="btnGetLatLng" type="button" class="button"
        value="Submit" onclick="getLatLng();" />
      </div>

      <div id="myMap" style="width: 1160px; height: 505px;"></div>
    </div>

    <div id="footer" style="background-color:#FFA500;clear:both;text-align:center;">
      © Arjun sunel
    </div>
  </div>
</body>
</html>
myStyle.css
body
{
 background-color: gray;
}

input.button
{
 background-color: blue;
 color:white;
 font-family: "Segoe UI";
 border: 0px none;
 font-size: 100%;
 height: 2.142em;
 min-width: 6em;
 width:150px
}

input.textbox
{
 border: 1px solid #BABABA;
 color: #212121;
 font-family: "Segoe UI";
 font-size: 100%;
 padding: 4px 8px;
 width:325px;
 height:22px;
 z-index: 6
}

Sunday, 21 December 2014

How to type Reverse Alphabet in less than 2 seconds?

I used the exact same method to type the alphabets in reverse order as explained in this post. It got me the timing of 1.73 seconds.

Wednesday, 17 December 2014

Find root using Halley's Method

#include<stdio.h>

#define F(x) (x*x - x -6)
#define F_PRIME(x) (2*x - 1)
#define F_DOUBLE_PRIME(x) (2)
#define MAX_ITER 100

float Halley(float x0)
{
    int iter = 0;
    float x1;
    
    while(iter < MAX_ITER)
    {
        x1 = x0 - (2 * F(x0) * F_PRIME(x0)) / (2 * F_PRIME(x0) * F_PRIME(x0) - F(x0) * F_DOUBLE_PRIME(x0));
        x0 = x1;
        iter++;
    }
    return x0;
}

int main()
{
    printf("Finding root of a continuous function using Newton's method.\n");
    
    float x0 = 1;
    printf("Root of the given function is : %f\n", Halley(x0));
    return 0;
}

Find root using Newton's method

#include<stdio.h>

#define F(x) (x*x - 4)
#define FPrime(x) (2*x)
#define MAX_ITER 100

float Newton(float x0)
{
    int iter = 0;
    float x1;
    
    while(iter < MAX_ITER)
    {
        x1 = x0 - F(x0)/FPrime(x0);
        x0 = x1;
        iter++;
    }
    return x0;
}

int main()
{
    printf("Finding root of a continuous function using Newton's method.\n");
    
    float x0 = 1;
    printf("Root of the given function is : %f\n", Newton(x0));
    return 0;
}

Find root using False Position Method

#include<stdio.h>
#include<math.h>

#define F(x) ((2*x)+1)
#define ERROR 0.00001
#define MAX_ITER 1000

float FalsePosition(float a, float b)
{   
    float c;
    int iter = 0;
    do
    {
        c = b - F(b) * (b - a) / (F(b) - F(a));

        printf("F(a): %f, F(b) : %f, F(c) : %f, a: %f, b : %f, c : %f\n", F(a), F(b), F(c), a, b, c);

        if((F(c) > 0 && F(a) > 0) || (F(c) < 0 && F(a) < 0))
        {
            a = c;
        }
        else
        {
            b=c;
        }

        iter++;
    }
    while(fabsf(F(c)) > ERROR && iter < MAX_ITER);
    return c;
}

int main()
{
    float a = -2.5;
    float b = 2.5;

    printf("Finding root in the interval [%f, %f]\n", a, b);

    if((F(a)>0 && F(b)>0) || (F(a)<0 && F(b)<0))
    {
        printf("No root lie in the interval [%f, %f]", a, b);
    }
    else
    {
        printf("The root is : %f\n", FalsePosition(a, b));
    }

    return 0;
}

Find root using Bisection Method

#include<stdio.h>
#include<math.h>

#define F(x) ((2*x)+1)
#define ERROR 0.00001

float Bisection(float a, float b)
{ 
 float mid;
 do
 {
  mid = (a+b)/2;
  printf("F(a): %f, F(b) : %f, F(mid) : %f\n", F(a), F(b), F(mid));

  if((F(mid)>0 && F(a)>0) || (F(mid)<0 && F(a)<0))
  {
   a = mid;
  }
  else
  {
   b = mid;
  }
  
  
 } while(fabsf(F(mid)) > ERROR);
 
 return a;
}

int main()
{
 float a = -2.5;
 float b = 2.5;
 
 printf("Finding root in the interval [%f, %f]\n", a, b);
 
 if((F(a)>0 && F(b)>0) || (F(a)<0 && F(b)<0))
 {
  printf("No root lie in the interval [%f, %f]", a, b);
 }
 else
 {
  printf("The root is : %f\n", Bisection(a, b));
 }
 
 return 0;
}

Tuesday, 16 December 2014

Find MinCut of a Graph using networkx

'''
* Implemented by Arjun sunel.
'''
#Program to find min-cut of a graph using Karger's Algorithm having running time O(n*n*n*n*logn)
import networkx as nx, random, matplotlib.pyplot as plt
def main():
 G =nx.MultiGraph()     #defining graph
 G.add_edges_from([(1,2),(2,3),(3,4),(4,2),(4,5) , (6,7), ( 7,8) , ( 8,5) , (1,3) , (6,5) , (9, 10) , (10,1) , (9, 1), (5,1) , (5, 11) , (7,5) , (8, 6)  , (10 , 3) , (9, 3) , (11, 7)])  #adding edges
 min_cut(G)  #prints min cut of G        #K = nx.gnm_random_graph(10 , 40) ---> used for creating a random graph
 nx.draw(G)   #plots graph G
 plt.show()   #to show graph
 
def min_cut(G):  #min-cut function
 u= (G.order())**2 # number of iterations required to ensure that we will get a min-cut
 List=Cut(G)  #initialized List to a Cut of G
 while u>0:   #while loop starts
  if len(Cut(G))<len(List): #comparing current and previous cut's lengths to get minimum of them
   List=Cut(G) 
  u=u-1
 print "min_cut is :", List   #prints min cut
 
def Cut(G):   #function to find a cut of G
 H = nx.MultiGraph()  #declared H and I as multigraphs
 for a,b in G.edges_iter():  # "for loop" for assigning "edges" as "weights" to each edge
  H.add_edge(a,b,weight= (a,b)) 
  
 while H.order()>2: # while loop  until number of nodes becomes 2
  (a,b,d)=random.choice(H.edges(data=True)) #randomly selected edge    

  for e  in H.edges():
   if    e== ( a , b ) : H.remove_edge(a,b )   #removing randomly selected edge

  for i in H.neighbors(b):    #adding and deleting edges during combining two nodes
   j=len(H.get_edge_data(b,i))
   while j>0: 
    H.add_edge( a ,  i  ,  weight=  H.get_edge_data(b,i)[j-1]['weight']   )
    j=j-1
   H.remove_edge(b,i)
  H.remove_node(b)  #while loop ends
  
 cut=[]
 for e in H.edges(data = True):
  cut.append(e[2]['weight']) 
 return cut     #returns a cut of the graph
 
if __name__ == '__main__':
    main()      #calls the main function


Monday, 15 December 2014

Recursive BubbleSort for Array of Structures

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// enumeration denoting sort type
enum CompareDataType
{
    cmpStringType = 1,
    cmpIntType = 2
};

// Employee structure
struct Employee
{
    char *name;
    int age;
};

// Method to swap two structures by reference.
void Swap(struct Employee *first, struct Employee *second)
{
    struct Employee temp = *first;
    *first = *second;
    *second = temp;
}


int IsLessThan(struct Employee *first, struct Employee* second, enum CompareDataType cmpType)
{
    int res = 0;
    switch (cmpType)
    {
        case cmpStringType:
            res = strcmp(first->name, second->name);
            break;
            
        case cmpIntType:
            res = first->age < second->age ? -1 : (second->age < first->age);
            break;
            
        default:
            fprintf(stderr, "Invalid sort comparison type\n");
            exit(EXIT_FAILURE);
    }
    return res;
}

// Bubble Sort Method
void BubbleSort(struct Employee array[], int size, enum CompareDataType cmpType)
{
    int i, swapped = 0;
    
    if(size <= 1)
        return;
    
    for(i = 0; i < size - 1; i++)
    {
        if (IsLessThan(array+i, array+i+1, cmpType) > 0)
        {
            Swap(&array[i], &array[i + 1]);
            swapped = 1;
        }
    }
    
    if (swapped)
        BubbleSort(array, size-1, cmpType);
}

// Entry point of the program
int main()
{
    struct Employee array[] = {{"John", 45}, {"Mary", 23}, {"Celina", 79}, {"Mike", 41}};
    int arraySize = 4;
    int index;
    
    printf("Before Sorting : \n");
    for(index = 0; index < arraySize; index++)
    {
        printf("(%s, %d) ", array[index].name, array[index].age);
    }
    
    printf("\n");
    
    BubbleSort(array, arraySize, cmpStringType);
    printf("After Sorting by name : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");
    
    BubbleSort(array, arraySize, cmpIntType);
    printf("After Sorting by age : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");       
    return 0;
}

Sunday, 14 December 2014

Recursive BubbleSort for Array of Strings

#include<stdio.h>
#include<string.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two strings by reference.
void Swap(char **first, char **second)
{
 char *temp = *first;
 *first = *second;
 *second = temp;
}

// Bubble Sort Method
void BubbleSort(char *array[], int size, int swapped)
{
 int i;
 
 if(swapped == 0 || size == 0)
    {
        return;
    }
 
 for(i = 0; i < size - 1; i++)
 {
  swapped = 0;

  if(strcmp(array[i], array[i+1]) > 0)
  {
   Swap(&array[i], &array[i + 1]);
   swapped = 1;
  }
 }
 
 BubbleSort(array, size-1, swapped);
}

// Entry point of the program
int main()
{
 char* array[] = {"dog", "dose", "apple", "baby", "den", "deck"};
 int arraySize = 6;
 int index;

 printf("Before Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 }  

 printf("\n");
 
 int swapped = 1;
 
 BubbleSort(array, arraySize, swapped);
 printf("After Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 } 
 
 printf("\n");
 return 0;
}

Recursive BubbleSort for Array of Characters

#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two characters by reference.
void Swap(char *first, char *second)
{
 char temp = *first;
 *first = *second;
 *second = temp;
}

// Bubble Sort Method
void BubbleSort(char array[], int size, int swapped)
{
    if(swapped == 0 || size == 0)
    {
        return;
    }
    
 int i;
 for(i = 0; i < size - 1; i++)
 {
  swapped = 0;
 
  if( array[i] > array[i + 1] )
  {
   Swap(&array[i], &array[i + 1]);
   swapped = 1;
  }
 }
 
    BubbleSort(array, size-1, swapped);
}

// Entry point of the program
int main()
{
 char array[] = {'d', 'a', 'c', 'b'};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%c ", array[index]);
 } 
 
 int swapped = 1;
 
 BubbleSort(array, arraySize, swapped);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%c ", array[index]);
 } 

 printf("\n");
}


Recursive BubbleSort for Array of Integers

#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two integers by reference.
void Swap(int *first, int *second)
{
 int temp = *first;
 *first = *second;
 *second = temp;
}

// Bubble Sort Method
void BubbleSort(int array[], int size, int swapped)
{
    if(swapped == 0 || size == 0)
    {
        return;
    }
    
 int i;
 for(i = 0; i < size - 1; i++)
 {
  swapped = 0;
 
  if( array[i] > array[i + 1] )
  {
   Swap(&array[i], &array[i + 1]);
   swapped = 1;
  }
 }
 
    BubbleSort(array, size-1, swapped);
}

// Entry point of the program
int main()
{
 int array[] = {5, -12, 14, 7};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 int swapped = 1;
 
 BubbleSort(array, arraySize, swapped);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 printf("\n");
}


Iterative InsertionSort for Array of Structures

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*
* Implemented by Arjun Sunel.
*/

// enumeration denoting sort type
enum CompareDataType
{
    cmpStringType = 1,
    cmpIntType = 2
};

// Employee structure
struct Employee
{
    char *name;
    int age;
};

// Method to swap two structures by reference.
void Swap(struct Employee *first, struct Employee *second)
{
    struct Employee temp = *first;
    *first = *second;
    *second = temp;
}


int IsLessThan(struct Employee *first, struct Employee* second, enum CompareDataType cmpType)
{
    int res = 0;
    switch (cmpType)
    {
        case cmpStringType:
            res = strcmp(first->name, second->name);
            break;
            
        case cmpIntType:
            res = first->age < second->age ? -1 : (second->age < first->age);
            break;
            
        default:
            fprintf(stderr, "Invalid sort comparison type\n");
            exit(EXIT_FAILURE);
    }
    return res;
}

// Insertion Sort Method
void InsertionSort(struct Employee array[], int size, enum CompareDataType cmpType)
{
 int i, j;
 struct Employee curElement;
 
 for(i = 1; i < size; i++)
 {
     curElement = array[i];
  j = i - 1;
  while(j >=0 && (IsLessThan(array+j, &curElement, cmpType) > 0))
  {
   Swap(&array[j+1], &array[j]);
   j--;
  }
  
  array[j+1] = curElement;
 }
}

// Entry point of the program
int main()
{
    struct Employee array[] = {{"John", 45}, {"Mary", 23}, {"Celina", 79}, {"Mike", 41}};
    int arraySize = 4;
    int index;
    
    printf("Before Sorting : \n");
    for(index = 0; index < arraySize; index++)
    {
        printf("(%s, %d) ", array[index].name, array[index].age);
    }
    
    printf("\n");
    
    InsertionSort(array, arraySize, cmpStringType);
    printf("After Sorting by name : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");
    
    InsertionSort(array, arraySize, cmpIntType);
    printf("After Sorting by age : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");       
    return 0;
}


Iterative InsertionSort for Array of Strings

#include<stdio.h>
#include<string.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two strings by reference.
void Swap(char **first, char **second)
{
 char *temp = *first;
 *first = *second;
 *second = temp;
}

// Insertion Sort Method
void InsertionSort(char *array[], int size)
{
 int i, j;
 char *curElement;
 
 for(i = 1; i < size; i++)
 {
  curElement = array[i];
  
  j = i - 1;
  while(j >=0 && strcmp(array[j], curElement) > 0)
  {
   Swap(&array[j+1], &array[j]);
   j--;
  }
  
  array[j+1] = curElement;
 }
}

// Entry point of the program
int main()
{
 char* array[] = {"dog", "dose", "apple", "baby", "den", "deck"};
 int arraySize = 6;
 int index;

 printf("Before Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 }  

 printf("\n");
 
 InsertionSort(array, arraySize);
 printf("After Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 } 
 
 printf("\n");
 return 0;
}


Iterative InsertionSort for Array of Integers

#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two integers by reference.
void Swap(int *first, int *second)
{
 int temp = *first;
 *first = *second;
 *second = temp;
}

// Insertion Sort Method
void InsertionSort(int array[], int size)
{
 int i, j, curElement;
 
 for(i = 1; i < size; i++)
 {
  curElement = array[i];
  
  j = i - 1;
  while(j >=0 && array[j] > curElement)
  {
   Swap(&array[j+1], &array[j]);
   j--;
  }
  
  array[j+1] = curElement;
 }
}

// Entry point of the program
int main()
{
 int array[] = {5, -12, 14, 7};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 InsertionSort(array, arraySize);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 printf("\n");
}


Iterative InsertionSort for Array of Characters

#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two characters by reference.
void Swap(char *first, char *second)
{
 char temp = *first;
 *first = *second;
 *second = temp;
}

// Insertion Sort Method
void InsertionSort(char array[], int size)
{
 int i, j, curElement;
 
 for(i = 1; i < size; i++)
 {
  curElement = array[i];
  
  j = i - 1;
  while(j >=0 && array[j] > curElement)
  {
   Swap(&array[j+1], &array[j]);
   j--;
  }
  
  array[j+1] = curElement;
 }
}

// Entry point of the program
int main()
{
 char array[] = {'d', 'a', 'c', 'b'};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%c ", array[index]);
 } 
 
 InsertionSort(array, arraySize);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%c ", array[index]);
 } 

 printf("\n");
}


Iterative BubbleSort for Array of Structures

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*
* Implemented by Arjun Sunel.
*/

// enumeration denoting sort type
enum CompareDataType
{
    cmpStringType = 1,
    cmpIntType = 2
};

// Employee structure
struct Employee
{
    char *name;
    int age;
};

// Method to swap two structures by reference.
void Swap(struct Employee *first, struct Employee *second)
{
    struct Employee temp = *first;
    *first = *second;
    *second = temp;
}


int IsLessThan(struct Employee *first, struct Employee* second, enum CompareDataType cmpType)
{
    int res = 0;
    switch (cmpType)
    {
        case cmpStringType:
            res = strcmp(first->name, second->name);
            break;
            
        case cmpIntType:
            res = first->age < second->age ? -1 : (second->age < first->age);
            break;
            
        default:
            fprintf(stderr, "Invalid sort comparison type\n");
            exit(EXIT_FAILURE);
    }
    return res;
}

// Bubble Sort Method
void BubbleSort(struct Employee array[], int size, enum CompareDataType cmpType)
{
 int i, j;
 int swapped = 1;
 
 for(i = 0; swapped && i < size - 1; i++)
 {
  swapped = 0;
  for(j = 0; j < size - 1 - i; j++)
  {
  if(IsLessThan(array+j, array+j+1, cmpType) > 0)
   {
    Swap(&array[j], &array[j + 1]);
    swapped = 1;
   }
  }
 }
}

// Entry point of the program
int main()
{
    struct Employee array[] = {{"John", 45}, {"Mary", 23}, {"Celina", 79}, {"Mike", 41}};
    int arraySize = 4;
    int index;
    
    printf("Before Sorting : \n");
    for(index = 0; index < arraySize; index++)
    {
        printf("(%s, %d) ", array[index].name, array[index].age);
    }
    
    printf("\n");
    
    BubbleSort(array, arraySize, cmpStringType);
    printf("After Sorting by name : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");
    
    BubbleSort(array, arraySize, cmpIntType);
    printf("After Sorting by age : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");       
    return 0;
}



Iterative BubbleSort for Array of Strings

#include<stdio.h>
#include<string.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two strings by reference.
void Swap(char **first, char **second)
{
 char *temp = *first;
 *first = *second;
 *second = temp;
}

// Bubble Sort Method
void BubbleSort(char *array[], int size)
{
 int i, j;
 int swapped = 1;
 
 for(i = 0; swapped && i < size - 1; i++)
 {
  swapped = 0;
  for(j = 0; j < size - 1 - i; j++)
  {
   if(strcmp(array[j], array[j+1]) > 0)
   {
    Swap(&array[j], &array[j + 1]);
    swapped = 1;
   }
  }
 }
}

// Entry point of the program
int main()
{
 char* array[] = {"dog", "dose", "apple", "baby", "den", "deck"};
 int arraySize = 6;
 int index;

 printf("Before Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 }  

 printf("\n");
 
 BubbleSort(array, arraySize);
 printf("After Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 } 
 
 return 0;
}



Iterative BubbleSort for Array of Integers

#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two integers by reference.
void Swap(int *first, int *second)
{
 int temp = *first;
 *first = *second;
 *second = temp;
}

// Bubble Sort Method
void BubbleSort(int array[], int size)
{
 int i, j;
 int swapped = 1;
 
 for(i = 0; swapped && i < size - 1; i++)
 {
  swapped = 0;
  for(j = 0; j < size - 1 - i; j++)
  {
   if( array[j] > array[j + 1] )
   {
    Swap(&array[j], &array[j + 1]);
    swapped = 1;
   }
  }
 }
}

// Entry point of the program
int main()
{
 int array[] = {5, -12, 14, 7};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 BubbleSort(array, arraySize);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 printf("\n");
}


Iterative BubbleSort for Array of Characters

#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two characters by reference.
void Swap(char *first, char *second)
{
 char temp = *first;
 *first = *second;
 *second = temp;
}

// Bubble Sort Method
void BubbleSort(char array[], int size)
{
 int i, j;
 int swapped = 1;
 
 for(i = 0; swapped && i < size - 1; i++)
 {
  swapped = 0;
  for(j = 0; j < size - 1 - i; j++)
  {
   if( array[j] > array[j + 1] )
   {
    Swap(&array[j], &array[j + 1]);
    swapped = 1;
   }
  }
 }
}

// Entry point of the program
int main()
{
 char array[] = {'d', 'a', 'c', 'b'};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%c ", array[index]);
 } 
 
 BubbleSort(array, arraySize);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%c ", array[index]);
 } 

 printf("\n");
}


Recursive MergeSort for Array of Structures

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// enumeration denoting sort type
enum CompareDataType
{
    cmpStringType = 1,
    cmpIntType = 2
};

// Employee structure
struct Employee
{
    char *name;
    int age;
};

// Method to swap two structures by reference.
void Swap(struct Employee *first, struct Employee *second)
{
    struct Employee temp = *first;
    *first = *second;
    *second = temp;
}


int IsLessThan(struct Employee *first, struct Employee* second, enum CompareDataType cmpType)
{
    int res = 0;
    switch (cmpType)
    {
        case cmpStringType:
            res = strcmp(first->name, second->name);
            break;
            
        case cmpIntType:
            res = first->age < second->age ? -1 : (second->age < first->age);
            break;
            
        default:
            fprintf(stderr, "Invalid sort comparison type\n");
            exit(EXIT_FAILURE);
    }
    return res;
}

// Method to get the partition index of an array.
int Partition(struct Employee array[], int startIndex, int endIndex, enum CompareDataType cmpType)
{
 struct Employee endIndexElement = array[endIndex];
 int index;
 int tempIndex = startIndex;
 
 for(index = startIndex; index <= endIndex - 1; index++)
 {
  if(IsLessThan(&array[index], &endIndexElement, cmpType) < 0)
  {
    Swap( &array[index], &array[tempIndex]);
    tempIndex++;
  }
 }
 
 Swap( &array[endIndex], &array[tempIndex]);
 return tempIndex;
}

// Quicksort method
void QuickSort(struct Employee array[], int startIndex, int endIndex, enum CompareDataType cmpType)
{
 int partitionIndex;
 
 if(startIndex < endIndex)
 {
  partitionIndex = Partition(array, startIndex, endIndex, cmpType);
  
  // Now the element at partition index is fixed, we will recursively call the QuickSort method on the left and right subarrays.
  QuickSort(array, startIndex, partitionIndex - 1, cmpType);
  QuickSort(array, partitionIndex + 1, endIndex, cmpType);
 }
}

// Merging the sorted left and right subarrays.
void Merge(struct Employee array[], int startIndex, int midIndex, int endIndex, enum CompareDataType cmpType)
{
 int leftSubArraySize = (midIndex - startIndex) + 1 ;
 int rightSubArraySize = (endIndex - midIndex);
 
 struct Employee Left[leftSubArraySize];
 struct Employee Right[rightSubArraySize];
 
 int i, j, k;
 
 for( i = 0; i < leftSubArraySize; i++)
 {
  Left[i] = array[startIndex + i];
 }
 
 for( j = 0; j < leftSubArraySize; j++)
 {
  Right[j] = array[midIndex + j + 1];
 }
 
 i = 0;
 j = 0;
 k = startIndex;
 
 while(i < leftSubArraySize && j < rightSubArraySize)
 {
  if(IsLessThan(&Left[i], &Right[j], cmpType) > 0)
  {
   array[k] = Left[i];
   i++;
  }
  else
  {
   array[k] = Right[j];
   j++;
  }
  
  k++;
 }
 
 while(i < leftSubArraySize)
 {
  array[k] = Left[i];
  i++;
  k++;
 }
 
 while(j < rightSubArraySize)
 {
  array[k] = Right[j];
  j++;
  k++;
 }
}

// MergeSort method
void MergeSort(struct Employee array[], int startIndex, int endIndex, enum CompareDataType cmpType)
{
 if(startIndex < endIndex)
 {
  int midIndex = (startIndex + (endIndex - startIndex)/2);
  
  // recursively call the MergeSort method on the left and right subarrays.
  MergeSort(array, startIndex, midIndex, cmpType);
  MergeSort(array, midIndex + 1, endIndex, cmpType);
  Merge(array, startIndex, midIndex, endIndex, cmpType);
 }
}

// Entry point of the program
int main()
{
    struct Employee array[] = {{"John", 45}, {"Mary", 23}, {"Celina", 79}, {"Mike", 41}};
    int arraySize = 4;
    int index;
    
    printf("Before Sorting : \n");
    for(index = 0; index < arraySize; index++)
    {
        printf("(%s, %d) ", array[index].name, array[index].age);
    }
    
    printf("\n");
    
    QuickSort(array, 0, arraySize-1, cmpStringType);
    printf("After Sorting by name : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");
    
    QuickSort(array, 0, arraySize-1, cmpIntType);
    printf("After Sorting by age : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");       
    return 0;
}

Recursive MergeSort for Array of Strings

#include<stdio.h>
#include<string.h>
/*
* Implemented by Arjun Sunel.
*/

// Merging the sorted left and right subarrays.
void Merge(char *array[], int startIndex, int midIndex, int endIndex)
{
 int leftSubArraySize = (midIndex - startIndex) + 1 ;
 int rightSubArraySize = (endIndex - midIndex);
 
 char *Left[leftSubArraySize];
 char *Right[rightSubArraySize];
 
 int i, j, k;
 
 for( i = 0; i < leftSubArraySize; i++)
 {
  Left[i] = array[startIndex + i];
 }
 
 for( j = 0; j < leftSubArraySize; j++)
 {
  Right[j] = array[midIndex + j + 1];
 }
 
 i = 0;
 j = 0;
 k = startIndex;
 
 while(i < leftSubArraySize && j < rightSubArraySize)
 {
  if(strcmp(Left[i], Right[j]) < 0)
  {
   array[k] = Left[i];
   i++;
  }
  else
  {
   array[k] = Right[j];
   j++;
  }
  
  k++;
 }
 
 while(i < leftSubArraySize)
 {
  array[k] = Left[i];
  i++;
  k++;
 }
 
 while(j < rightSubArraySize)
 {
  array[k] = Right[j];
  j++;
  k++;
 }
}

// MergeSort method
void MergeSort(char *array[], int startIndex, int endIndex)
{
 if(startIndex < endIndex)
 {
  int midIndex = (startIndex + (endIndex - startIndex)/2);
  
  // recursively call the MergeSort method on the left and right subarrays.
  MergeSort(array, startIndex, midIndex);
  MergeSort(array, midIndex + 1, endIndex);
  Merge(array, startIndex, midIndex, endIndex);
 }
}

// Entry point of the program
int main()
{
 char* array[] = {"dog", "dose", "apple", "baby", "den", "deck"};
 int arraySize = 6;
 int index;

 printf("Before Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 }  

 printf("\n");
 
 MergeSort(array, 0, arraySize-1);
  printf("After Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 } 
 
 return 0;
}


Recursive MergeSort for Array of Integers

#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Merging the sorted left and right subarrays.
void Merge(int array[], int startIndex, int midIndex, int endIndex)
{
 int leftSubArraySize = (midIndex - startIndex) + 1 ;
 int rightSubArraySize = (endIndex - midIndex);
 
 int Left[leftSubArraySize], Right[rightSubArraySize];
 
 int i, j, k;
 
 for( i = 0; i < leftSubArraySize; i++)
 {
  Left[i] = array[startIndex + i];
 }
 
 for( j = 0; j < leftSubArraySize; j++)
 {
  Right[j] = array[midIndex + j + 1];
 }
 
 i = 0;
 j = 0;
 k = startIndex;
 
 while(i < leftSubArraySize && j < rightSubArraySize)
 {
  if(Left[i] <= Right[j])
  {
   array[k] = Left[i];
   i++;
  }
  else
  {
   array[k] = Right[j];
   j++;
  }
  
  k++;
 }
 
 while(i < leftSubArraySize)
 {
  array[k] = Left[i];
  i++;
  k++;
 }
 
 while(j < rightSubArraySize)
 {
  array[k] = Right[j];
  j++;
  k++;
 }
}

// MergeSort method
void MergeSort(int array[], int startIndex, int endIndex)
{
 if(startIndex < endIndex)
 {
  int midIndex = (startIndex + (endIndex - startIndex)/2);
  
  // recursively call the MergeSort method on the left and right subarrays.
  MergeSort(array, startIndex, midIndex);
  MergeSort(array, midIndex + 1, endIndex);
  Merge(array, startIndex, midIndex, endIndex);
 }
}

// Entry point of the program
int main()
{
 int array[] = {5, -12, 14, 7};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 MergeSort(array, 0, arraySize-1);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 printf("\n");
}


Recursive MergeSort for Array of Characters

#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Merging the sorted left and right subarrays.
void Merge(char array[], int startIndex, int midIndex, int endIndex)
{
 int leftSubArraySize = (midIndex - startIndex) + 1 ;
 int rightSubArraySize = (endIndex - midIndex);
 
 char Left[leftSubArraySize], Right[rightSubArraySize];
 
 int i, j, k;
 
 for( i = 0; i < leftSubArraySize; i++)
 {
  Left[i] = array[startIndex + i];
 }
 
 for( j = 0; j < leftSubArraySize; j++)
 {
  Right[j] = array[midIndex + j + 1];
 }
 
 i = 0;
 j = 0;
 k = startIndex;
 
 while(i < leftSubArraySize && j < rightSubArraySize)
 {
  if(Left[i] <= Right[j])
  {
   array[k] = Left[i];
   i++;
  }
  else
  {
   array[k] = Right[j];
   j++;
  }
  
  k++;
 }
 
 while(i < leftSubArraySize)
 {
  array[k] = Left[i];
  i++;
  k++;
 }
 
 while(j < rightSubArraySize)
 {
  array[k] = Right[j];
  j++;
  k++;
 }
}

// MergeSort method
void MergeSort(char array[], int startIndex, int endIndex)
{
 if(startIndex < endIndex)
 {
  int midIndex = (startIndex + (endIndex - startIndex)/2);
  
  // recursively call the MergeSort method on the left and right subarrays.
  MergeSort(array, startIndex, midIndex);
  MergeSort(array, midIndex + 1, endIndex);
  Merge(array, startIndex, midIndex, endIndex);
 }
}

// Entry point of the program
int main()
{
 char array[] = {'d', 'a', 'c', 'b'};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%c ", array[index]);
 } 
 
 MergeSort(array, 0, arraySize-1);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%c ", array[index]);
 } 

 printf("\n");
}


Recursive QuickSort for Array of Structures

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// enumeration denoting sort type
enum CompareDataType
{
    cmpStringType = 1,
    cmpIntType = 2
};

// Employee structure
struct Employee
{
    char *name;
    int age;
};

// Method to swap two structures by reference.
void Swap(struct Employee *first, struct Employee *second)
{
    struct Employee temp = *first;
    *first = *second;
    *second = temp;
}


int IsLessThan(struct Employee *first, struct Employee* second, enum CompareDataType cmpType)
{
    int res = 0;
    switch (cmpType)
    {
        case cmpStringType:
            res = strcmp(first->name, second->name);
            break;
            
        case cmpIntType:
            res = first->age < second->age ? -1 : (second->age < first->age);
            break;
            
        default:
            fprintf(stderr, "Invalid sort comparison type\n");
            exit(EXIT_FAILURE);
    }
    return res;
}

// Method to get the partition index of an array.
int Partition(struct Employee array[], int startIndex, int endIndex, enum CompareDataType cmpType)
{
 struct Employee endIndexElement = array[endIndex];
 int index;
 int tempIndex = startIndex;
 
 for(index = startIndex; index <= endIndex - 1; index++)
 {
  if(IsLessThan(&array[index], &endIndexElement, cmpType) < 0)
  {
    Swap( &array[index], &array[tempIndex]);
    tempIndex++;
  }
 }
 
 Swap( &array[endIndex], &array[tempIndex]);
 return tempIndex;
}

// Quicksort method
void QuickSort(struct Employee array[], int startIndex, int endIndex, enum CompareDataType cmpType)
{
 int partitionIndex;
 
 if(startIndex < endIndex)
 {
  partitionIndex = Partition(array, startIndex, endIndex, cmpType);
  
  // Now the element at partition index is fixed, we will recursively call the QuickSort method on the left and right subarrays.
  QuickSort(array, startIndex, partitionIndex - 1, cmpType);
  QuickSort(array, partitionIndex + 1, endIndex, cmpType);
 }
}

// Entry point of the program
int main()
{
    struct Employee array[] = {{"John", 45}, {"Mary", 23}, {"Celina", 79}, {"Mike", 41}};
    int arraySize = 4;
    int index;
    
    printf("Before Sorting : \n");
    for(index = 0; index < arraySize; index++)
    {
        printf("(%s, %d) ", array[index].name, array[index].age);
    }
    
    printf("\n");
    
    QuickSort(array, 0, arraySize-1, cmpStringType);
    printf("After Sorting by name : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");
    
    QuickSort(array, 0, arraySize-1, cmpIntType);
    printf("After Sorting by age : \n");
    for(index = 0; index < arraySize; index++)
        printf("(%s, %d) ", array[index].name, array[index].age);
    
    printf("\n");       
    return 0;
}


Recursive QuickSort for Array of Strings

#include<stdio.h>
#include<string.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two strings by reference.
void Swap(char **first, char **second)
{
 char *temp = *first;
 *first = *second;
 *second = temp;
}

// Method to get the partition index of an array.
int Partition(char* array[], int startIndex, int endIndex)
{
 char *endIndexElement = array[endIndex];
 int index;
 int tempIndex = startIndex;
 
 for(index = startIndex; index <= endIndex - 1; index++)
 {
  if(strcmp(array[index], endIndexElement) < 0)
  {
   Swap( &array[index], &array[tempIndex]);
   tempIndex++;
  }
 }
 
 Swap( &array[endIndex], &array[tempIndex]);
 return tempIndex;
}

// Quicksort method
void QuickSort(char* array[], int startIndex, int endIndex)
{
 int partitionIndex;
 
 if(startIndex < endIndex)
 {
  partitionIndex = Partition(array, startIndex, endIndex);
  
  // Now the element at partition index is fixed, we will recursively call the QuickSort method on the left and right subarrays.
  QuickSort(array, startIndex, partitionIndex - 1);
  QuickSort(array, partitionIndex + 1, endIndex);
 }
}

// Entry point of the program
int main()
{
 char* array[] = {"dog", "dose", "apple", "baby", "den", "deck"};
 int arraySize = 6;
 int index;

 printf("Before Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 }  

 printf("\n");
 
 QuickSort(array, 0, arraySize-1);
  printf("After Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 } 
 
 return 0;
}


Recursive QuickSort for Array of Integers

#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two integers by reference.
void Swap(int *first, int *second)
{
 int temp = *first;
 *first = *second;
 *second = temp;
}

// Method to get the partition index of an array.
int Partition(int array[], int startIndex, int endIndex)
{
 int endIndexElement = array[endIndex];
 int index;
 int tempIndex = startIndex;
 
 for(index = startIndex; index <= endIndex - 1; index++)
 {
  if(array[index] <= endIndexElement)
  {
   Swap( &array[index], &array[tempIndex]);
   tempIndex++;
  }
 }
 
 Swap( &array[endIndex], &array[tempIndex]);
 return tempIndex;
}

// Quicksort method
void QuickSort(int array[], int startIndex, int endIndex)
{
 int partitionIndex;
 
 if(startIndex < endIndex)
 {
  partitionIndex = Partition(array, startIndex, endIndex);
  
  // Now the element at partition index is fixed, we will recursively call the QuickSort method on the left and right subarrays.
  QuickSort(array, startIndex, partitionIndex - 1);
  QuickSort(array, partitionIndex + 1, endIndex);
 }
}

// Entry point of the program
int main()
{
 int array[] = {5, -12, 14, 7};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 QuickSort(array, 0, arraySize-1);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 printf("\n");
}

Recursive QuickSort for Array of Characters

#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two characters by reference.
void Swap(char *first, char *second)
{
 char temp = *first;
 *first = *second;
 *second = temp;
}

// Method to get the partition index of a character array.
int Partition(char array[], int startIndex, int endIndex)
{
 int endIndexElement = array[endIndex];
 int index;
 int tempIndex = startIndex;
 
 for(index = startIndex; index <= endIndex - 1; index++)
 {
  if(array[index] <= endIndexElement)
  {
   Swap( &array[index], &array[tempIndex]);
   tempIndex++;
  }
 }
 
 Swap( &array[endIndex], &array[tempIndex]);
 return tempIndex;
}

// Quicksort method
void QuickSort(char array[], int startIndex, int endIndex)
{
 int partitionIndex;
 
 if(startIndex < endIndex)
 {
  partitionIndex = Partition(array, startIndex, endIndex);
  
  // Now the element at partition index is fixed, we will recursively call the QuickSort method on the left and right subarrays.
  QuickSort(array, startIndex, partitionIndex - 1);
  QuickSort(array, partitionIndex + 1, endIndex);
 }
}

// Entry point of the program
int main()
{
 char array[] = {'d', 'a', 'c', 'b'};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%c ", array[index]);
 } 
 
 QuickSort(array, 0, arraySize-1);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%c ", array[index]);
 } 

 printf("\n");
}


Wednesday, 10 December 2014

How to type English Alphabet in less than 2 seconds?

If you want impress others by typing alphabets (A-Z in order) in less than 2 seconds on QWERTY keyboard, then keep following things in mind:

a) Put your hands on keyboard in proper way. See here for reference.

Memorize a Shuffled Deck of Cards!

There are 3 steps in memorizing a shuffled deck of cards.

1.  Assign a character to each card:

Prepare a list of 52 characters, one for each of the 52 cards. One should be aware of the unique features or qualities of each character. More the unique features a character have, the more easily a card can be memorized.

Tuesday, 9 December 2014

3 Layered ASP.NET Application Example - Part 4

In this post, we will create UI for PersonalTaskTracker application.
  • Open Web.config file of the application.
  • Add the following lines to the Web.config file.


Web.config
 
<connectionstrings>
  <add connectionstring="data source=YOUR_SERVER_NAME; uid=YOUR_USER_ID; Pwd=YOUR_PASSWORD; database=PTT" name="PersonalTaskTrackerConnectionString">
 </add>
</connectionstrings>

3 Layered ASP.NET Application Example - Part 3

In this post, we will create BLL for PersonalTaskTracker application.

  • Right click the Solution and add a new project which is Console Application named BLL.
  • Right click the BLL project and add the reference to DAL
Add the following two classes to the BLL project.

3 Layered ASP.NET Application Example - Part 2


  • Open Microsoft Visual Studio.
  • Create a new ASP.NET Empty Web Application.
  • Name the project PersonalTaskTracker
  • Right click the Solution and add a new project which is Console Application named DAL.
  • Right click the DAL project and add the reference to System.Configuration

3 Layered ASP.NET Application Example - Part 1


We are going to  implement a Personal Task Tracker, a 3-layered ASP.NET application. This application supports the functions to add, edit, delete and view tasks. Each task has properties: description, summary,  date of creation and status (denotes whether the task is closed or open). The user interface will look something like:



Sunday, 7 December 2014

Generic Priority Queue Using Sorted Dictionary in C#

A priority queue is a queue in which items are sorted according to priority. An item with highest priority will come out of it first.

Here, we will see a generic priority queue implemented using Sorted Dictionary. By generic, it means we can make a priority queue of any type of objects, but the object should contain some priority property. In short, the generic object should be a derived class of the PriorityNode.

Monday, 1 December 2014

Searching a keyword in JSON Result-set

Note: the below code return all the objects that has at least one key with its value matching the keyword. The partial-searching is done here.