Sunday, March 16, 2014

Trying to level up:Reading pseudo code and libraries

Rather than being devoted to my thoughts and my obsessions,all the posts in this blog seem to be devoted to the stuff I do when I'm not compelled to do anything or the stuff I do when I ignore my responsibilities for a little while(a guilty pleasure I sometimes enjoy).Writing these posts also convinces me that I am not wasting the little time I have,I tell the guilty parts of me "See,you did enough to fill a blog post".Sometimes it also enables me to do quality brainstorming,I sometimes write new code or edit and improve my code for the blog.So essentially you can say it's more for myself than it is for you.And if I am doing this stuff in my free time,they are part of my thoughts and obsessions.This also allows me to share my code and my ideas with other developers which I rarely do.

Since the last blog post,I had enough time to read a bit of pseudo code and try my hand at implementing a few measly sorting algorithms and various linked-lists in C(please don't ask me to do the running time analysis...yet).

 #include<stdio.h>  
 #include<stdlib.h>  
 int getMaxGap(int size);  
 int* getRandomNumbers(int size,int seed);  
 int* shellSort(int arr[],int size);  
 int* getPseudoRandomNumbers(int size,int seed);  
 int getMaxGap(int size)  
 {  
      int gap=1;  
      while(gap<size)  
      {  
           gap=gap*3+1;  
      }  
      return gap/9;  
 }  
 //this gives me truly random numbers...but they are completely useless for sorting...  
 int* getRandomNumbers(int size,int seed)  
 {  
      int i;  
      srand(seed);  
      int *res=calloc(size,sizeof(int));  
      for(i=0;i<size;i++)  
      {  
           res[i]=rand();  
      }  
      return res;       
 }  
 int* getPseudoRandomNumbers(int size,int seed)  
 {  
      int i;  
      int *res=calloc(size,sizeof(int));  
      for(i=0;i<size;i++)  
      {  
           res[i]=rand()%seed;  
      }  
      return res;  
 }  
 int* insertionSort(int* arr,int size)  
 {  
      int i,j,key;  
      for(i=1;i<size;i++)  
      {  
           key=arr[i];  
           for(j=i-1;j>=0 && key<arr[j];j-=1)  
           {  
                arr[j+1]=arr[j];       
           }  
           arr[j+1]=key;       
      }  
      return arr;       
 }  
 int* shellSort(int arr[],int size)  
 {  
      int gap=getMaxGap(size);  
      int j,k,key;  
      while(gap>0)  
      {  
           for(j=gap;j<size;j++)  
           {  
                key=arr[j];  
                for(k=j-gap;k>=0 &&key<arr[k];k-=gap)  
                     arr[k+gap]=arr[k];                 
                arr[k+gap]=key;       
           }       
           gap=gap/3;  
      }  
      return arr;  
 }  
 //next for bubblesort...compare adjacent elements with one another and swap when required,you will notice that after i passes   
 //the n-1 th element is in it's proper place...  
 int* bubbleSort(int* arr,int size)  
 {  
      int i=0,pass=0;  
      int switched=1;  
      //because an element goes to it's proper place after each iteration,it would only require size-1 iterations...  
      for(pass=0;pass<size-1;pass++)  
      {  
           //for each pass...use size-pass-1 because of arr[i+1] i+1<size=>i<size-1  
           //checks if values have been swapped in this pass  
           if(switched)  
           {  
                switched=0;  
                for(i=0;i<size-pass-1;i++)  
                {  
                     if(arr[i]>arr[i+1])  
                     {  
                          switched=1;  
                          arr[i]=arr[i]+arr[i+1];  
                          arr[i+1]=arr[i]-arr[i+1];  
                          arr[i]=arr[i]-arr[i+1];  
                     }       
                }  
           }            
      }       
      return arr;       
 }  
 int main(int argc,char** argv)  
 {            
      int j;  
      int *res=getPseudoRandomNumbers(18,25);  
      printf("\nThe input array\n");  
      for(j=0;j<18;j++)  
      {  
           printf("%d\t",res[j]);  
      }  
      printf("\nThe output array is\n");  
      res=bubbleSort(res,18);  
      for(j=0;j<18;j++)  
      {  
           printf("%d\t",res[j]);  
      }  
      free(res);       
      return 0;  
 }  


I have learnt,a long time back about a magical chain of C structures called Linked Lists,this was a time when the word pointers andconsequently any code that had them terrified me before I realized that had it was just a way to directly access a memory locations and traverse them based on the size of data-type you were storing.In C,it is not just a useful feature,it is essentially the central core of the programming language.

Would you like to create an array,please specify a size so that we know how much memory to allocate in a contigious block and we wont always tell you this but what you have is the pointer to the first element,you want to update a value from a function without returning an updated value,better pass in a memory location using a pointer and change the value.Maybe you would like to hold a reference to a struct in another struct,use a pointer because structs are passed in by value.

Here is a doubly linked list that can act as a queue,a stack and a deque,I wrote this a long time back and I havent checked or updated in a while,so I am really nervous about posting it here.

 #include<stdio.h>  
 #include<stdlib.h>  
 struct Node* createNode(int val);  
 void insertBefore(struct Node* toAdd,struct Node* behind);  
 void insertAfter(struct Node* toAdd,struct Node* after);  
 void removeThis(struct Node* node);  
 void removePrevious(struct Node* node);  
 void removeNext(struct Node* node);  
 void push(int val);  
 int pop();  
 int pullHead();  
 void pushTail(int value);  
 void pushHead(int value);  
 void freeLinkedList();  
 struct Node  
 {  
      int value;  
      struct Node* next;  
      struct Node* prev;  
 };  
 typedef struct Node Node;  
 Node* head;  
 Node* createNode(int val)  
 {  
      Node* res=malloc(sizeof(Node));  
      res->value=val;  
      res->next=NULL;  
      res->prev=NULL;  
      return res;  
 }  
 void insertBefore(Node* toAdd,Node* behind)  
 {  
      if(behind==head)  
      {  
           toAdd->next=head;  
           head->prev=toAdd;  
           head=toAdd;  
      }  
      else  
      {  
           Node* back=behind->prev;  
           back->next=toAdd;  
           behind->prev=toAdd;  
           toAdd->prev=back;  
           toAdd->next=behind;  
      }  
 }  
 void insertAfter(Node* toAdd,Node* after)  
 {  
      if(after->next!=NULL)  
      {  
           Node* front=after->next;  
           after->next=toAdd;  
           toAdd->prev=after;  
           toAdd->next=front;  
           front->prev=toAdd;       
      }  
      else  
      {  
           after->next=toAdd;  
           toAdd->prev=after;  
      }       
 }  
 void removeThis(Node* node)  
 {  
      if(node==head)  
      {  
           Node* temp=head->next;  
           temp->prev=NULL;  
           head->next=NULL;  
           free(head);  
           head=temp;  
      }       
      else  
      {  
           Node* back=node->prev;  
           Node* front=node->next;  
           back->next=front;  
           front->prev=back;  
           node->next=NULL;  
           node->prev=NULL;  
           free(node);  
      }  
 }  
 void removePrevious(Node* node)  
 {  
      if(node==head)  
      {  
           puts("The head is the first node of the list,no node could be found behind it for removal");  
      }  
      else  
      {  
           Node* back=node->prev;  
           if(back->prev!=NULL)  
           {  
                Node* dback=back->prev;  
                dback->next=node;  
                node->prev=dback;  
                back->prev=NULL;  
                back->next=NULL;  
                free(back);  
           }  
           else  
           {  
                back->next=NULL;  
                node->prev=NULL;  
                head=node;  
                free(back);  
           }       
      }  
 }  
 void removeNext(Node* node)  
 {  
      if(node->next==NULL)  
      {  
           puts("This node is the tail of the list,it is not connected to any other node in the forward direction,removal impossible\n");  
      }  
      else  
      {  
           Node* temp=node->next;  
           Node* front=temp->next;  
           node->next=front;  
           front->prev=node;  
           temp->next=NULL;  
           temp->prev=NULL;  
           free(temp);  
      }  
 }  
 void push(int val)  
 {  
      Node* res=createNode(val);  
      res->value=val;  
      res->next=head;  
      head=res;  
 }  
 int pop()  
 {  
      Node* temp=head;  
      int res=temp->value;  
      head=temp->next;  
      head->prev=NULL;  
      temp->next=NULL;  
      free(temp);  
      return res;  
 }  
 int pullHead()  
 {  
      return pop();  
 }  
 void pushTail(int value)  
 {  
      //problem:find the last node needs traversal  
      Node* res=createNode(value);  
      Node* temp=head;  
      while(temp->next!=NULL)  
      {  
           temp=temp->next;  
      }  
      temp->next=res;  
 }  
 void pushHead(int value)  
 {  
      push(value);  
 }  
 void printAllNodesFrom(Node* node)  
 {  
      while(node->next!=NULL)  
      {  
           printf("%d--",node->value);  
           node=node->next;  
      }  
      printf("%d\n",node->value);  
 }  
 //BUG...  
 void printAllNodesTo(Node* node,int order)  
 {  
      //NON-ZERO:Go to head and print to node:  
      if(order)  
      {  
           Node* temp=node;  
           while(node!=head)  
           {  
                node=node->prev;  
           }  
           while(node->next!=temp)  
           {  
                printf("%d--",node->value);  
                node=node->next;  
           }  
           printf("%d\n",node->value);  
      }  
      //0:REVERSE ORDER  
      else  
      {  
           while(node->prev!=head)  
           {  
                printf("%d--",node->value);  
                node=node->prev;  
           }  
           printf("%d\n",node->prev->value);  
      }  
 }  
 void freeLinkedList()  
 {  
      Node* node=head;  
      Node* temp;  
      while(node!=NULL)  
      {  
           temp=node;  
           node=node->next;  
           temp->next=NULL;  
           temp->prev=NULL;  
           free(temp);  
      }       
 }  
 int main(int argc,char** argv)  
 {  
      head=createNode(1);//1  
      insertAfter(createNode(2),head);//1--2  
      insertBefore(createNode(3),head->next);//1--3--2  
      insertBefore(createNode(4),head);//4--1--3--2  
      printAllNodesFrom(head);  
      removeThis(head->next);//4--3--2  
      removeThis(head);//3--2  
      printAllNodesFrom(head);  
      removePrevious(head);//prints warning  
      removePrevious(head->next);//2  
      printAllNodesFrom(head);  
      push(5);//5--2  
      pushTail(6);//5--2--6  
      printAllNodesFrom(head);  
      removeNext(head);//5--6  
      printAllNodesFrom(head);  
      pop();//6  
      printAllNodesFrom(head);  
      push(7);//7--6  
      Node* n=createNode(8);  
      insertAfter(n,head->next);//7--6--8  
      freeLinkedList();  
      return 0;  
 }  


And while continuing to read the JavaScript Allonge,I came across this memoize function,I took a look at memoization on Wikipedia and luckily found some pseudo code for it that can be used inside JavaScript.The pseudo code specified appends the lookup table as a property of the function being called,I managed to create a version of the function that works for a function that requires a single parameter.Instead of doing what the pseudo-code suggested  I used a closure to use and update the lookup-table.

For multiple parameters we need to create a key,in JavaScript Allonge,the key is a JSON string of the arguments array-like object(which is hated and reviled by the JS community so much so that it is preparing to leave JavaScript in the future).The version of memoize allows you to pass your keymaker function which can be used instead of what I described above.In other blog posts over the web people have used recursion and closures in memoization which I would rather not do.


 var memoize=function(fn,context)  
 {  
   var cache={};  
   return function(param)  
   {  
     if(!cache[param])  
     {  
       cache[param]=fn.call(context,param);  
     }  
     return cache[param];  
   }  
 }  
 console.log(memoize(fibbonaci)(20));  
 console.log(memoize(factorial)(5));  
 function factorial(n)  
 {  
   if(n==0)  
     return 1;  
   else  
     return n*factorial(n-1);    
 }  
 function fibbonaci(n)  
 {  
   if(n==0 || n==1)  
     return 1;    
   else  
   {  
     return fibbonaci(n-1)+fibbonaci(n-2);  
   }  
 }  


I have also started reading the source code of libraries such as http://bit.ly/1d3jrlA which is about 350 lines and is concerned with functional programming in JavaScript which might even serve as a gentle soothing introduction to reading the source code of some of the other open source libraries such as underscore,requirejs and jquery that  I would like to work with/am working with.However I do not like it that the string lambdas used there do not allow me to create closures because closures allow encapsulation and awesome functions such as memoization.

I remember watching a video where Crockford said that the arguments array must only be used in a read-only manner because it could break compatibility with older versions of the Public Enemy#1 where arguments does not inherit from Array.prototype.So,I guess I should be worried about using this function.


 Functional.compose = function () {  
   var fns = Functional.map(Function.toFunction, arguments),  
     arglen = fns.length;  
   return function () {  
     for (var i = arglen; --i >= 0;)  
       arguments = [fns[i].apply(this, arguments)];//should we fiddle with the arguments like this??  
     return arguments[0];  
   }  
 }  


Now,there is this and then there is THIS,that monstrous keyword that breaks code by just changing to the value to the global object or to undefined(since ES5).And thus,I decided to try the arrow functions in the Firefox scratchpad.

 var harmonyFunc=s => s;  
 alert(harmonyFunc(2));  
 var harmonyFunc2=() => 'Welcome to the Matrix,Neo';  
 alert(harmonyFunc2());  
 //These lyrics found themselves on Mozilla Developer Network from a Maroon5 Song  
 var a=["We're up all night 'till the sun",  
     "We're up all night to get some",  
     "We're up all night for good fun",  
     "We're up all night to get lucky"  
    ];  
 //defining an anonymous inner function...  
 var harmonyFunc3=a.map(s=>s.length);  
 alert(JSON.stringify(harmonyFunc3));  
 var PersonOriginal=function()  
 {  
   this.age=0;  
   setInterval(()=>{  
     if(this.age<24)  
     {  
       console.log(age);  
       this.age++;//this refers to person  
     }  
   },1000);  
 }  
 //cannot create constructors using the harmony functional notation  
 //something to remember when you are creating brand new objects...this  
 //is because it does not have a sense of this...evil smiley face  
 var Person=() => {  
   this.age=0;  
   setInterval(()=>{  
     if(this.age<24)  
     {  
       console.log(age);  
       this.age++;//this refers to person  
     }  
   },1000);  
 }  
 var p=new Person();  

Does this allow me to use call and apply and continue passing an object around just for it's context?Will this allow me to do recursion without using named functions which leads me to worry about hoisting.If not,I could use fancy combinator logic that I am a few(much more than a few) light years away from understanding.

 var memoize=(fn,context) =>{  
   var cache={};  
   return param =>{  
    if(!cache[param])  
    {  
     cache[param]=fn.call(context,param);  
    }  
    return cache[param];  
   }    
 };  
 var factorial=n => {  
   if(n==0)  
   {  
     return 1;  
   }  
   else  
   {  
     return n* factorial(n-1);  
   }  
 }  
 alert(memoize(factorial)(6,null));  

This works,so we have recursion without having to resort to named functions(which get hoisted) because named function expressions do not work in IE<=8.The next logical step was to test for
hoisting ,so I moved the alert to the top of the script.It says function not defined,similarly for factorial.

I think passing an object around for it's context is a Java-like move for a language trying to move away from Java.We could instead use a property attached to the object that uniquely represents the property which is even more Java like.It is interesting to notice how Android duplicates this pattern providing each Activity with a Context that is accessible via the this keyword.It then uses the context to call other contexts like another Activity or a shared resource like the Location Service.It is also interesting how you can refer to the enclosing context from a Thread in an Activity or a Service using getBaseContext and the application using getApplicationContext from anywhere.Here,this is a reference to Context object.

 LocationManager lm=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);  
 startActivity(new Intent(this,XYZActi ity.class);  
 getBaseContext();  
 getApplicationContext();  

I also managed to write a function that creates DOM elements using JavaScript this is a badly structured example which does not concern itself with Public Enemy #1,know to the enterprise as The ONE and commonly referred to as Internet Explorer. By writing this function,I think I understand why Backbone use mixins(so I have been told) for creating new Views.If I had a chance to do it all over again,I would pass it an object instead.


 define(function () {  
   function isArray(arg)  
   {  
     return arg && arg instanceof Array;  
   }  
   function isObject(obj)  
   {  
     return obj && obj instanceof Object;  
   }  
   return {  
     createSimpleElement:function(name,value)  
     {  
       var res=document.createElement(''+name);  
       res.innerHTML=value;   
       return res;  
     },  
     createFindableElement:function(name,value,id,classes)  
     {  
       var self=this;   
       var res=self.createSimpleElement(name,value);  
       if(isArray(id))  
       {  
        res.id=''+id[0];  
       }  
       else if(!isObject(res))  
       {  
        res.id=''+id;  
       }      
       if (classes && typeof classes === 'string')  
       {  
         res.className += classes;  
       }   
       else if (isArray(classes))  
       {  
         for (i = 0; i < classes.length; i++)  
         {  
           res.className += ' ' + classes[i];  
         }  
       }  
       return res;  
     },  
     createStyledElement:function(name,value,id,classes,styles)  
     {  
       var self=this;  
       var res=self.createFindableElement(name,value,id,classes);  
       if(isObject(styles))  
       {  
        for (i in styles)  
         {  
           if (styles.hasOwnProperty(i))  
           {  
             res.style[i] = styles[i];  
           }  
         }  
       }  
       return res;  
     },  
     createElement: function (name, value,id,classes, styles, events, addTo)  
     {  
       var i = 0;  
       var self=this;  
       var res=self.createStyledElement(name,value,id,classes,styles,events,addTo);  
       if (events && events instanceof Object)  
       {  
         for (i in events)  
         {  
           if (events.hasOwnProperty(i));  
           {  
             res.addEventListener(i, events[i], false);  
           }  
         }  
       }  
       addTo.appendChild(res);  
       return res;  
     }  
   }  
 });  

I was trying to demonstrate an example of how to use the DOM API to generate new elements while using requirejs without making use of jquery.The design criteria was simple,allow creating an element by it's name and value.Add a class or a set of classes and an id to it which makes it more easy to find and assign styles to from other places.The idea was allow passing styles and events in as objects and currying the function for all the values which I later realized was a bad idea.So,instead of a single function I created a group of functions to handle this.

Thanks for reading guys and I cannot believe I created a multi-lingual programming post(pats self really hard on the back and grimaces in pain).