Vous êtes sur la page 1sur 36

Algorithms and Algorithmic

Complexity

ASSIGNMENT
M.Tech CSE

1st Semester
Submitted By: Sounak Banerjee

University Roll: 97/CSM/160024


Class Roll: 26
Assignment 1

1.1 Problem Statement: A partition of a positive


integer n is a way to write n as a sum of positive integers.
For instance, 7 = 3 + 2 + 1 + 1 is a partition of 7. Given a
positive integer, find the number of partitions of this
integer. Write a program to do this.
1.2 Algorithm: We print all partition in sorted order and
numbers within a partition are also printed in sorted order.
The idea is to get next partition using the values in current
partition. We store every partition in an array p[]. We
initialize p[] as n where n is the input number. In every
iteration. we first print p[] and then update p[] to store the
next partition. So the main problem is to get next partition
from a given partition.
Steps to get next partition from current partition:
We are given current partition in p[] and its size. We need
to update p[] to store next partition. Values in p[] must be
sorted in non-increasing order.
Step 1: Find the rightmost non-one value in p[] and store
the count of 1s encountered before a non-one value in a
variable rem_val (It indicates sum of values on right side to
be updated). Let the index of non-one value be k.
Step 2: Decrease the value of p[k] by 1 and increase
rem_val by 1. Now there may be two cases:
a) If p[k] is more than or equal to rem_val. This is a
simple case (we have the sorted order in new partition).
Put rem_val at p[k+1] and p[0k+1] is our new partition.
b) Else (This is a interesting case, take initial p[] as {3, 1,
2 | Page
1, 1}, p[k] is decreased from 3 to 2, rem_val is increased
from 3 to 4, the next partition should be {2, 2, 2}).
Copy p[k] to next position, increment k and reduce
count by p[k] while p[k] is less than rem_val. Finally, put
rem_val at p[k+1] and p[0k+1] is our new partition. This
step is like dividing rem_val in terms of p[k] (4 is divided in
2s).

1.3 Program:
The algorithm has been implemented using JAVA
programming language.
File: Partition.java
import java.util.Scanner;
public class Partition
{
static int count=0;
static void printArray(int p[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(p[i] + " ");
System.out.println("");
}
static void printAllUniqueParts(int n)
{
int[] p = new int[100];
int k=0;
p[k]=n;
while(true)
{
3 | Page
printArray(p,k+1);
count++;
int rem_val = 0;
while (k >= 0 && p[k] == 1)
{
rem_val += p[k];
k--;
}
if (k < 0)
return;
p[k]--;
rem_val++;
while (rem_val > p[k])
{
p[k+1] = p[k];
rem_val = rem_val - p[k];
k++;
}
p[k+1] = rem_val;
k++;
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number : ");
int number=sc.nextInt();
4 | Page
System.out.println(" ");
System.out.println("List of Partitions of "+number+"
are: ");
printAllUniqueParts(number);
System.out.println(" ");
System.out.print("number of partitions are: "+count);
}
}

1.4 Output:

5 | Page
6 | Page
Assignment 2

2.1 Problem Statement: Write n interactive


program that would generate convex hull using Grahams
Algorithm. Show the output on the screen .
2.2 Algorithm: Given a set of points in the plane. the
convex hull of the set is the smallest convex polygon that
contains all the points of it.
The first step in this algorithm is to find the point with the
lowest y-coordinate. If the lowest y-coordinate exists in
more than one point in the set, the point with the lowest x-
coordinate out of the candidates should be chosen. Call
this point P. This step takes O(n), where n is the number of
points in question.
Next, the set of points must be sorted in increasing order
of the angle they and the point P make with the x-axis. Any
general-purpose sorting algorithm is appropriate for this,
for example heapsort (which is O(n log n)).
Let points[0..n-1] be the input array.
Step 1: Find the bottom-most point by comparing y
coordinate of all points. If there are two points with same y
value, then the point with smaller x coordinate value is
considered. Let the bottom-most point be P0. Put P0 at first
position in output hull.
Step 2: Consider the remaining n-1 points and sort them
by polor angle in counterclockwise order around points[0].
If polor angle of two points is same, then put the nearest
point first.
Step 3: After sorting, check if two or more points have
same angle. If two more points have same angle, then
remove all same angle points except the point farthest
from P0. Let the size of new array be m.
7 | Page
Step 4: If m is less than 3, return (Convex Hull not
possible)
Step 5: Create an empty stack S and push points[0],
points[1] and points[2] to S.
Step 6: Process remaining m-3 points one by one. Do
following for every point points[i]
6.1: Keep removing points from stack while orientation
of following 3 points is not counterclockwise(or they dont
make a left turn).
a) Points next to top in stack.
b) Points at the top of stack.
6.2: Push points[i] to S.
Step 5: Print contents of S

2.3 Program:
The algorithm has been implemented using JAVA
programming language.
File: GrahamScan.java
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.Stack;

class Point2D implements Comparable<Point2D>


{
public static final Comparator<Point2D> X_ORDER =
new XOrder();
public static final Comparator<Point2D> Y_ORDER =
new YOrder();
public static final Comparator<Point2D> R_ORDER =
8 | Page
new ROrder();
public final Comparator<Point2D> POLAR_ORDER = new
PolarOrder();
public final Comparator<Point2D> ATAN2_ORDER = new
Atan2Order();
public final Comparator<Point2D> DISTANCE_TO_ORDER
= new DistanceToOrder();

private final double x; // x coordinate


private final double y; // y coordinate

public Point2D(double x, double y)


{
if (Double.isInfinite(x) || Double.isInfinite(y))
throw new IllegalArgumentException("Coordinates
must be finite");
if (Double.isNaN(x) || Double.isNaN(y))
throw new IllegalArgumentException("Coordinates
cannot be NaN");
if (x == 0.0)
x = 0.0; // convert -0.0 to +0.0
if (y == 0.0)
y = 0.0; // convert -0.0 to +0.0
this.x = x;
this.y = y;
}

public double x()


{
return x;
}

public double y()


{
return y;
}
9 | Page
public double r()
{
return Math.sqrt(x * x + y * y);
}

public double theta()


{
return Math.atan2(y, x);
}

private double angleTo(Point2D that)


{
double dx = that.x - this.x;
double dy = that.y - this.y;
return Math.atan2(dy, dx);
}

public static int ccw(Point2D a, Point2D b, Point2D c)


{
double area2 = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) *
(c.x - a.x);
if (area2 < 0)
return -1;
else if (area2 > 0)
return +1;
else
return 0;
}

public static double area2(Point2D a, Point2D b, Point2D


c)
{
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}

10 | P a g e
public double distanceTo(Point2D that)
{
double dx = this.x - that.x;
double dy = this.y - that.y;
return Math.sqrt(dx * dx + dy * dy);
}

public double distanceSquaredTo(Point2D that)


{
double dx = this.x - that.x;
double dy = this.y - that.y;
return dx * dx + dy * dy;
}

public int compareTo(Point2D that)


{
if (this.y < that.y)
return -1;
if (this.y > that.y)
return +1;
if (this.x < that.x)
return -1;
if (this.x > that.x)
return +1;
return 0;
}

private static class XOrder implements


Comparator<Point2D>
{
public int compare(Point2D p, Point2D q)
{
if (p.x < q.x)
return -1;
if (p.x > q.x)
return +1;
11 | P a g e
return 0;
}
}

private static class YOrder implements


Comparator<Point2D>
{
public int compare(Point2D p, Point2D q)
{
if (p.y < q.y)
return -1;
if (p.y > q.y)
return +1;
return 0;
}
}

private static class ROrder implements


Comparator<Point2D>
{
public int compare(Point2D p, Point2D q)
{
double delta = (p.x * p.x + p.y * p.y) - (q.x * q.x +
q.y * q.y);
if (delta < 0)
return -1;
if (delta > 0)
return +1;
return 0;
}
}

private class Atan2Order implements


Comparator<Point2D>
{
public int compare(Point2D q1, Point2D q2)
12 | P a g e
{
double angle1 = angleTo(q1);
double angle2 = angleTo(q2);
if (angle1 < angle2)
return -1;
else if (angle1 > angle2)
return +1;
else
return 0;
}
}

private class PolarOrder implements


Comparator<Point2D>
{
public int compare(Point2D q1, Point2D q2)
{
double dx1 = q1.x - x;
double dy1 = q1.y - y;
double dx2 = q2.x - x;
double dy2 = q2.y - y;

if (dy1 >= 0 && dy2 < 0)


return -1; // q1 above; q2 below
else if (dy2 >= 0 && dy1 < 0)
return +1; // q1 below; q2 above
else if (dy1 == 0 && dy2 == 0)
{ // 3-collinear and horizontal
if (dx1 >= 0 && dx2 < 0)
return -1;
else if (dx2 >= 0 && dx1 < 0)
return +1;
else
return 0;
} else
return -ccw(Point2D.this, q1, q2); // both above
13 | P a g e
or below
}
}

private class DistanceToOrder implements


Comparator<Point2D>
{
public int compare(Point2D p, Point2D q)
{
double dist1 = distanceSquaredTo(p);
double dist2 = distanceSquaredTo(q);
if (dist1 < dist2)
return -1;
else if (dist1 > dist2)
return +1;
else
return 0;
}
}

public boolean equals(Object other)


{
if (other == this)
return true;
if (other == null)
return false;
if (other.getClass() != this.getClass())
return false;
Point2D that = (Point2D) other;
return this.x == that.x && this.y == that.y;
}

public String toString()


{
return "(" + x + ", " + y + ")";
}
14 | P a g e
public int hashCode()
{
int hashX = ((Double) x).hashCode();
int hashY = ((Double) y).hashCode();
return 31 * hashX + hashY;
}

public class GrahamScan


{
private Stack<Point2D> hull = new Stack<Point2D>();

public GrahamScan(Point2D[] pts)


{

// defensive copy
int N = pts.length;
Point2D[] points = new Point2D[N];
for (int i = 0; i < N; i++)
points[i] = pts[i];
Arrays.sort(points);

Arrays.sort(points, 1, N, points[0].POLAR_ORDER);

hull.push(points[0]); // p[0] is first extreme point


int k1;
for (k1 = 1; k1 < N; k1++)
if (!points[0].equals(points[k1]))
break;
if (k1 == N)
return; // all points equal
int k2;
for (k2 = k1 + 1; k2 < N; k2++)
if (Point2D.ccw(points[0], points[k1], points[k2]) !=
15 | P a g e
0)
break;
hull.push(points[k2 - 1]); // points[k2-1] is second
extreme point

for (int i = k2; i < N; i++)


{
Point2D top = hull.pop();
while (Point2D.ccw(hull.peek(), top, points[i]) <= 0)
{
top = hull.pop();
}
hull.push(top);
hull.push(points[i]);
}

assert isConvex();
}

public Iterable<Point2D> hull()


{
Stack<Point2D> s = new Stack<Point2D>();
for (Point2D p : hull)
s.push(p);
return s;
}

private boolean isConvex()


{
int N = hull.size();
if (N <= 2)
return true;

Point2D[] points = new Point2D[N];


int n = 0;
for (Point2D p : hull())
16 | P a g e
{
points[n++] = p;
}

for (int i = 0; i < N; i++)


{
if (Point2D
.ccw(points[i], points[(i + 1) % N], points[(i +
2) % N]) <= 0)
{
return false;
}
}
return true;
}

// test client
public static void main(String[] args)
{
System.out.println("Graham Scan Test");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of points");
int N = sc.nextInt();

Point2D[] points = new Point2D[N];


System.out.println("Enter the coordinates of each
points: <x> <y>");
for (int i = 0; i < N; i++)
{
int x = sc.nextInt();
int y = sc.nextInt();
points[i] = new Point2D(x, y);
}
GrahamScan graham = new GrahamScan(points);
System.out.println("The convex hull consists of
following points: ");
17 | P a g e
for (Point2D p : graham.hull())
System.out.println(p);
sc.close();
}}
2.4 Output:

18 | P a g e
Assignment 3

3.1 Problem Statement: Write an interactive program that


would implement closest pair problem.
1.2 Algorithm: We are given an array of n points in the plane, and
the problem is to find out the closest pair of points in the array. This
problem arises in a number of applications. For example, in air-traffic
control, you may want to monitor planes that come too close together,
since this may indicate a possible collision. Recall the following formula
for distance between two points p and q.

The Brute force solution is O(n^2), compute the distance between each
pair and return the smallest. We can calculate the smallest distance in
O(nLogn) time using Divide and Conquer strategy.

19 | P a g e
Algorithm:
Input: An array of n points P[]
Output: The smallest distance between two points in the given array.
As a pre-processing step, input array is sorted according to x coordinates.
Step 1: Find the middle point in the sorted array, we can take P[n/2] as
middle point.
Step 2: Divide the given array in two halves. The first subarray contains
points from P[0] to P[n/2]. The second subarray contains points from
P[n/2+1] to P[n-1].
Step 3: Recursively find the smallest distances in both subarrays. Let the
distances be dl and dr. Find the minimum of dl and dr. Let the minimum
be d.

Step 4: From above 3 steps, we have an upper bound d of minimum


distance. Now we need to consider the pairs such that one point in pair is
from left half and other is from right half. Consider the vertical line
passing through passing through P[n/2] and find all points whose x
coordinate is closer than d to the middle vertical line. Build an array
strip[] of all such points.

20 | P a g e
Step 5: Sort the array strip[] according to y coordinates. This step is
O(nLogn). It can be optimized to O(n) by recursively sorting and merging.
Step 6: Find the smallest distance in strip[]. This is tricky. From first look,
it seems to be a O(n^2) step, but it is actually O(n). It can be proved
geometrically that for every point in strip, we only need to check at most 7
points after it (note that strip is sorted according to Y coordinate).
See this for more analysis.
Step 7: Finally return the minimum of d and distance calculated in above
step (step 6)

3.3 Program:
The algorithm has been implemented using JAVA
programming language.
File: ClosestPair.java
import java.util.*;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.Arrays;
import java.util.Scanner;

21 | P a g e
public class ClosestPair {
// Each row in points represents a point
private double[][] points;
Point p1, p2;
public static void main(String[] args) {
int number=0;
Scanner scan = new Scanner( System.in );
System.out.println( "Enter number of points: " );
number = scan.nextInt();
double[][] points = new double[number][2];
for (int i = 0; i < number; i++) {
System.out.println( "Enter the x-coordinate for point "
+ ( i + 1 ) );
points[i][0] = scan.nextInt();
System.out.println( "Enter the y-coordinate for point "
+ ( i + 1 ) );
points[i][1] = scan.nextInt();
}
ClosestPair closestPair = new ClosestPair(points);
System.out.println("shortest distance is " +
closestPair.getMinimumDistance());
System.out.print("(" + closestPair.p1.x + ", " +
closestPair.p1.y + ") to ");
System.out.println("(" + closestPair.p2.x + ", " +
closestPair.p2.y + ")");
}
ClosestPair() {
}
public ClosestPair(double[][] points) {
setPoints(points);
}
public void setPoints(double[][] points) {
this.points = points;
}
public double getMinimumDistance() {
Point[] pointsOrderedOnX = new Point[points.length];
22 | P a g e
for (int i = 0; i < pointsOrderedOnX.length; i++)
pointsOrderedOnX[i] = new Point(points[i][0], points[i]
[1]);
Arrays.sort(pointsOrderedOnX);
// Locate the identical points if exists
if (checkIdentical(pointsOrderedOnX))
return 0; // The distance between the identical points is
0
Point[] pointsOrderedOnY = pointsOrderedOnX.clone();
Arrays.sort(pointsOrderedOnY, new CompareY());

return distance(pointsOrderedOnX, 0,
pointsOrderedOnX.length - 1, pointsOrderedOnY);
}
public boolean checkIdentical(Point[] pointsOrderedOnX)
{
for (int i = 0; i < pointsOrderedOnX.length - 1; i++) {
if (pointsOrderedOnX[i].compareTo(pointsOrderedOnX[i
+ 1]) == 0) {
p1 = pointsOrderedOnX[i];
p2 = pointsOrderedOnX[i + 1];
return true;
}
}

return false;
}
public double distance(
Point[] pointsOrderedOnX, int low, int high,
Point[] pointsOrderedOnY) {
if (low >= high) // Zero or one point in the set
return Double.MAX_VALUE;
else if (low + 1 == high) {
// Two points in the set
p1 = pointsOrderedOnX[low];
p2 = pointsOrderedOnX[high];
23 | P a g e
return distance(pointsOrderedOnX[low],
pointsOrderedOnX[high]);
}
int mid = (low + high) / 2;
Point[] pointsOrderedOnYL = new Point[mid - low + 1];
Point[] pointsOrderedOnYR = new Point[high - mid];
int j1 = 0; int j2 = 0;
for (int i = 0; i < pointsOrderedOnY.length; i++) {
if
(pointsOrderedOnY[i].compareTo(pointsOrderedOnX[mid])
<= 0)
pointsOrderedOnYL[j1++] = pointsOrderedOnY[i];
else
pointsOrderedOnYR[j2++] = pointsOrderedOnY[i];
}
// Recursively find the distance of the closest pair in the
left
// half and the right half
double d1 = distance(
pointsOrderedOnX, low, mid, pointsOrderedOnYL);
double d2 = distance(
pointsOrderedOnX, mid + 1, high, pointsOrderedOnYR);
double d = Math.min(d1, d2);
// stripL: the points in pointsOrderedOnYL within the strip
d
int count = 0;
for (int i = 0; i < pointsOrderedOnYL.length; i++)
if (pointsOrderedOnYL[i].x >=
pointsOrderedOnX[mid].x - d)
count++;
Point[] stripL = new Point[count];
count = 0;
for (int i = 0; i < pointsOrderedOnYL.length; i++)
if (pointsOrderedOnYL[i].x >=
pointsOrderedOnX[mid].x - d)
stripL[count++] = pointsOrderedOnYL[i];
24 | P a g e
count = 0;
for (int i = 0; i < pointsOrderedOnYR.length; i++)
if (pointsOrderedOnYR[i].x <=
pointsOrderedOnX[mid].x + d)
count++;
Point[] stripR = new Point[count];
count = 0;
for (int i = 0; i < pointsOrderedOnYR.length; i++)
if (pointsOrderedOnYR[i].x <=
pointsOrderedOnX[mid].x + d)
stripR[count++] = pointsOrderedOnYR[i];
// Find the closest pair for a point in stripL and
// a point in stripR
double d3 = d;
int j = 0;
for (int i = 0; i < stripL.length; i++) {
while (j < stripR.length && stripL[i].y > stripR[j].y + d)
j++;
int k = j; // Start from r1 up in stripR
while (k < stripR.length && stripR[k].y <= stripL[i].y +
d) {
if (d3 > distance(stripL[i], stripR[k])) {
d3 = distance(stripL[i], stripR[k]);
p1 = stripL[i];
p2 = stripR[k];
}
k++;
}
}
return Math.min(d, d3);
}
public static double distance(Point p1, Point p2) {
return distance(p1.x, p1.y, p2.x, p2.y);
}
public static double distance(
double x1, double y1, double x2, double y2) {
25 | P a g e
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 -
y1));
}
static class Point implements Comparable<Point> {
double x;
double y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
public int compareTo(Point p2) {
if (this.x < p2.x)
return -1;
else if (this.x == p2.x) {
// Secondary order on y-coordinates
if (this.y < p2.y)
return -1;
else if (this.y == p2.y)
return 0;
else
return 1;
}
else
return 1;
}
}
static class CompareY implements
java.util.Comparator<Point> {
public int compare(Point p1, Point p2) {
if (p1.y < p2.y)
return -1;
else if (p1.y == p2.y) {
// Secondary order on x-coordinates
if (p1.x < p2.x)
return -1;
else if (p1.x == p2.x)
26 | P a g e
return 0;
else
return 1;
}
else
return 1;
}
}
}

3.4 Output:

27 | P a g e
28 | P a g e
Assignment 4

4.1 Problem Statement: Write a program to find as


many prime fibonacci numbers as possible.
4.2 Algorithm: Fibonacci series is defined as a
sequence of numbers in which the first two numbers are 1
and 1, or 0 and 1, depending on the selected beginning
point of the sequence, and each subsequent number is the
sum of the previous two. So, in this series, the n th term is
the sum of (n-1)th term and (n-2)th term. In this tutorial,
were going to discuss a simple algorithm and flowchart for
Fibonacci series along with a brief introduction to Fibonacci
Series and some of its important properties .
Fibonacci series generates the subsequent number by adding two
previous numbers. Fibonacci series starts from two numbers F0 &
F1. The initial values of F0 & F1 can be taken 0, 1 or 1, 1 respectively.
Fibonacci series satisfies the following conditions

Fn = Fn-1 + Fn-2
Fibonacci iterative algorithm:
Procedure Fibonacci(n)
declare f0, f1, fib, loop
set f0 to 0
set f1 to 1
display f0, f1
for loop 1 to n
fib f0 + f1
f0 f1
f1 fib
display fib
29 | P a g e
end for
end procedure
Any whole number which is greater than 1 and has only
two factors that is 1 and the number itself, is called a
prime number. Other than these two number it has no
positive divisor.
Prime number testing algorithm:
START
Step 1 Take integer variable A
Step 2 Divide the variable A with (A-1 to 2)
Step 3 If A is divisible by any value (A-1 to 2) it is not
prime
Step 4 Else it is prime
STOP
Algorithm for finding prime fibonacci:
Procedure PrimeFibonacci(n)
declare f0, f1, fib, loop
set f0 to 0
set f1 to 1
display f0, f1
for loop 1 to n
fib f0 + f1
f0 f1
f1 fib
if fib is prime then
display fib
end for
end procedure
30 | P a g e
4.3 Program:
The algorithm has been implemented using JAVA
programming language.
File: PrimeFibo.java
import java.util.Scanner;
public class PrimeFibo
{
static int n1=0,n2=1,n3=0;
static void printFibonacci(long number)
{
long a = -1;
long b = 1;
long c = 0;
for(long i=1; i<=number; i++)
{
c = a + b;
long temp = a;
a = b;
b = c;
long t=isPrime(c);
if(t==0 && (c != 0 && c != 1))
System.out.println("T("+i+") :"+c+" is
prime");
else
System.out.println("T("+i+") :"+c);
}
}
static long isPrime(long n)
{
long i,m=0,flag=0;
31 | P a g e
m=n/2;
for(i=2;i<=m;i++)
{
if(n%i==0)
{
flag=1;
break;

}
}
return flag;
}
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the uppermost Nth term : ");
long limit = Integer.parseInt(scan.nextLine());
System.out.println("The Fibonacci Series are : ");
printFibonacci(limit);
}
}

32 | P a g e
4.4 Output:

33 | P a g e
34 | P a g e
35 | P a g e
36 | P a g e

Vous aimerez peut-être aussi