Complete Quinne McClusky Algorithm

Sunday, 7 October 2012
Sorry for not posting since a long time..got busy in some work .. but coming back with this big one which you all will enjoy ..

Lucky you people...we got this as our assignment this semester so we had to write this completely .. exciting though the only problem was for reduction of dont care terms to give multiple answers .
        I would not say this is the efficient but this gives correct answers and is the shortest from all others my batch has written..we had to write it in C but other languages can impliment it shorter.Heres the code..

##########################################################################

#include<stdio.h>
#include<stdlib.h>
#define MAX_VARS 4 /*variables in the product term*/
#define TRUE 1
#define FALSE 0
#define MAXTERMS 16 /*since maximum number of variables for an n variable is pow(2,n)*/
struct term
{
    unsigned t:MAX_VARS;
    unsigned f:MAX_VARS;
    int compterms[MAXTERMS];
    int nn;
};
typedef struct term TERM;
//definaition of all functions here
//==========================================================================================
void init(TERM *tr,int n);
int combinable(TERM tt1,TERM tt2);
int onebit(int num);
void combine(TERM m1,TERM m2,TERM *m3);
int EqualTerms(TERM tt1,TERM tt2);
void printTerm(TERM tt1);
int inDontCares(int n);
void makezeros(int column,int final_index,int table[][MAXTERMS]);
void sort_both(int row_ones[],int pos[],int count);
void print_solutions(int ii,int table1[][MAXTERMS],int final_index,TERM essential1[],int ess);
void zeroall(int row,int table[][MAXTERMS]);
//==========================================================================================
//global variables
TERM terms[MAX_VARS+1][MAXTERMS];//calculate the terms at eacch level
int dont_care[MAX_VARS+1][MAXTERMS];//sees if it is completely made up of dont care terms
int numTerms[MAX_VARS+1];//the number of terms at each level
TERM prime_implicants[MAXTERMS];//stores the prime implicants
//++=============================================
int main()
{
    printf("********************************************************************\n");
    printf("                QUINNE MCLUSKY FOR %d VARIABLES                       \n",MAX_VARS);
    printf("********************************************************************\n\n");
    static int table[MAXTERMS][MAXTERMS];//the table
    int covered[MAX_VARS+1][MAXTERMS];//checks to see if it was covered in the next level
    int m;
    int j,k,p;
    TERM tempTerm;
    int found;
    /*Initialize number of terms at each level m*/
    for(m=0;m<MAX_VARS+1;m++)
    numTerms[m]=0;
    /*read input minterms from user*/
    int in;
    printf("Enter the number of normal minterms to be entered ::");
    scanf("%d",&in);
    if(in>0)
    printf("Enter the normal terms::\n");
    int ind=0,trm;
    numTerms[0]=in;
    for(ind=0;ind<in;ind++)
    {
        scanf("%d",&trm);
        init(&terms[0][ind],trm);
        covered[0][ind]=FALSE;
        dont_care[0][ind]=FALSE;
    }
    printf("Enter the number of dont care terms::");
    int dc;
    scanf("%d",&dc);
    if(dc>0)
    printf("Enter the dont care terms ::\n");
    numTerms[0]+=dc;
    int counter;
    for(counter=0;counter<dc;counter++)
    {
        scanf("%d",&trm);
        init(&terms[0][ind+counter],trm);
        covered[0][ind+counter]=FALSE;
        dont_care[0][ind+counter]=TRUE;
    }
    /*entire input read
    now generating the prime implicants*/
    for(m=0;m<MAX_VARS;m++)
    for(j=0;j<numTerms[m];j++)
    for(k=j+1;k<numTerms[m];k++)
    {
        int both_dontcare=FALSE;
        if(combinable(terms[m][j],terms[m][k]))
        {
            covered[m][j]=TRUE;
            covered[m][k]=TRUE;
            if((dont_care[m][j]==TRUE)&&(dont_care[m][k]==TRUE))
            both_dontcare=TRUE;
            combine(terms[m][j],terms[m][k],&tempTerm);
            found=FALSE;
            for(p=0;p<numTerms[m+1];p++)
            if (EqualTerms(terms[m+1][p],tempTerm))
            found=TRUE;
            if(!found)
            {
                numTerms[m+1]=numTerms[m+1]+1;
                terms[m+1][numTerms[m+1]-1]=tempTerm;
                covered[m+1][numTerms[m+1]-1]=FALSE;
                if(both_dontcare)
                dont_care[m+1][numTerms[m+1]-1]=TRUE;
                else
                dont_care[m+1][numTerms[m+1]-1]=FALSE;
            }
        }
    }
    /*prime implicants including the dont care generated*/
    //creating the minterm table
    /*******************get the number of nonrepeating final prime implicants*****************/
    int final_index=0,ii=0;
    for(m=0;m<MAX_VARS;m++)
    for(j=0;j<numTerms[m];j++)
    {
        if((!covered[m][j])&&(!dont_care[m][j]))
        {
            int flag=1;
            for(ii=0;ii<final_index;ii++)
            {
                if(EqualTerms(terms[m][j],prime_implicants[ii]))
                flag=0;
            }
            if(flag)
            {
                prime_implicants[final_index]=terms[m][j];
                final_index++;
            }
        }
    }
    //and finally the table
    /*setting the table values according to the prime implicants*/
    for(ii=0;ii<final_index;ii++)
    {
        for(j=0;j<prime_implicants[ii].nn;j++)
        table[ii][prime_implicants[ii].compterms[j]]=1;
    }
    for(ii=0;ii<MAXTERMS;ii++)
    {
        if(inDontCares(ii))
        for(j=0;j<final_index;j++)
        table[j][ii]=0;
    } 
    TERM essential[MAXTERMS];
    int ess=0;
    //get the essential prime implicants
    while(TRUE)
    {
               int flag=1;
               for(ii=0;ii<MAXTERMS;ii++)
               {
                    int count=0;
                    int pos=0;
                    for(j=0;j<final_index;j++)
                    if(table[j][ii]==1)
                    {count++;pos=j;}
                    if(count==1)
                    {
                                //this is an essential p implicant
                                essential[ess]=prime_implicants[pos];
                                ess++;
                                table[j][ii]=0;
                                int c;//remove all other  ones
                                for(c=0;c<MAXTERMS;c++)
                                if(table[pos][c]==1)
                                makezeros(c,final_index,table);//set the col to zero
                                flag=0;
                    }
               }
               if(flag)//no more count=1 i.e no more ess prime im 
               break;
    }
    //remove those rows which are subsets of other rows
    for(ii=0;ii<final_index;ii++)
    {
    int jj;
    for(jj=ii+1;jj<final_index;jj++)
    {
        if(subset(ii,jj,table))
        zeroall(jj,table);
            else if(subset(jj,ii,table))
                 zeroall(ii,table);
        }
    }
    printf("\n\nThe answer is\\are ::\n");
    /*printf("---------------------------------------------------------\n");
    for(ii=0;ii<final_index;ii++)
    {
     for(j=0;j<MAXTERMS;j++)
     printf("%d ",table[ii][j]);
     printf("\n");
    }
    printf("---------------------------------------------------------\n");*/
    print_solutions(0,table,final_index,essential,ess);
}

void print_solutions(int ii,int table1[][MAXTERMS],int final_index,TERM essential1[],int ess)
{
     //base case
      int i,j;
     if(ii==MAXTERMS)
     {
                        //print the ans
                        int i;
                        for(i=0;i<ess;i++)
                        {
                                          printTerm(essential1[i]);
                                          if(i<ess-1)
                                          printf("+");
                        }
                        printf("\n");
     }
     else
     {
         TERM essential[MAXTERMS];
         int ess2=ess;
         int pos[MAXTERMS];
         int row_ones[MAXTERMS];
         int index=0;
         int count=0;
         int table[MAXTERMS][MAXTERMS];
         //remove those rows which are subsets of other rows
         for(i=0;i<final_index;i++)
     for(j=i+1;j<final_index;j++)
     {
            if(subset(i,j,table1))
            zeroall(j,table1);
                else if(subset(j,i,table1))
                     zeroall(i,table1);
         }
         //done
         for(i=0;i<MAXTERMS;i++)
         for(j=0;j<MAXTERMS;j++)
         table[i][j]=table1[i][j];
         //copied a new table
         for(i=0;i<MAXTERMS;i++)
         essential[i]=essential1[i];
         //copied essentials
         for(j=0;j<final_index;j++)
         if(table[j][ii]==1)
         {
               pos[count]=j;
               row_ones[count]=onesInRow(j,table);
               count++;
         }
         if(count==0)//col has no ones
         print_solutions(ii+1,table,final_index,essential,ess);
         else
         {
             int t_max=row_ones[0];
             int unq=0;
             while(row_ones[unq]==t_max)
             {
                                      int row=pos[unq];
                                      //reinitialixe the table
                                      for(i=0;i<MAXTERMS;i++)
                                      for(j=0;j<MAXTERMS;j++)
                                      table[i][j]=table1[i][j];
                                      //reinitialize essentials
                                      for(i=0;i<MAXTERMS;i++)
                                      essential[i]=essential1[i];
                                      ess2=ess;
                                      //make all ones in this row zero
                                      int c;
                                      for(c=0;c<MAXTERMS;c++)
                                      if(table[row][c]==1)
                                      makezeros(c,final_index,table);
                                      //add to prime implicants
                                      essential[ess2++]=prime_implicants[row];
                                      //now send it with increased index
                                      print_solutions(ii+1,table,final_index,essential,ess2);
                                      unq++;
             }
         }
     }
}

void zeroall(int row,int table[][MAXTERMS])
{
    int i;
    for(i=0;i<MAXTERMS;i++)
    table[row][i]=0;
}

int subset(int row1,int row2,int table[][MAXTERMS])
{
    int i,count=1;
    int equal=1;
    for(i=0;i<MAXTERMS;i++)
    if(table[row1][i]!=table[row2][i])
    if(table[row2][i]!=0)
    count=0;
    for(i=0;i<MAXTERMS;i++)
    if(table[row1][i]!=table[row2][i])
    equal=0;
    if(equal)
    count=0;
    return count;
}

void sort_both(int row_ones[],int pos[],int count)
{
     int i,j;
     for(i=0;i<count;i++)
     {
         int temp=row_ones[i];
         int p=i;
         for(j=i+1;j<count;j++)
         {
             if(temp<row_ones[j])
             {temp=row_ones[j];
             p=j;
             }
         }//we got the max now swap
         temp=row_ones[i];
         row_ones[i]=row_ones[p];
         row_ones[p]=temp;
         temp=pos[i];
         pos[i]=pos[p];
         pos[p]=temp;
     }
}

int onesInRow(int row,int table[][MAXTERMS])//will help to find the dominated row
{
     int i,count=0;
     for(i=0;i<MAXTERMS;i++)
     if(table[row][i]==1)
     count++;
     return count;
}  

void makezeros(int column,int final_index,int table[][MAXTERMS])
{
    int i;
    for(i=0;i<final_index;i++)
    table[i][column]=0;
}

int inDontCares(int n)
{
    int i,flag=0;
    for(i=0;i<numTerms[0];i++)
    if((dont_care[0][i]==TRUE)&&(terms[0][i].t==n))
    flag=1;
    if(flag)
    return TRUE;
    else
    return FALSE;
}

int combinable(TERM tt1,TERM tt2)
{
    if(((tt1.t^tt2.t)==(tt1.f^tt2.f))&& onebit(tt1.t^tt2.t))
    return TRUE;
    else
    return FALSE;
}

int onebit(int num)
{
    int ones=0,i;
    for(i=0;i<MAX_VARS;i++)
    {

        if(num&1)
        ones++;
        num=num>>1;
    }
    if(ones==1)
    return 1;
    else
    return 0;
}

void combine(TERM m1,TERM m2,TERM *m3)
{
    m3->t=m1.t & m2.t;
    m3->f=m1.f & m2.f;
    m3->nn=m1.nn+m2.nn;
    int i=0,ind=0;
    for(i=0;i<m1.nn;i++)
    {
                        m3->compterms[ind]=m1.compterms[i];
                        ind++;
    }
    for(i=0;i<m2.nn;i++)
    {
                        m3->compterms[ind]=m2.compterms[i];
                        ind++;
    }                    
}

int EqualTerms(TERM tt1,TERM tt2)
{
    return ((tt1.t==tt2.t)&&(tt1.f==tt2.f));
}

void init(TERM *tr,int n)
{
    tr->t=n;
    tr->f=~n;
    tr->compterms[0]=n;
    tr->nn=1;
}

void printTerm(TERM tt1)
{
    int i;
    char ch=(char)(64+MAX_VARS);
    while((tt1.t>0)||(tt1.f>0))
    {
        int bit1=tt1.t&1;
        int bit2=tt1.f&1;
        if((bit1!=bit2)&&(bit1==0))
        printf("%c'",ch);
        if((bit1!=bit2)&&(bit1==1))
        printf("%c",ch);
        ch--;
        tt1.t=tt1.t>>1;
        tt1.f=tt1.f>>1;
    }
    //printf("+");
}
#########################################################################

Works for not just 4 variables ..by changing the define terms and MAXTERMS you can turn this into n variable K-Map minimization .. Thanks

BASIC IMPLIMENTATION OF LINKED LIST IN JAVA

Friday, 24 August 2012
import java.io.*;
class Node
{
    int data;
    Node next;
    public Node(int d)
    {
        next=null;
        data=d;
    }
    public Node(int d,Node n)
    {
        next=n;
        data=d;
    }
    public void set_data(int d)
    {
        data=d;
    }
    public int get_data()
    {
        return data;
    }
    public void set_next(Node d)
    {
        next=d;
    }
    public Node get_next()
    {
        return next;
    }
}

//implimenting linked list class
class Linkedlist
{
    Node head;
    public Linkedlist()
    {
    head=null;
    }
    public void add(int pos,Node n)
    {
    //pos is the position
    //0 is at the beginning
    if(pos==0)
    {
        if(head==null)
        head=n;
        else
        {
        Node temp=new Node(n.get_data(),head);
        head=temp;
        }
    }
    else
    {
        Node temp=head;
        int count=1;
        int flagfound=0;
        while(temp.get_next()!=null)
        {
            if(count==pos)
            {
                flagfound=1;
                break;
            }
            count++;
            temp=temp.get_next();
        }
        if(flagfound==0)
        {
            System.out.println("problem");
        }
        else
        {
            Node temp1=temp.get_next();
            temp.set_next(n);
            n.set_next(temp1);
        }
    }
    }
    //finished add method
    public void del(int d)
    {
        Node temp=head;
        //check if list is empty
        if(head==null)
        {
            System.out.println("List is empty");
            return;
        }
        //if first node
        if(temp.get_data()==d)
        {
        head=head.get_next();
        return;
        }
        //else if not the first node
        int flag=0;
        while(temp.get_next()!=null)
        {
            if(temp.get_next().get_data()==d)
            {
                flag=1;
                break;   
            }
            else
            {
                temp=temp.get_next();
            }
        }
        if(flag==1)
        {
            Node temp2=temp.get_next().get_next();
            temp.set_next(temp2);
        }
        else
        System.out.println("not found");
    }
    //finished del method

    public void search(int d)
    {
        Node temp=head;
        if(head==null)
        {
            System.out.println("List is empty");
            return;
        }
        //if first node
        int count=1;
        if(head.get_data()==d)
        {
            System.out.println("Node found. Node number= "+count);
            return;
        }
        int flag=0;
        while(temp.get_next()!=null)
        {
            temp=temp.get_next();   
            count++;
            if(temp.get_data()==d)
            {
                flag=1;
                System.out.println("Node found. Node number= "+count);
            }
        }
        if(flag==0)
        {
        System.out.println("Not found in list");
        }
       
    }
    //writing update method
   
    public void update(int olddata,int newdata)
    {
        Node temp=head;
                if(head==null)
                {
                        System.out.println("List is empty");
                        return;
                }
                //if first node
                int count=1;
                if(head.get_data()==olddata)
                {
                        System.out.println("Node found. Node number= "+count);
            head.set_data(newdata);
                        return;
                }
                int flag=0;
                while(temp.get_next()!=null)
               {
                        temp=temp.get_next();
                        count++;
                        if(temp.get_data()==olddata)
                        {
                                flag=1;
                temp.set_data(newdata);
                                System.out.println("Node found. Node number= "+count);
                        }
                }
        if(flag==0)
        System.out.println("node not found");
    }
   
    //writing display method
    public void display()
    {
        //if empty
        if(head==null)
        System.out.println("empty list");   
        else
        {
            Node temp=head;
            System.out.println("Printing the list:");
            System.out.print(head.get_data()+", ");
            while(temp.get_next()!=null)
            {
                temp=temp.get_next();
                System.out.print(temp.get_data()+", ");
            }
        }
    }
}

class check
{
    public static void main(String[] args)throws IOException
    {
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        //create a linkedlist
        Linkedlist ll=new Linkedlist();
        while(true)
        {
        System.out.println("\nWelcome to world of linked lists.Choose an option :");
        System.out.println("1. add(data,pos);");
        System.out.println("2. delete(int d)");
        System.out.println("3. search(int d);");
        System.out.println("4. update(int old,int new)");
        System.out.println("5. display");
        System.out.println("6. exit");
        int n1,n2;
        int ch=Integer.parseInt(br.readLine());
        switch(ch)
        {
        case 1:System.out.println("Enter the data and then pos");
            n1=Integer.parseInt(br.readLine());
            n2=Integer.parseInt(br.readLine());
            Node nn=new Node(n1);
            ll.add(n2,nn);
            break;
        case 2:System.out.println("Enter data");
            n1=Integer.parseInt(br.readLine());
            ll.del(n1);
            break;
        case 3:System.out.println("Enter data");
             n1=Integer.parseInt(br.readLine());
            ll.search(n1);
            break;
        case 4:System.out.println("Enter old data and then new data");
             n1=Integer.parseInt(br.readLine());
             n2=Integer.parseInt(br.readLine());
            ll.update(n1,n2);
            break;
        case 5:ll.display();
            break;
        case 6:System.exit(500);
        default: System.out.println("wrong option try again");
        }
        }
    }
}   

Easter Eggs In Python

Wednesday, 20 June 2012
This is just for fum:

try these in IDLE and notice whats hidden in python-------
1. import this
2. import __hello__
3. import antigravity
4. from __future__ import braces


Radix Sort In Python

Sunday, 17 June 2012
def radix_sort(array,k):
    """k is the max no. of digits in the number in array"""
    num=10
    max_num=10**k
    while num!=max_num:
        def key_arr(x):
            return x%num
        array.sort(key=key_arr)
        num=num*10
    return array

#############################################
array=list(map(int,input().split()))
print(array)
#for a maximum of 4 digit number
array=radix_sort(array,4)
print(array)
#############################################

Traversal in Binary Trees II

Tuesday, 12 June 2012
,
Function to print the postorder given the preorder and inorder:

void postorder( int preorder[], int prestart, int inorder[], int inostart, int length)
{
  if(length==0) return; //terminating condition
  int i;
  for(i=inostart; i<inostart+length; i++)
    if(preorder[prestart]==inorder[i])//break when found root in inorder array
      break;
  postorder(preorder, prestart+1, inorder, inostart, i-inostart);
  postorder(preorder, prestart+i-inostart+1, inorder, i+1, length-i+inostart-1);
  printf("%d ",preorder[prestart]);
}

Function to print the preorder given the postorder and inorder:

void preorder( int postorder[],int poststart,int inorder[],int inostart,int length)
{
  //printf("length=%d\n",length);
  if(length==0) return;//terminating condition
  int i;
  for(i=inostart;i<inostart+length;i++)
    if(postorder[poststart]==inorder[i])//break when found root in inorder array
        break;
  printf("%d ",postorder[poststart]);
  preorder(postorder,i-1,inorder,inostart,i-inostart);
  preorder(postorder,poststart-1,inorder,i+1,length-i+inostart-1);
}


Traversal in Binary trees...

Friday, 6 April 2012
,
Preorder traversal:

preorder(v)
if(v==NULL) then return
else visit(v)//generic computation
preorder(v.leftchild())
preorder(v.rightchild())

postorder(v)
if(v==NULL) then return
else postorder(v.leftchild())
postorder(v.rightchild())
visit(v)//generic computation

Use of post order traversal:
->computing arithmetic expression

Inorder traversal:When the node is visited between the left
and the right subtree(only in binary tree)

inOrder(v):
if(v==NULL)then return
else inOrder(v.leftChild())
visit(v)
inOrder(v.rightChild())

Another way is the Euler Tour traversal:

->generic traversal of the binary tree.
->Each case is a special case of this tree
->Each internal node is visited three times

->Given the preorder and the inorder traversal of a binary tree
we can find out the actual tree recursively.
->Similarly we can find the tree from post order and inorder
traversal mentioned.
->But a postorder and a preorder traversal is insufficient as
there can be two trees having the same preorder and post order
traversal
->however in case of binary tree we can make the tree given the preorder and the post order traversal


Next entries will be:
1. Program to print the tree given:
->postorder and inorder traversal
->preorder and inorder traversal
->postorder and preorder traversal in binary tree
2. To compute the number of possible trees given a particular
order of binary tree

Recursive Solution To The 8 queen Problem

Tuesday, 3 April 2012
#include
#include
static int board[8][8];
static int arrpos[8][2];
int count=0;
int flag=0;
int check(int row,int column)
{
int i;
for(i=0;i<8;i++) { if((board[row][i]==1)&&(i!=column)) return 0; if((board[i][column]==1)&&(i!=row)) return 0; } int copyr=row-1,copyc=column+1; while((copyr>=0)&&(copyc>=0)&&(copyr<=7)&&(copyc<=7)) { if((board[copyr][copyc]==1)) return 0; copyr=copyr-1; copyc=copyc+1; } copyr=row+1,copyc=column+1; while((copyr>=0)&&(copyc>=0)&&(copyr<=7)&&(copyc<=7)) { if((board[copyr][copyc]==1)) return 0; copyr=copyr+1; copyc=copyc+1; } copyr=row-1,copyc=column-1; while((copyr>=0)&&(copyc>=0)&&(copyr<=7)&&(copyc<=7)) { if((board[copyr][copyc]==1)) return 0; copyr=copyr-1; copyc=copyc-1; } copyr=row+1,copyc=column-1; while((copyr>=0)&&(copyc>=0)&&(copyr<=7)&&(copyc<=7)) { if((board[copyr][copyc]==1)) return 0; copyr=copyr+1; copyc=copyc-1; } return 1; } void printarray() { count++; printf("solution %d:",count); int i;//printing the answer for(i=0;i<8;i++) { printf("(%d,%d)",arrpos[i][0],arrpos[i][1]); } printf("\n"); //char c; //scanf("%c",&c); } void getpos(int row,int column,int i) { if(i==8) { printarray();//print answer int lr=arrpos[7][0]; int lc=arrpos[7][1]; board[lr][lc]=0; if (board[0][7]==1) { flag++; if(flag==4) exit(1); }//end program getpos(lr,lc+1,i-1);//start next } if((row<0)||(row>7)||(column>7)||(column<0))
{
int m=i-1;
board[row-1][arrpos[m][1]]=0;
getpos(row-1,arrpos[m][1]+1,i-1);//backtrack previous
}
int mm=check(row,column);
if(mm)
{
arrpos[i][0]=row;
arrpos[i][1]=column;
board[row][column]=1;
getpos(row+1,0,i+1);
//get next row
}
else if(column<7)
getpos(row,column+1,i);//get next place
else
{
int m=i-1;
board[row-1][arrpos[m][1]]=0;
getpos(row-1,arrpos[m][1]+1,i-1);//backtrack previous
}
}


int main()
{
printf("Taking the chessboard as 8x8 from (0,0) to (7,7) as co-ordinates\nSolutions are:\n");
getpos(0,0,0);
return 0;
}
Copyright @ 2013 code-craft. Designed by Templateism | MyBloggerLab