Sunday 31 May 2015

Printing the truth tables of Binary Operators : AND, OR, NOR, XOR, NAND, NXOR, using simple java code :)

Hello friends,

I want to discuss the program to print the Truth Table of the binary Operators. Binary operator works on two bits and give result in binary. Also do note how I have used an abstract method in an enum that I have defined in my program and also have overridden the same :)


 
 public class TruthTableOfBinaryOperators {  
      public enum Operator {  
           AND {  
                @Override  
                public String getOperatorName() {  
                     return "AND";  
                }  
           },  
           OR {  
                @Override  
                public String getOperatorName() {  
                     return "OR";  
                }  
           },  
           NOR {  
                @Override  
                public String getOperatorName() {  
                     return "NOR";  
                }  
           },  
           XOR {  
                @Override  
                public String getOperatorName() {  
                     return "XOR";  
                }  
           },  
           NXOR {  
                @Override  
                public String getOperatorName() {  
                     return "NXOR";  
                }  
           },  
           NAND {  
                @Override  
                public String getOperatorName() {  
                     return "NAND";  
                }  
           };  
           abstract public String getOperatorName();  
      };  
      public static void printTruthTable(int N, Operator op) {  
           int totalSubSets = (1 << N);  
           for (int i = 0; i < totalSubSets ; i++) {  
                int result = -1;  
                for (int j = N - 1; j >= 0; j--) {  
                     int currentBit;  
                     if ((i & (1 << j)) != 0) {  
                          currentBit = 1;  
                     } else {  
                          currentBit = 0;  
                     }  
                     if (result == -1) {  
                          result = currentBit;  
                     } else {  
                          switch(op){  
                          case AND:  
                               if(result != 0){  
                                    result = currentBit & result;  
                               }  
                               break;  
                          case NAND:  
                               if((currentBit & result)==0){  
                                    result = 0;  
                               }else{  
                                    result = 1;  
                               }  
                               break;  
                          case OR:  
                               if(result != 1){  
                                    result = currentBit | result;  
                               }  
                               break;  
                          case NOR:  
                               if((currentBit | result)==0){  
                                    result = 0;  
                               }else{  
                                    result = 1;  
                               }  
                               break;  
                          case XOR:  
                                    result = currentBit ^ result;  
                               break;  
                          case NXOR:  
                               if((currentBit ^ result) == 0){  
                                    result = 0;  
                               }else{  
                                    result = 1;  
                               }  
                               break;  
                          }  
                     }  
                     System.out.print(currentBit+" ");  
                }  
                if(result != -1){  
                     System.out.println(" "+op.getOperatorName()+" -> "+result);  
                }  
           }  
      }  
      public static void main(String[] args) {  
           printTruthTable(2, Operator.XOR);  
      }  
 }  

Saturday 30 May 2015

XOR : The Exclusive OR



public class XORBasics {
public static void main(String[] args) {
/**
* What is XOR ?

* XOR is an binary operator which when applied on two numbers, it returns 0 in case both the numbers are same


*  0 ^ 0 = 0 (XOR for same bits results in 0)
*  0 ^ 1 = 1 
*  1 ^ 0 = 1
*  1 ^ 1 = 0 (XOR for same bits results in 0)

* Lets have two numbers a=3 and b=4. expressing them in binary and then applying the XOR operation on them below.
*  
*  Number     Binary   Decimal 
*     a                011        3
*     b                100        4
*     c                111        7
*     
*  As per property of XOR a^b is same as b^a
*  Also an interesting property of XOR is 
*  if c = a^b then b = a^c and a = b^c.
*  
*  
*                               
*/
int a = 3;
int b = 4;
int c = a^b;
System.out.println("a is "+a);
System.out.println("b is "+b);
System.out.println("c is "+c);
System.out.println("a^c "+ (a^c));
System.out.println("b^c is "+(b^c));
System.out.println("is a^c equals c^a ? "+((a^c) == (c^a)));
/**
* Swapping two numbers using XOR operator. In this we do not need the third variable.
* if x = 10 and y = 20;
* then performing below 3 steps swaps the numbers
* STEP1. y = x^y;
* STEP2. x = x^y;
* STEP3. y = x^y;

* Lets see how it works
* STEP1. lets take a variable z = x^y. so y is assigned value of z, i.e new value of y is z. 
* STEP2. x = x^(new value of y) = x^z. So x is assigned a new value i.e x^z which from previous example we know would be original value of y.
*   So new value of x is now y
*      STEP3. y = (new value of x)^(new value of y) = y^z. which we know should be original value of x

*/
int x = 10;
int y = 20;
y = x^y;
x = x^y;
y = x^y;
System.out.println("new value of x is "+ x);
System.out.println("new value of y is "+ y);
}
}

Tuesday 26 May 2015

Counting Max Consecutive elements in an array!!

Hello friends,

In this post, I would like to present a problem I encountered where we need to find consecutive occurrence of elements in a 2D matrix of N * N size. If  a cell has same element as contained by itself in the  top, bottom , right or left direct neighbor cell, then these two cells are said to have consecutive  occurrence of same element .
The consecutive same elements form a cluster  (sector).
The problem is to find the number of such clusters of same elements and to find the maximum size of the cluster.

For example
Input
N = 5;

Matrix :
{ 1, 1, 1, 0, 0 },
{ 1, 0, 1, 0, 0 },
{ 1, 0, 1, 0, 1 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 1 }

Solution :

We can see we have three clusters with sizes as 8, 4 and 1.

So we need to output number of clusters followed by a space and then need to output the maximum size;

Output : 3 8



Lets see the code for this problem. I have used a stack for brack-tracing in this problem ( implemented the basic stack using array, although I could have used the java.util.Stack or simply ArrayList which would have reduced few lines of code, but anyways I choose to use basic array based Stack) In the program below I have used 'sector' instead of cluster.


There can be a approach using recursion, but I find understanding the code execution flow better in iterative manner.

public class LargestGridSector {
 /// input starts
 public static int data[][] = 
                                    { { 1, 1, 1, 0, 0 }, 
                                    { 1, 0, 1, 0, 0 }, 
                                    { 1, 0, 1, 0, 1 }, 
                                    { 1, 0, 0, 0, 1 }, 
                                    { 0, 1, 0, 1, 1 } };
 public static int N = 5;
 /// input ends

 public static void main(String[] args) {
  largedtGridSector();
  System.out.println(numOfSectors +" "+maxSectorSize);
 }

 public static class Point {
  int x;
  int y;

  public Point(int x, int y) {
   this.x = x;
   this.y = y;
  }
 }

 public static int largedtGridSector = 0;
 public static final int ONE = 1;
 public static final int ZERO = 0;
 public static final int VISITED = 3;
 public static final int INSTACK = 2;
 public static int numOfSectors = 0;
 public static int maxSectorSize = 0;
 public static int currentSectorSize = 0;
 public static Point[] stack = new Point[N * N];
 public static int stackIndex = -1;

 public static void largedtGridSector() {
  for (int i = 0; i < N; i++) {
   for (int j = 0; j < N; j++) {
    switch (data[i][j]) {
    case ONE:
     int x = i;
     int y = j;
     numOfSectors++;
     currentSectorSize = 0;
     boolean toBreakWhile = false;
     while (true) {
      switch (data[x][y]) {
      case ONE:
       Point p = new Point(x, y);
       push(p);
       data[p.x][p.y] = INSTACK;
       currentSectorSize++;
       if (y < N - 1 && data[x][y + 1] == ONE) {
        y++;
       } else if (y > 0 && data[x][y - 1] == ONE) {
        y--;
       } else if (x < N - 1 && data[x + 1][y] == ONE) {
        x++;
       } else if (x > 0 && data[x - 1][y] == ONE) {
        x--;
       } else if (stackIndex >= 0) {
        Point prePoint = pop();
        data[prePoint.x][prePoint.y] = VISITED;
        if (stackIndex >= 0) {
         x = stack[stackIndex].x;
         y = stack[stackIndex].y;
        }
       }
       break;
      case INSTACK:
       if (y < N - 1 && data[x][y + 1] == ONE) {
        y++;
       } else if (y > 0 && data[x][y - 1] == ONE) {
        y--;
       } else if (x < N - 1 && data[x + 1][y] == ONE) {
        x++;
       } else if (x > 0 && data[x - 1][y] == ONE) {
        x--;
       } else if (stackIndex >= 0) {
        Point prePoint = pop();
        data[prePoint.x][prePoint.y] = VISITED;
        if (stackIndex >= 0) {
         x = stack[stackIndex].x;
         y = stack[stackIndex].y;
        }
       }
       break;
      default:
       toBreakWhile = true;
       break;
      }
      if (stackIndex < 0 || toBreakWhile) {
       break;
      }
     }
     if (currentSectorSize > maxSectorSize) {
      maxSectorSize = currentSectorSize;
     }
     break;
    default:
     continue;
    }
   }
  }
 }

 public static void push(Point p) {
  stackIndex++;
  stack[stackIndex] = p;
 }

 public static Point pop() {
  Point p = stack[stackIndex];
  stack[stackIndex] = null;
  stackIndex--;
  return p;
 }

}

Monday 25 May 2015

Lets try PowerSet!!

Friends lets go little mix and match. Lets try our mind with some algorithms.

In Mathematics we all would have studied Sets, Lets try to print the PowerSet for a given set S.

Now what is a Power set, lets try to understand with an example.

If S is the set {a, b, c}, then the subsets of S are:
{} 
{a}
{b}
{c}
{a, b}
{a, c}
{b, c}
{a, b, c}
and hence the power set of S is {{}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {a, b, c}}
For more on Sets, you can visit some sites on Maths, but for the algorithm of PowerSet we are going to discuss above information is enough.

Lets try to represent the power set by below process. 

    a    b    c        decimal number        Sub Set
    0    0    0                  1                        {}
    0    0    1                  2                        {c}
    0    1    0                  3                        {b}
    0    1    1                  4                        {b,c}
    1    0    0                  5                        {a}
    1    0    1                  6                        {a,c}
    1    1    0                  7                        {a,b}
    1    1    1                  8                        {a,b,c}

                                                  POWER SET :  { {}, {c}, {b}, {b,c}, {a}, {a,c}, {a,b}, {a,b,c} }





 public class PowerSet {

      public static char[] input = {'A','B','C'};

      public static void main(String[] args) {
           printPowerSet();
      }

      public static void printPowerSet(){
           int N = input.length;
           int twoPowN = 1<<N;
           for(int i = 0 ; i < twoPowN ; i++){
                System.out.print("{");
                for(int j = 0; j < N; j++){

                     // i goes from 000, 001, 010, 011, 100, 101, 110, 111 (111 is twoPowN-1)  
                     // j goes from 0,1,2 : 000,001,010  
                     // Quest. How to know if jth bit of i is set ? : Ans. Perform AND of i with 1<<j   
                     // 001<<0 == 001  
                     // 001<<1 == 010  
                     // 001<<2 == 100  
                     boolean isJthBitOfISet = (i & (1<<j)) != 0; // this will be 0,2,4
                     if(isJthBitOfISet){
                          // print the jth element  
                          System.out.print(" " +input[j]);
                     }
                }
                System.out.println(" }");
           }
      }
 }


Output is
{ }
{ A }
{ B }
{ A B }
{ C }
{ A C }
{ B C }
{ A B C }

Try coding this on your own and you will get the concept!!. Follow this place for more stuff...

Happy coding!!



Saturday 23 May 2015

time out please!!

Hey friends, before we proceed ahead, I want to have little discussion with you guys.

Some of you may have landed up here searching for quick question and answers to prepare for their job interviews. 
If you are one of those 'some of the people', then you are part of  my correct intended audience.

OK, now let me put some bits and pieces for you, don't worry I will put them in place as we proceed further and together they will make sense. 

Lets see what may be your wants from your new job. You would want to earn more, you would  want to work in a better environment and would likely want good quality work,

Friends Lets talk about Princely treatment, perks, good environment and money.
'There are no free Lunches'. Money making is not an easy job. You may feel someone making money easily but believe me its not as easy as it looks. Big organisations are not for charity, they want to get returns when they put investment in you.

Now lets talk about good quality work, Until unless you like coding you will always feel yourself caught in a 'Wrong Job', working as a software professional. No piece of software would seam to you as a good work until you have 'coding' as one of your HOBBY.

My dear pals, you need to SPEND TIME DOING CODING. There are no shortcuts to success, Mugging up the definitions, UML notations, algorithms, design patterns, won't take you much distance. 

If you feel, suffocated while coding, please rethink why and for what are you preparing for. You need to give a serious rethink to your career options.

But if you enjoy coding, if you search good practices in coding and are eager to apply in your work then friends , WELCOME, this is your world. Cheers!! and now lets proceed ahead.

All the best




Sunday 10 May 2015

C2SLS !! Don't worry it will make sense :)


Hello friends,

Be curios , to answer your curiosity, search the world around you for answers , and when you get results for your searching, study & learn and then finally SHARE !!

That is about C2SLS.

Now you are here means you have climbed the first two stairs. Your curiosity made you search and you landed in here. Welcome friend, lets learn the stuff together. I will try to keep it simple and also will try not to let the fun element go away.


All the best. Do follow for more stuff!!


Thanks & Regards
Krishna