Depth First Search in C and Python

Monday, 15 October 2012
#include<stdio.h>
#include<assert.h>
#include<conio.h>
/* maxVertices represents maximum number of vertices that can be present in the graph. */
/*graph is undirected and not weighted*/
#define maxVertices   100
void Dfs(int graph[][maxVertices],int *size,int presentVertex,int *visited)
{
     printf("Now visiting vertex %d\n",presentVertex);
     visited[presentVertex]=1;
     /* Iterate through all the vertices connected to the presentVertex and perform dfs on those
           vertices if they are not visited before */
     int iter;
     for(iter=0;iter<size[presentVertex];iter++)
     {
             if(!visited[graph[presentVertex][iter]])
             Dfs(graph,size,graph[presentVertex][iter],visited);
     }
     return;
}
/* Input Format: Graph is directed and unweighted. First two integers must be number of vertces and edges 
   which must be followed by pairs of vertices which has an edge between them. */
int main()
{
        int graph[maxVertices][maxVertices],size[maxVertices]={0},visited[maxVertices]={0};
        int vertices,edges,iter;
        /* vertices represent number of vertices and edges represent number of edges in the graph. */
        scanf("%d%d",&vertices,&edges);
        int vertex1,vertex2;
        for(iter=0;iter<edges;iter++)
        {
                scanf("%d%d",&vertex1,&vertex2);
                assert(vertex1>=0 && vertex1<vertices);
                assert(vertex2>=0 && vertex2<vertices);
                graph[vertex1][size[vertex1]++] = vertex2;
        }
        int presentVertex;
        for(presentVertex=0;presentVertex<vertices;presentVertex++)
        {
                if(!visited[presentVertex])
                {
                        Dfs(graph,size,presentVertex,visited);
                }
        }
        getche();
        return 0;

}     


--------------------------------------PYTHON IMPLEMENTATION---------------------------------------------

def dfs(graph,p_vertex,visited):
    print("Visiting vertex {0}".format(p_vertex))
    visited[p_vertex]=1
    #print(len(graph[p_vertex]))
    for itr in range(0,len(graph[p_vertex])):
        if(visited[graph[p_vertex][itr]]==0):
            #print("sent to visit vertex {0}".format(graph[p_vertex][itr]))
            dfs(graph,graph[p_vertex][itr],visited)
    return

vertices=int(input("Enter number of vertices::"))
edges=int(input("Enter the number of edges::"))
graph=[]
visited=[0]*vertices

#create the vertices
for i in range(0,vertices):
    v=[]
    graph.append(v)
#take input
for i in range(0,edges):
    v1,v2=input().split()
    v1,v2=int(v1),int(v2)
    assert(v1>=0 and v1<vertices)
    assert(v2>=0 and v2<vertices)
    graph[v1].append(v2)

print(graph)

for p_vertex in range(0,vertices):
    if(visited[p_vertex]==0):
        dfs(graph,p_vertex,visited)

Breadth First Search In Python and C

# breadth first search in PYTHON 3.2 #
from queue import *

def bfs(graph,p_vertex,visited):
    q=Queue()
    q.put(p_vertex)
    visited[p_vertex]=1
    while q.qsize()>0:
        t=q.get()
        print("Visiting vertex {0}".format(t))
        #i.e if t is what we want return t
        for child in range(0,len(graph[p_vertex])):
            if(visited[graph[p_vertex][child]]==0):
                visited[graph[p_vertex][child]]=1
                q.put(graph[p_vertex][child])
    return

vertices=int(input("Enter number of vertices::"))
edges=int(input("Enter the number of edges::"))
graph=[]
visited=[0]*vertices

#create the vertices
for i in range(0,vertices):
    v=[]
    graph.append(v)
#take input
for i in range(0,edges):
    v1,v2=input().split()
    v1,v2=int(v1),int(v2)
    assert(v1>=0 and v1<vertices)
    assert(v2>=0 and v2<vertices)
    graph[v1].append(v2)
print(graph)

for p_vertex in range(0,vertices):
    if(visited[p_vertex]==0):
        bfs(graph,p_vertex,visited)


----------->For those interested in C implimentation might find this a little long then python but here it is-------------->


#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
/* maxVertices represents maximum number of vertices that can be present in the graph. */
#define maxVertices   100
typedef struct Queue
{
        int capacity;
        int size;
        int front;
        int rear;
        int *elements;
}Queue;
/* crateQueue function takes argument the maximum number of elements the Queue can hold, creates
   a Queue according to it and returns a pointer to the Queue. */
Queue * CreateQueue(int maxElements)
{
        /* Create a Queue */
        Queue *Q;
        Q = (Queue *)malloc(sizeof(Queue));
        /* Initialise its properties */
        Q->elements = (int *)malloc(sizeof(int)*maxElements);
        Q->size = 0;
        Q->capacity = maxElements;
        Q->front = 0;
        Q->rear = -1;
        /* Return the pointer */
        return Q;
}
void Dequeue(Queue *Q)
{
        /* If Queue size is zero then it is empty. So we cannot pop */
        if(Q->size==0)
        {
                printf("Queue is Empty\n");
                return;
        }
        /* Removing an element is equivalent to incrementing index of front by one */
        else
        {
                Q->size--;
                Q->front++;
                /* As we fill elements in circular fashion */
                if(Q->front==Q->capacity)
                {
                        Q->front=0;
                }
        }
        return;
}
int Front(Queue *Q)
{
        if(Q->size==0)
        {
                printf("Queue is Empty\n");
                exit(0);
        }
        /* Return the element which is at the front*/
        return Q->elements[Q->front];
}
void Enqueue(Queue *Q,int element)
{
        /* If the Queue is full, we cannot push an element into it as there is no space for it.*/
        if(Q->size == Q->capacity)
        {
                printf("Queue is Full\n");
        }
        else
        {
                Q->size++;
                Q->rear = Q->rear + 1;
                /* As we fill the queue in circular fashion */
                if(Q->rear == Q->capacity)
                {
                        Q->rear = 0;
                }
                /* Insert the element in its rear side */
                Q->elements[Q->rear] = element;
        }
        return;
}



void Bfs(int graph[][maxVertices], int *size, int presentVertex,int *visited)
{
        visited[presentVertex] = 1;
        /* Iterate through all the vertices connected to the presentVertex and perform bfs on those
           vertices if they are not visited before */
        Queue *Q = CreateQueue(maxVertices);
        Enqueue(Q,presentVertex);
        while(Q->size)
        {
                presentVertex = Front(Q);
                printf("Now visiting vertex %d\n",presentVertex);
                Dequeue(Q);
                int iter;
                for(iter=0;iter<size[presentVertex];iter++)
                {
                        if(!visited[graph[presentVertex][iter]])
                        {
                                visited[graph[presentVertex][iter]] = 1;
                                Enqueue(Q,graph[presentVertex][iter]);
                        }
                }
        }
        return;


}
/* Input Format: Graph is directed and unweighted. First two integers must be number of vertces and edges
   which must be followed by pairs of vertices which has an edge between them. */
int main()
{
        int graph[maxVertices][maxVertices],size[maxVertices]={0},visited[maxVertices]={0};
        int vertices,edges,iter;
        /* vertices represent number of vertices and edges represent number of edges in the graph. */
        scanf("%d%d",&vertices,&edges);
        int vertex1,vertex2;
        for(iter=0;iter<edges;iter++)
        {
                scanf("%d%d",&vertex1,&vertex2);
                assert(vertex1>=0 && vertex1<vertices);
                assert(vertex2>=0 && vertex2<vertices);
                graph[vertex1][size[vertex1]++] = vertex2;
        }
        int presentVertex;
        for(presentVertex=0;presentVertex<vertices;presentVertex++)
        {
                if(!visited[presentVertex])
                {
                        Bfs(graph,size,presentVertex,visited);
                }
        }
        return 0;
}

------------------------------------------------------->END<------------------------------------------------------------------

Kruskal Algorithm in C

Sunday, 14 October 2012
Here is another important graph algo for finding the minimum weighted spanning tree imlimented in C.Input is taken from adj matrix with non-conn terms having val in #define MAXVAL & the number of vert changed by changing #define MAXVAL...


/*KRUSKAL ALGORITHM IN C*/
#include<stdio.h>
#define VERT 4 //predefined number of vertices
#define MAXVAL 99
void kruskal(int a[][VERT],int n);
int gethead(int vert,int par[]);
void vertex_union(int v1,int v2,int par[]);

void vertex_union(int v1,int v2,int par[])
{
    if(v1>v2)
    par[v1]=v2;
    else
    par[v2]=v1;
}

int gethead(int vert,int par[])
{
    while(par[vert]!=vert)
    {
        vert=par[vert];
    }
    return vert;
}

void kruskal(int a[][VERT],int n)
{
    int nofedges,i,parent[VERT],min,j,k,u,v,path[VERT-1][2],sum;
    nofedges=k=sum=0;
    for(i=0;i<n;i++)
    parent[i]=i;//sets parent
    while(nofedges<n-1)
    {
        min=MAXVAL;
        for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        if(a[i][j]<min)
        {
            min=a[i][j];
            u=i;
            v=j;
        }//gets the min for each turn
        if(min!=MAXVAL)
        {
            i=gethead(u,parent);
            j=gethead(v,parent);
            /*printf("==>%d %d %d %d\n",i,j,u,v);
            int ii;
            for(ii=0;ii<VERT;ii++)
            printf("%d ",parent[ii]);
            printf("\n");*/
            if(i!=j)
            {
                //printf("-->adding vertex %d %d",u,v);
                path[k][0]=u;
                path[k][1]=v;
                k++;
                sum+=min;
                vertex_union(i,j,parent);
                nofedges+=1;
            }
            a[u][v]=a[v][u]=999;
        }
    }
    if(nofedges!=n-1)
    printf("Invalid Spanning Tree");
    else
    {
        printf("Minimum cost=%d\n",sum);
        printf("The edges included are ::\n");
        for(i=0;i<n-1;i++)
        printf("%d %d \n",path[i][0],path[i][1]);
    }
}

int main()
{
    int cost[VERT][VERT],i,j;
    for(i=0;i<VERT;i++)
    for(j=0;j<VERT;j++)
    scanf("%d",&cost[i][j]);
    //adjacency matrix entered
    kruskal(cost,VERT);

}

Hope you enjoyed this..

Creating AVL Tree In Java

Friday, 12 October 2012

 Complete implementation only without the delete method ... If anyone wants it i will post it later in the comments :


import java.io.*;
class Node
{
int data;
Node leftchild;
Node rightchild;
Node parent;
public Node(int d)
{
    data=d;
    leftchild=null;
    rightchild=null;
}
public int get_data()
{
    return data;
}
public Node get_leftchild()
{
    return leftchild;
}
public Node get_rightchild()
{
    return rightchild;
}
public void set_data(int d)
{
    data=d;
}
public void set_leftchild(Node n)
{
    leftchild=n;
}
public void set_rightchild(Node n)
{
    rightchild=n;
}
public void set_parent(Node n)
{
    parent=n;
}
public Node get_parent()
{
    return parent;
}
}

//end of the node class

//start
class Avl
{
Node root;
public Avl()
{
    root=null;
}

public int max(int a,int b)
{
    if(a>b)
    return a;
    else
    return b;
}

public int get_height(Node n)
{
    if(n==null)
    return 0;
    else
    return max(get_height(n.get_leftchild()),get_height(n.get_rightchild()))+1;
}

public void left_left_rot(Node k2)
{
    Node k1=k2.get_leftchild();
    Node B=k1.get_rightchild();
    Node gp=k2.get_parent();
    if(gp!=null)
    {
        if(gp.get_rightchild()==k2)
        {
            gp.set_rightchild(k1);
            k1.set_parent(gp);
        }
        else
        {
            gp.set_leftchild(k1);
            k1.set_parent(gp);
        }
    }
    else
    {
    k1.set_parent(null);
    }
    k1.set_rightchild(k2);
    if(k1!=null)
    k2.set_parent(k1);
    k2.set_leftchild(B);
    if(B!=null)
    B.set_parent(k2);
}

public void right_right_rot(Node x)
{
    Node y=x.get_rightchild();
    Node B=y.get_leftchild();
    Node gp=x.get_parent();
    if(gp.get_rightchild()==x)
    {
        gp.set_rightchild(y);
        y.set_parent(gp);
        }
    else
    {
        gp.set_leftchild(y);
        y.set_parent(gp);
    }
    y.set_leftchild(x);
    x.set_parent(y);
    x.set_rightchild(B);
    if(B!=null)
    B.set_parent(x);
}

public void left_right_rot(Node k3)
{
    Node k1=k3.get_leftchild();
    Node k2=k1.get_rightchild();
    Node B=k2.get_leftchild();
    Node C=k2.get_rightchild();
    Node par=k3.get_parent();
    if(par.get_leftchild()==k3)
    par.set_leftchild(k2);
    else
    par.set_rightchild(k2);
    if(k2!=null)
    k2.set_parent(par);
    k2.set_leftchild(k1);
    if(k1!=null)
    k1.set_parent(k2);
    k2.set_rightchild(k3);
    if(k3!=null)
    k3.set_parent(k2);
    k1.set_rightchild(B);
    k3.set_leftchild(C);
    if(B!=null)
    B.set_parent(k1);
    if(C!=null)
    C.set_parent(k3);
}

public void right_left_rot(Node k1)
{
    Node k3=k1.get_rightchild();
    Node k2=k3.get_leftchild();
    Node C=k2.get_rightchild();
    Node B=k2.get_leftchild();
    Node par=k1.get_parent();
    if(par.get_leftchild()==k1)
    par.set_leftchild(k2);
    else
    par.set_rightchild(k2);
    if(k2!=null)
    k2.set_parent(par);
    k2.set_rightchild(k3);
    k2.set_leftchild(k1);
    if(k3!=null)
    k3.set_parent(k2);
    if(k1!=null)
    k1.set_parent(k2);
    k1.set_rightchild(B);
    k3.set_leftchild(C);
    if(B!=null)
    B.set_parent(k1);
    if(C!=null)
    C.set_parent(k3);
}
   

public int balance_factor(Node n)
{
    Node n1=n.get_rightchild();
    Node n2=n.get_leftchild();
    int h1,h2;
    h1=get_height(n1);
    h2=get_height(n2);
    return (h2-h1);
}
public Node returnUnbalanced(Node n)
{
    Node unbal=null;
    int checkflag=1;
    if(get_height(n.get_parent())==1)
    return unbal;
    int bf;
    while(n.get_parent()!=null)
    {
        n=n.get_parent();
        bf=balance_factor(n);
        if(checkflag==1)
        if((bf==2)||(bf==-2))
        {
            unbal=n;
            checkflag=0;
        }
    }
    return unbal;
}


   
public void insert(Node n,Node bs)
{
    if(bs==null)
    {
        root=n;
    }
    else
    {
        if(bs.get_data()>n.get_data())
        {
            if(bs.get_leftchild()==null)
            {
                bs.set_leftchild(n);
                n.set_parent(bs);
                Node unbal=returnUnbalanced(n);
                if(unbal!=null)
                {//balance it
                    int bf=balance_factor(unbal);
                    System.out.println("node ::"+unbal.get_data());
                    if(bf==2)
                    {
                        int bf2=balance_factor(unbal.get_leftchild());
                        if(bf2==1)
                        left_left_rot(unbal);
                        if(bf2==-1)
                        left_right_rot(unbal);
                    }
                    if(bf==-2)
                    {
                        int bf2=balance_factor(unbal.get_rightchild());
                        if(bf2==1)
                        right_left_rot(unbal);
                        if(bf2==-1)
                        right_right_rot(unbal);
                    }
                }
            }
            else
            insert(n,bs.get_leftchild());
        }
        else
        {
            if(bs.get_rightchild()==null)
            {
                bs.set_rightchild(n);
                n.set_parent(bs);
                Node unbal=returnUnbalanced(n);
                if(unbal!=null)
                {//perform the req bal op
                    int bf=balance_factor(unbal);
                    System.out.println("node::"+unbal.get_data());
                    if(bf==2)
                    {
                        int bf2=balance_factor(unbal.get_leftchild());
                        if(bf2==1)
                        left_left_rot(unbal);
                        if(bf2==-1)
                        left_right_rot(unbal);
                    }
                    if(bf==-2)
                    {
                        int bf2=balance_factor(unbal.get_rightchild());
                        if(bf2==1)
                        right_left_rot(unbal);
                        if(bf2==-1)
                        right_right_rot(unbal);
                    }
                }
            }
            else
            insert(n,bs.get_rightchild());
        }
    }
}

public void search(int n,Node bs)
{
    if(bs==null)
    System.out.println("not present in tree");
    else
    {
        if(bs.get_data()==n)
        System.out.println("Node is present in Tree");
        else if(bs.get_data()>n)
             search(n,bs.get_leftchild());
             else
             search(n,bs.get_rightchild());
    }
}

public Node findmin(Node bs)
{
    if(bs!=null)
        while(bs.get_leftchild()!=null)
        bs=bs.get_leftchild();
    return bs;
}

public Node findmax(Node bs)
{
    if(bs!=null)
        while(bs.get_rightchild()!=null)
        bs=bs.get_rightchild();
    return bs;
}

public void del(int n,Node bs)
{
    if(bs==null)
    System.out.println("node not found in tree");
    else
    {
        if(bs.get_data()==n)
        {
        //do the three cases
            //case 1.Node has no children;
            if((bs.get_leftchild()==null)&&(bs.get_rightchild()==null))
            {
                Node par=bs.get_parent();
                if(par.get_rightchild()==bs)
                par.set_rightchild(null);
                else
                par.set_leftchild(null);
            }
            //case 2.if Node has 1 child
            else
            {
                if((bs.get_leftchild()==null)||(bs.get_rightchild()==null))
                {
                    //System.out.println("here");
                    Node par=bs.get_parent();
                    Node child;
                    if(bs.get_leftchild()==null)
                    child=bs.get_rightchild();
                    else
                    child=bs.get_leftchild();
                    if(par.get_leftchild()==bs)
                    par.set_leftchild(child);
                    else
                    par.set_rightchild(child);
                }
                else //Node has 2 children
                {
                    Node min_r=findmin(bs.get_rightchild());
                    int tset=min_r.get_data();
                    //min would be that node itself or left leaf
                    Node par=min_r.get_parent();
                    if(par==bs)
                    {
                        bs.set_rightchild(min_r.get_rightchild());
                        bs.set_data(tset);
                    }
                    else
                    {
                        par.set_leftchild(null);
                        bs.set_data(tset);
                    }
                   
                }
            }
        }
        else if(bs.get_data()>n)
            del(n,bs.get_leftchild());
             else
            del(n,bs.get_rightchild());
    }
}

public void preorder(Node bs)
{
    if(bs==null)
    return;
    else
    {
        System.out.print(bs.get_data()+" ");
        preorder(bs.get_leftchild());
        preorder(bs.get_rightchild());
    }
}

public void postorder(Node bs)
{
    if(bs==null)
    return;
    else
    {
        postorder(bs.get_leftchild());
        postorder(bs.get_rightchild());
        System.out.print(bs.get_data()+" ");
    }
}

public void inorder(Node bs)
{
    if(bs==null)
    return;
    else
    {
        inorder(bs.get_leftchild());
        System.out.print(bs.get_data()+" ");
        inorder(bs.get_rightchild());
    }
}
}

class check
{
public static void main(String[] args)throws IOException
{
    FileReader fr=new FileReader("input.txt");
    BufferedReader br=new BufferedReader(fr);
    InputStreamReader isr=new InputStreamReader(System.in);
    BufferedReader br1=new BufferedReader(isr);
    String line=br.readLine();
    String[] numS=line.split(" ");
    int[] numbers=new int[numS.length];
    //create the bst
    Avl tree=new Avl();
    //input the elements
    for(int i=0;i<numS.length;i++)
    {
        numbers[i]=Integer.parseInt(numS[i]);
        Node n=new Node(numbers[i]);
        tree.insert(n,tree.root);
    }
    //print the preorder
    System.out.println("preorder traversal ::");
    tree.preorder(tree.root);
    System.out.println("\nPostorder traversal::");
    tree.postorder(tree.root);
    System.out.println("\ninorder traversal ::");
    tree.inorder(tree.root);
    //options
    Node nn;
    int d,s;
    while(true)
    {
    System.out.println("\n1.tree height\n2.Search(int)\n3.findmin()\n4.findmax()\n5.preorder()\n6.postorder()\n7.inorder()\n8.exit\n");
    int input=Integer.parseInt(br1.readLine());
    switch(input)
    {
        /*case 1: d=Integer.parseInt(br1.readLine());
            tree.del(d,tree.root);
            break;*/
        case 2: s=Integer.parseInt(br1.readLine());
            tree.search(s,tree.root);
            break;
        case 3: nn=tree.findmin(tree.root);
            System.out.println(nn.get_data());
            break;
        case 4: nn=tree.findmax(tree.root);
            System.out.println(nn.get_data());
            break;
        case 5:tree.preorder(tree.root);
            System.out.println();
            break;
        case 6:tree.postorder(tree.root);
            System.out.println();
            break;
        case 7:tree.inorder(tree.root);
            System.out.println();
            break;
        case 1:System.out.println(tree.get_height(tree.root));
            break;
        case 8:System.exit(1000);
            break;
        default:System.out.println("Not an option");
            break;
    }
    }
}
}

Dijkstra's Algorithm in C

Monday, 8 October 2012
Here's a graph algorithm implementation of Dijkstra's Algorithm in C .. input preferences are mentioned in comments in the program....

###########################################################################
/*Dijkrtas algorithm in C*/
#define N 6 //the number of vertices
#include<stdio.h>
#define INFINITY 999
#define TRUE 1
#define FALSE 0

int allvisited(int visits[])//checks if all nodes are visited or not
{
    int i,flag=1;
    for(i=0;i<N;i++)
    {
        if(visits[i]!=1)
        flag=0;
    }
    return flag;
}

int dijkstra(int graph[][N],int target,int source)
{
    int visited[N],dist[N];
    //source -1 in actual matrix ..check row for neighbours
    //init
    int i;
    for(i=0;i<N;i++)
    {
        dist[i]=INFINITY;
        visited[i]=-1;
    }
    int start=source;
    while(!allvisited(visited))
    {
        //printf("--->start=%d\n",start);
        visited[start]=1;
        if(dist[start]==INFINITY)
        {
            dist[start]=0;
        }
        for(i=0;i<N;i++)
        {
            if(graph[start][i]!=INFINITY)//this is a neighbour of start
            {
                int d=dist[start]+graph[start][i];
                if(d<dist[i])
                dist[i]=d;
            }
        }
        //checking
        /*for(i=0;i<N;i++)
        printf("%d ",dist[i]);
        printf("\n");*/
        //get the next node i.e. will be the minimum of tentative dist and unvisited
        int min=INFINITY;
        int pos=INFINITY;
        for(i=0;i<N;i++)
        {
            if(visited[i]!=1)
            {
                if(dist[i]<min)
                {
                    min=dist[i];
                    pos=i;
                }
            }
        }
        //if pos==NULL then over
        if(pos==INFINITY)
        break;
        else
        start=pos;
        //printf("continue..\n");
    }
    return dist[target];
}

int main()
{
    int graph[N][N];
    int i,j;
    printf("Enter the graph::\n");
    for(i=0;i<N;i++)
    for(j=0;j<N;j++)
    scanf("%d",&graph[i][j]);
    //taken input must be symmetric and for i=j should be 0 and for not connected should be infinity as defined
    int src,tar;
    printf("Enter the source and target::");
    scanf("%d %d",&src,&tar);
    int dis=dijkstra(graph,tar-1,src-1);
    printf("min dist=%d",dis);
    return 0;
}
##################################################################################

If anyone wants the python or Java version please mention it in the comments and i will post it..

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");
        }
        }
    }
}   
Copyright @ 2013 code-craft. Designed by Templateism | MyBloggerLab