• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
projectsgeek

ProjectsGeek

Download Mini projects with Source Code, Java projects with Source Codes

  • Home
  • Java Projects
  • C++ Projects
  • VB Projects
  • PHP projects
  • .Net Projects
  • NodeJs Projects
  • Android Projects
    • Project Ideas
      • Final Year Project Ideas
      • JSP Projects
  • Assignment Codes
    • Fundamentals of Programming Language
    • Software Design Laboratory
    • Data Structure and Files Lab
    • Computer Graphics Lab
    • Object Oriented Programming Lab
    • Assembly Codes
  • School Projects
  • Forum

Design and Analysis of Algorithms

8 Queen Problem

June 21, 2011 by ProjectsGeek Leave a Comment

 

 

 

8 Queen Problem
Aim: Implementation of 8 queen problem( Non recursive implementation) using

backtracking strategy

Objective: To study and understand the concept of backtracking.

Theory:

 

 

 

Backtracking

 

General method-

• Useful technique for optimizing search under some constraints

• Express the desired solution as an n-tuple (x1, . . . , xn) where each xi 2 Si, Si being a finite set

• The solution is based on finding one or more vectors that maximize, minimize, or satisfy a criterion function P(x1, . . . , xn)

• Sorting an array a[n]

– Find an n-tuple where the element xi is the index of ith smallest element in a

– Criterion function is given by a[xi] _ a[xi+1] for 1 _ i < n

– Set Si is a finite set of integers in the range [1,n]

• Brute force approach

– Let the size of set Si be mi

– There are m = m1m2 · · ·mn n-tuples that satisfy the criterion function P

– In brute force algorithm, you have to form all the m n-tuples to determine the optimal solutions

• Backtrack approach

– Requires less than m trials to determine the solution

– Form a solution (partial vector) and check at every step if this has any chance of success

– If the solution at any point seems not-promising, ignore it

– If the partial vector (x1, x2, . . . , xi) does not yield an optimal solution, ignore mi+1 · · ·mn possible test vectors

even without looking at them

• All the solutions require a set of constraints divided into two categories: explicit and implicit constraints

Definition 1 Explicit constraints are rules that restrict each xi to take on values only from a given set.

– Explicit constraints depend on the particular instance I of problem being solved

– All tuples that satisfy the explicit constraints define a possible solution space for I

– Examples of explicit constraints

_ xi _ 0, or all nonnegative real numbers

_ xi = {0, 1}

_ li _ xi _ ui

Definition 2 Implicit constraints are rules that determine which of the tuples in the solution space of I satisfy the

criterion function.

– Implicit constraints describe the way in which the xis must relate to each other.

• 8-queens problem

 

 

 

– Place eight queens on an 8 × 8 chessboard so that no queen attacks another queen

Backtracking

1

2

3

4

5

6

7

8

1

Q

2

Q

3

Q

4

Q

5

Q

6

Q

7

Q

8

Q

– Identify data structures to solve the problem

_ First pass: Define the chessboard to be an 8 × 8 array

_ Second pass: Since each queen is in a different row, define the chessboard solution to be an 8-tuple (x1, . . . , x8),

where xi is the column for ith queen

– Identify explicit constraints

_ Explicit constraints using 8-tuple formulation are Si = {1, 2, 3, 4, 5, 6, 7, 8}, 1 _ i _ 8

_ Solution space of 88 8-tuples

– Identify implicit constraints

_ No two xi can be the same, or all the queens must be in different columns

· All solutions are permutations of the 8-tuple (1, 2, 3, 4, 5, 6, 7, 8)

· Reduces the size of solution space from 88 to 8! tuples

_ No two queens can be on the same diagonal

– The solution above is expressed as an 8-tuple as 4, 6, 8, 2, 7, 1, 3, 5

Other Projects to Try:

  1. Prim’s Algorithm , Minimum Cost of Spanning Tree
  2. N queen problem code in C Language

Filed Under: Design and Analysis of Algorithms

Prim’s Algorithm , Minimum Cost of Spanning Tree

June 21, 2011 by ProjectsGeek Leave a Comment

Objective of prim’s algorithm is to understand the Greedy method to obtain a minimum cost spanning tree edge by edge.

 

Greedy method :

 

  1. It is the most straight forward design technique. Most of the problems have n inputs & require us to obtain a subset that satisfies some constraints.
  2. Any subset that satisfies these constraints is called a feasible solution.
  3. We find a feasible solution that either maximizes or minimizes a given objective function.
  4. A feasible solution that does this is called an ‘Optimal Solution’ .

Greedy algorithm :

 

·It works in stages , considers one input at a time .
·Inputs are considered in an order determined by some selection procedure.
·At each stage, decision is made regarding whether a particular input is in optimal solution.
·Inclusion of next input into partially constructed optimal solution should always result into feasible solution. If not then, this input is not considered.
·Selection procedure is based on some optimization measure; which may be objective function.
·Greedy algorithm that makes use of optimization measures to generate suboptimal solution is called ‘Subset Paradigm’.

General greedy algorithm :

 

Algorithm Greedy (a,n)

// a[1…n] contains n inputs.

{

solution=0; //initialise the solution

for( i=1 to n )

do

{

x= select(a);

if(feasible(solution, x)) then

solution= union(solution , x);

}

return solution;

}

à Function select , selects an input from a[ ] and removes it. The selected input’s value is assigned to x.
àFunction feasible is Boolean valued function that determines whether x can be included into solution vector.
àFunction union combines x with solution and updates the objective function.
·Knapsack problem , job sequencing , minimum spanning trees comes under the subset paradigm.
·Shortest path , Huffman codes comes under ordering paradigm.

Minimum cost spanning trees :

 

Definition : Spanning trees –

Let G = (V , E) be an undirected connected graph. A subgraph t= ( V , E’) of G is a spanning tree if and only if t is a tree. (No cycle exists.)

In practical situations, the edges have weights assigned to them, weights are positive. These weights may represent the cost of construction, lengths of links etc.

Given such weighted graph one would like to select cities (vertices) to have minimum total cost / minimum total length. So one can find a spanning tree with minimum cost.

Since identification of minimum spanning tree involves selection of a subset of the edges, this problem fits into the Subset Paradigm.

Prims algorithm’s outline :

Greedy method constructs the tree by including edge by edge. Choose an edge that results in a minimum increase in sum of cost of edges so far included. Also set of edges so far selected form a tree. (No cycle.)

Pseudo code for Prim’s algorithm :

Prim()

// cost[1..n][1..] is a cost adjacency matrix.

// n: number of vertices in the graph.

// cost [ i ][ j ] =∞ , if there is no edge between I and j.

// cost [ i ][ j ] =∞ , if i=j

// cost [ i ][ j ] = cost [ i ][ j ] = positive number if it is edge.

// t [1..n-1][1..2] has all the edges of minimum spanning tree

// mincost is minimum cost

// near[ ] is an array which stores vertex in tree

// such that cost [ j ][ near[ j ] ] is minimum among all choices for near[ j ].

  1. mincost =0;
  2. For (i=2 to n) do near[ i ]=1;
  3. Near[1]=0 //vertex 1 is initially in ‘t’ .
  4. For(i=1 to n-1) do
  5. { // find n-1 edges of tree.
  6. Let j be an index such that
  7. Near[ j ] !=0 & cost[ j ][ near[ j ] ] is minimum.
  8. // computation of j requires linear loop
  9. // not shown above.
  10. t[ i ][1] = j; t[ i ][2]= near[ j ];
  11. mincost=mincost + cost[ j ][near [ j ] ];
  12. Near[ j ] =0;
  13. For( k= 1 to n ) do //update near[ ]
  14. If(near[ k ] !=0) && (cost[ k ][ near[ k ] ] > cost[ k ][ j ])
  15. Near[ k ]=j;
  16. }
  17. return mincost.

 

 

Stages in Prim’s algorithm :

 

 

 

 

Complexity : The time required by algorithm Prim is O(n^2) where n is number of vertices in graph G. Each iteration of for loop takes O(n) time. So the total time is O(n^2).

If we store nodes not yet included in tree as a red-black tree then algorithm takes O(log n) time.

Disadvantages of Prim’s algorithm:

  1. List of edges has to be searched from beginning as new edge gets added.
  2. If there are more than one edges having same weight then all possible spanning trees are required to be found for final minimal tree.

Other Projects to Try:

  1. Dijkstra Algorithm in C Language
  2. Software Design Laboratory Assignments
  3. Kruskal’s Algorithm , Prims Algorithm
  4. Expression Tree using C Language
  5. Prims algorithm Code in C Language

Filed Under: Design and Analysis of Algorithms

Kruskal’s Algorithm , Prims Algorithm

June 21, 2011 by ProjectsGeek Leave a Comment

Implement kruskal’s algorithm and Prims algorithm

 

 

Aim – Write a program in C/C++ to implement kruskal’s algorithm and Prims algorithm.

 

Objective: – To understand the role of Kruskal and Prim’s algorithm in finding out the minimum cost spanning tree.

 

Theory :

 

Kruskal’s algorithm is another greedy algorithm for the minimum spanning tree problem that also always yields an optimal solution. It is named Kruskal’s algorithm [Kru56], after Joseph Kruskal, who discovered the algorithm when he was a second-year graduate student. Kruskal’s algorithm looks at the minimum spanning tree for a weighted connected graph G = {V, E} as an acyclic subgraph with |V|-1 edges for which the sum of the edges weights is the smallest.

The algorithm begins by sorting the graph’s edges in non decreasing order of their weights. Then, starting with the empty subgraph, it scans this sorted list adding the next edge on the list to the current subgraph if such an inclusion does not create a cycle and simply skipping the edge otherwise.

 

 

 

Data Structures used:

 

  1. Use array reorientation of sets where value in the array is either a link to parent field or for root node the value is total no of children with negative sign.
  2. We use heap to store the edge information.

Pseudocode for Kruskal: –

 

// Cost – 2 dimensional matrix, cost[u][v] is cost of edge (u,v);

// n no. of vertices.

//‘t’ set of edges in minimum spanning tree – it us a 2D array. t[1…..n][1….2]

// initially each vertex is in different set.

  1. Construct a minimum heap out of edge costs using heapify.
  2. For( i = 1 to n) do parent[i] = -1;

// each vertex is in different set.

  1. I=0; mincost=0;
  2. While(i 

    )>

  3. {
  4. Delete minimum cost edge (u,v) from heap
  5. Reheapify using adjust.
  6. J=find(u); k=find(v);
  7. If (j!=k) then\
  8. {
  9. I++; t[i][1]=u,t[i][2]=v;
  10. Union(j,k); mincost = mincost+cost[u][v];
  11. }
  12. }

Algorithm SimpleUnion (I, j) // i & j are roots of sets.

{

p[i] = j;

}

Algorithm SimpleFind (i ) // return root of ‘i’

{

while (p[i] >=0) do i=p[i];

return I;

}

If we want to perform n-1 unions then can be processed in Linear time O(n)

The time required to process a find for an element at level ‘i’ of a tree is O(i), so total time needed to process n finds is O(n^2)

One can improve the performance of our union & find by avoiding creation of degenerating trees.

We apply weighting rule for Union, which says that if the number of nodes in the tree with root i is less than the number of nodes in the tree with root j, then make j as the parent of i, otherwise make i, as the parent of j. Thus we avoid degenerated/skewed trees.

Similarly we use CollapseFind , to improve the performance of find. In CollapsingFind, we are required to go up to reach the root node and then reset the links. Every first find has to go through intermediate nodes to go up to root node, but every next find on similar node will require only one link to go up, thus reducing the cost cost of find. Collapsing rule says that, if j is a node on the path from i to its root node and p[i] is not root[i], then set p[j] to root[i].

Weighted union(I,j)

{

Temp=p[i]+p[j];

If(p[i]>p[j]) // i has fewer nodes

{

p[i]=j, p[j]=temp;

}

Else

{

p[j]=I; // j has fewer nodes

p[i]=temp;

}

}

Collapse Find(i)

{

r=I;

While(p[r]>=0)

r=p[r];

while(i=r)

{

s=p[i];

p[i]=r;

i=s;

}

}

Analysis of Kruskal algorithm :

 

Time required to construct the initial heap is log E.

Removal of edge from heap requires again log E and the edge is removed in the while loop which runs for E times, hence the time complexity of algorithm is O(E log E). Here since we have used sets to represent trees and we have used efficient find and union algorithms which take almost O(1) time.

Other Projects to Try:

  1. Regular Expression to DFA Code in C Language
  2. Prims algorithm Code in C Language
  3. Krushkals algorithm Code in C Language
  4. Prim’s Algorithm , Minimum Cost of Spanning Tree
  5. Macro Processor Algorithm

Filed Under: Design and Analysis of Algorithms

Tower of Hanoi

June 21, 2011 by ProjectsGeek Leave a Comment

To implement a Tower of Hanoi (Recursive implementation)

Aim:-

Write a program to implement a Tower of Hanoi (Recursive implementation) in

C /C++ language.

Objective:-

To understand and implement Recursive algorithm using the Tower of Hanoi

problem and study Divide and Conquer strategy.

Theory:-

Divide and conquer strategy:

Divide: Divide the problem into a number of subproblem that are smaller instances of the same problem.

Conquer: Conquer the subproblem by solving them recursively. If the subproblem sizes are small enough, just solve the subproblems in a straight forward manner.

Combine: Combine the solutions to the sub problems into the solutions for the original problem.

When the subproblems are large enough to solve recursively, we call that the recursive case. Once the subprobles become small enough that we no longer recurse, recursion “bottoms out” and that we have gone down to the base case. In combine step, we solve subproblems that are quite not same as original.

Recurrences go hand in hand with divide-and-conquer paradigm, because they give us a natural way to characterize the running times of divide-and-conquer algorithms.

Algorithm DAndC(P)

{

If small((P) then return S(P);

Else

{

Divide P into smaller instances say P1,P2,P3……….Pk ,

k>=1;

Apply DAndC to each of thse subproblems

Return Combine(DAndC(P1),DAndC(P2),……DAndC(Pk));

}

}

Tower of Hanoi problem:

Assume that there are ‘n’ number of disks on tower A. The disks are of decreasing size and are stacked on the tower in decreasing order of size bottom to top. Besides this tower, there are two other towers labeled B and C. The disks from tower A are to be moved to tower B using tower C as intermediate storage. The disks are to be moved one at a time. In addition, at no time can a disk be on top of a smaller disk.

Assume that there are n number of disks on tower A. To get the largest disk to the bottom of tower B, we move the remaining n-1 disks to tower C and then move the largest disk to tower B. Now ,we are left with the task of moving the disks from tower C to tower B. To do this, we have tower A and B available. The fact that the tower B has a disk can be ignored as the disk is larger than the disks being moved from tower C and so any disk can be placed on top of it.

Algorithm TowerofHanoi(n,x,y,z)

//Move the top n disks from tower x to tower y

{

If(n >= 1)then

{

TowerofHanoi(n-1,x,z,y);

Write(“move top disk from tower”,x,”to top of tower”,y);

TowerofHanoi(n-1,z,y,x);

}

}

The recursive nature of the solution is apparent from the above algorithm. Our solution for an n-disk problem is formulated in terms of solutions to two(n-1)disk problems.

Analysis

Recurrence relation:

T(n)=g(n)…….. n is small

=T(n1)+T(n2)+……+T(nk)+f(n)

In general,

T(n)=T(1)

=aT(n/b)+f(n). n=2k

Example:

tn = 0

=t(n-1) + 1+t(n-1)

Where first t(n-1) =movement of (n-1) disks from tower A to tower C. 1 is for the movement of the bottommost disk from tower A to tower B.

Second t(n-1) = movement of the (n-1) disks from tower C to tower B.

tn = 2t(n-1) + 1

Thus,

tn – 2tn-1 = 1 b=1

p(n)=1

Characteristic polynomial is (x-2) (x-1)

tn = c1 1n + c2 2n

t1= 2t0 + 1

t0 = 0 …..Original recursive relation

t1 = 1

when n=0

tn = c1 + c2 = 0, t0 is0

When n=1

tn = c1 + 2c2 =1, t1 is0

-c2 = -1

c2 = 1

c1 = -1

tn = 2n-1 ……tower of hanoi

tn = number of disk movements.

Other Projects to Try:

  1. Tower of Hanoi problem code in C Language
  2. 8 Queen Problem
  3. Software Design Laboratory Assignments
  4. Finding Real solutions of Quadratic equations in Java code
  5. N queen problem code in C Language

Filed Under: Design and Analysis of Algorithms

Tower of Hanoi problem code in C Language

May 4, 2011 by ProjectsGeek Leave a Comment

Tower of Hanoi problem code in C Language

Write a c program for  Tower of Hanoi problem. User  has to provide input to the program in terms of numbers of disc on each tower and the program should print the solution of tower of hanoi.

Tower of Hanoi code

 #include  
 #include  
 #include  
 #include  
 void toh(int n,char src,char dest,char by)  
 {  
   time_t t1;  
   if(n==1)  
     printf("Move frm %c to %c \n",src,dest);  
   else  
   {  
     toh(n-1,src,by,dest);  
     printf("Move frm %c to %c time: \n ",src,dest);  
     delay(500);  
     toh(n-1,by,dest,src);  
   }  
   //printf("time:%ld\n",stime(NULL));  
 }  
 void main()  
 {  
   clrscr();  
   printf("Enter the no of disks\n");  
   int n;  
   scanf("%d",&n);  
   time_t t1,t2;  
   t1=time(NULL);  
   toh(n,'A','C','B');  
   t2=time(NULL);  
   printf("The difference is: %f seconds\n",difftime(t2,t1));  
   getch();  
 }

 

 

Other Projects to Try:

  1. Dijkstra Algorithm in C Language
  2. Regular Expression to DFA Code in C Language
  3. Tower of Hanoi
  4. Prims algorithm Code in C Language
  5. N queen problem code in C Language

Filed Under: Design and Analysis of Algorithms

Prims algorithm Code in C Language

May 4, 2011 by ProjectsGeek Leave a Comment

Prims algorithm Code in C Language

Write a program for Prims algorithm Code in C Language for finding Minimum spanning tree.

 Prims algorithm Code

 #include  
 #include  
 #define max 50  
 #define infinity 32767  
 void input(int adj[max][max],int n)  
 {  
   int i,j;  
   char ch;  
   for(i=0;i<n;++i) <br="">   {  
     for(j=0;j<n;++j) <br="">     {  
       adj[i][j]=infinity;  
     }  
   }  
   int s,d,w;  
   while(1)  
   {  
     printf("Do You want to enter another edge\n");  
     flushall();  
     scanf("%c",&ch);  
     if(ch=='y'||ch=='Y')  
     {  
       flushall();  
       printf("Source:");  
       scanf("%d",&s);  
       printf("Dest:");  
       scanf("%d",&d);  
       printf("Weight:");  
       scanf("%d",&w);  
       adj[s][d]=w;  
       adj[d][s]=w;  
     }  
     else  
       break;  
   }  
 }  
 int check(int arr[],int pos)  
 {  
   while(1)  
   {  
     if(arr[pos]!=-1)  
       pos=arr[pos];  
     else  
       return pos;  
   }  
   //return -1;  
 }  
 void print(int mst[],int n)  
 {  
   printf("SOURCE\tDEST\tWEIGHT\n");  
   for(int i=0;i<(n/3);++i)  
   {  
     for(int j=i*3;j<(i+1)*3;++j)  
     {  
       printf("%d\t",mst[j]);  
     }  
     printf("\n");  
   }  
 }  
 void main()  
 {  
   int adj[max][max];  
   int n;  
   clrscr();  
   printf("Enter the no of vertices\n");  
   scanf("%d",&n);  
   input(adj,n);  
   int visited[max];  
   visited[0]=-1;  
   for(int i=1;i<n;++i) <br="">   {  
     visited[i]=0;  
   }  
   int min=infinity;  
   int pos,ptr=0;  
   int mst[max];  
   for(int j=0;j<n-1;++j) <br="">   {  
     min=infinity;  
     for(i=0;i<n;++i) <br="">     {  
       if(visited[i]!=-1)  
       {  
         if(min>adj[i][visited[i]])  
         {  
           pos=i;  
           min=adj[i][visited[i]];  
         }  
       }  
     }  
     mst[ptr++]=pos;  
     mst[ptr++]=visited[pos];  
     mst[ptr++]=adj[pos][visited[pos]];  
     visited[pos]=-1;  
     for(i=0;i<n;++i) <br="">     {  
       if(visited[i]!=-1 && adj[i][pos]<adj[i][visited[i]] )="" <br="">       {  
         visited[i]=pos;  
       }  
     }  
   }  
   print(mst,ptr);  
   getch();  
 }

 

Other Projects to Try:

  1. Breadth First and Depth First Search C Language
  2. Hash table code in C Language
  3. Bankers Algorithm using C Language OS problem
  4. Kruskal’s Algorithm , Prims Algorithm
  5. Krushkals algorithm Code in C Language

Filed Under: Design and Analysis of Algorithms

  • Page 1
  • Page 2
  • Go to Next Page »

Primary Sidebar

Tags

.Net Projects Download Android Project Ideas Android Projects Angular 2 Assembly Codes C # Projects C & C++ Projects C++ Projects Class Diagrams Computer Graphics Database Project Data Mining Projects DataScience Projects Datastructure Assignments Download Visual Basic Projects Electronics project Hadoop Projects Installation Guides Internet of Things Project IOS Projects Java Java Interview Questions Java Projects JavaScript JavaScript Projects java tutorial JSON JSP Projects Mechanical Projects Mongodb Networking Projects Node JS Projects OS Problems php Projects Placement Papers Project Ideas Python Projects seminar and presentation Struts

Search this Website


Footer

Download Java Project
Download Visual Basic Projects
Download .Net Projects
Download VB Projects
Download C++ Projects
Download NodeJs Projects
Download School Projects
Download School Projects
Ask Questions - Forum
Latest Projects Ideas
Assembly Codes
Datastructure Assignments
Computer Graphics Lab
Operating system Lab
australia-and-India-flag
  • Home
  • About me
  • Contact Form
  • Submit Your Work
  • Site Map
  • Privacy Policy