Tuesday, 31 March 2015

Paint Fill

//paint fill function : given a point , a 2d array , and a new color , fill the image (2d-array here) using new color

public enum Color
{  
    Black , White , Red , Yellow , Green
}

public static void boolean PaintFill(Color[][] screen , int x , int  y  ,  Color nColor)
{
    /*
    *   Here x is column index and y is the row index , as happens in screen orientations
    */
   
    if(screen[y][x] == nColor) return false ;
    return PaintFill(screen , int x , int y , screen[y][x] , nColor);
}


public static boolean PaintFill (Color[][] screen , int x  , int y , Color oColor , Color nColor)
{
    //check if the index is out of bounds of the screen
    if ( y < 0  || y > screen.length   || x < 0 || x > screen[0].length)
        return false ;
   
    //if the present point pixel is of old color , recurse coloring the neighbors
    if (screen[y][x] == oColor)
    {
        PaintFill(screen , x-1 , y, oColor , nColor ) ; //left
        PaintFill(screen , x+1 , y, oColor , nColor ) ; //right
        PaintFill(screen , x , y-1, oColor , nColor ) ; //top
        PaintFill(screen , x , y+1, oColor , nColor ) ; //bottom
    }
   
    return true ;
}

Operators C tid bits


1 :
    precedence of comparison operators (<=, >= and ==) is higher than assignment operator =. The result of a comparison operator is either 0 or 1 based on the comparison result

    2 :
     int i = 1, 2, 3;
     printf("%d", i);
     Compile time error : Comma acts as a separator here. The compiler creates an integer variable and initializes it with 1. The compiler fails to create integer variable 2 because 2 is not a valid identifier.
   
     3:
     int i = (1, 2, 3);
     printf("%d", i);
     Output : 3
     The bracket operator has higher precedence than assignment operator. The expression within bracket operator is evaluated from left to right but it is always the result of the last expression which gets assigned.
   
     4:
      int i;
    i = 1, 2, 3;
    printf("%d", i);  Output : 1
    Comma acts as an operator. The assignment operator has higher precedence than comma operator. So, the expression is considered as (i = 1), 2, 3 and 1 gets assigned to variable i.
  
    5 The control in the logical OR goes to the second expression only if the first expression results in FALSE
    6: . An expression doesn't get evaluated inside sizeof operator.
  
    7 :
        This is an another way to convert an alphabet to upper case by resetting its bit positioned at value 32 i.e. 5th bit from the LSB(assuming LSB bit at position 0).
      
        eg : a &= ~32 ; Outputs A  ;
    8:
        We can swap two variables without any extra variable using bitwise XOR operator '^'. Let X and Y be two variables to be swapped. Following steps swap X and Y.

          X = X ^ Y;
          Y = X ^ Y;
          X = X ^ Y ;
           
   

Monday, 30 March 2015

Linked List in C++

#include <iostream>
#include<conio.h>

using namespace std;

class Node {
private :
    int data;
    Node *next;
public :
    void setData( int data ){
        this->data = data;
   }
    void setNext(Node *node) {
        this->next = node;
    }
        Node* getNext(){
        return next;
    }
    int getData() { return data; }

};



class LinkedList
{
 private:
     Node *head;
     static int length ;

public :
   
    LinkedList(){ head = NULL; }
    void insertAtHead(int  );
    void deleteFromHead( );
    void displayList();
    int getLength(){ return length ; }
    bool isEmpty(){ return  (length == 0);  }

   
};
int LinkedList::length;

void LinkedList::insertAtHead(int data){
    Node *node = new Node();
    node->setData(data);

    Node *temp = head;
    head = node;
    node->setNext(temp);
    ++length;

}

void LinkedList::deleteFromHead(){
    if (isEmpty() )
    {
        cout << "List is empty  \n";
    }
    else
    {
        Node *temp = head;
        head = head->getNext();
        delete temp;
        --length;
    }

}

void LinkedList::displayList(){
    Node *temp = head;
   
    if ( isEmpty() ){
        cout << "Empty list";
    }
    else {
        while (temp != NULL)
        {

            int data = temp->getData();
            cout << data << " \n";
            temp = temp->getNext();
        }
    }

}


int main()
{
    LinkedList list;

    list.insertAtHead(1);
    list.insertAtHead(2);
    list.insertAtHead(3);
    list.insertAtHead(4);
    list.insertAtHead(5);

    list.displayList();

    list.deleteFromHead();
    list.deleteFromHead();
    list.deleteFromHead();
    list.deleteFromHead();
    list.deleteFromHead();

    list.displayList();

    getchar();
    return 0;

   



}

Tid-Bits C I/O



1 :
     char array[100];
    printf("%d" , scanf("%s" , arr));
    //input  : Jimmmy
    prints 1  as scan returns number of inputs successfully read
 2: 
    printf(" \"JIMMY %% N  %% JOLLY\"");
   
    output : "JIMMY % N % JOLLY"
   
    (\\\) backslash are used for escaping double quotes
   
 3: prototype of printf() in C :
              int printf(const char *format, ...);
 4:

    The stdout stream is buffered, so will only display what’s in the buffer after it reaches a newline (or when it’s told to)
    eg :
    printf(“\%\n”); prints : %
   
   
  5 :
    Use of backspace \b  and return  \r escape characters is terminal dependent :
        http://stackoverflow.com/questions/17236242/usage-of-b-and-r-in-c
       
   6:
        int main()
            {
               printf(1 + "Jjim");
               return 0;
            }
           
            prints : jim
          
           printf()  prototype as int printf( const char *format , ... ) ; The compiler adds 1 to base address of "Jjim" and sends "jim" as an arguemnts to
           printf() function defined in stdio.h header file .
    7:
            int main()
                {
                    printf("%c ", 5["jimmyjolly"]);
                    return 0;
                }
               
              prints : 'j'
       
          Compiler assumes   5["jimmyjolly"] as *(5 + "jimmyjolly") Adding 5 to base address of the string increments the pointer to point 'j'
                             Applying value-of opertaor gives 'j' as final result
            Same logic for  "jimmyjolly"[5] where  output is j
     
     
      8 :
             gets() can read a string with spaces but a normal scanf() with %s can not.
             gets() doesn't do any array bound testing and should not be used
             use fgets() instead :
                char *fgets(char *s, int n, FILE *stream);
                fgets read at most n-1 characters into the array s, stopping if a newline is encountered, the newline is included in the array, which is terminated by ‘\0'.
                fgets returns s, or NULL if end of file or error occurs.
     9 :
            #include <stdio.h>

            int main()
            {
                char str[50] = {0};
                scanf("%4s", str);
                printf(str);
                getchar();
                return 0;
            }
           
            input :  jimmy
            ouput : jimmy
           statment  scanf("%4s" , str ) ;  Read maximum 4 characters from console where str is a char array variable eg. char str[50];
          
          
        10 :
           
            printf(“%.*s”, n, s); in this statement value of pointer will move till nth character of s , printing n characters

            .* means The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
        11 :
             printf function returns the number of characters successfully printed on the screen.
         12 :
            The return type of getchar() is int to accommodate EOF which indicates failure
          13 :
             for a CPU with memory mapped I/O ,  I/O protection is ensured by operating system routine (s)