0% found this document useful (0 votes)
6 views

Assignment3_AkshayBhat

The project focuses on designing a network topology that ensures all nodes are connected with a minimum degree of three and a maximum diameter of four, while minimizing the total geometric length of links. Two heuristic algorithms, Local Search and Constructive Heuristic, are implemented and tested across multiple experiments to evaluate their effectiveness in achieving the project's objectives. Results indicate that the Constructive Heuristic algorithm is faster and more efficient than the Local Search algorithm in reducing costs.

Uploaded by

jsanthoshithota
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Assignment3_AkshayBhat

The project focuses on designing a network topology that ensures all nodes are connected with a minimum degree of three and a maximum diameter of four, while minimizing the total geometric length of links. Two heuristic algorithms, Local Search and Constructive Heuristic, are implemented and tested across multiple experiments to evaluate their effectiveness in achieving the project's objectives. Results indicate that the Constructive Heuristic algorithm is faster and more efficient than the Local Search algorithm in reducing costs.

Uploaded by

jsanthoshithota
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

ALGORITHMIC ASPECTS OF

TELECOMMUNICATION NETWORKS
CS 6385.0W1

PROJECT #3
NETWORK TOPOLOGY
DESIGN

Submitted by
Akshay Bhat
ID: 2021319198
Netid: axb163530

1
CONTENTS

OBJECTIVE.............................................................................................................................. 3

NETWORK TOPOLOGY......................................................................................................... 3

ALGORITHMS…………………………………..………………………………4

RESULTS .................................................................................................................................. 6

OBSERVATION AND CONCLUSION ........................................................................... 22

APPENDIX ................................................................................................................................ 23

README .................................................................................................................................... 38

2
OBJECTIVE
The aim of the project is to create a network topology (represented by an undirected graph),
such that it has the following properties:

1. It contains all the given nodes.


2. The degree of each vertex in the graph is at least 3, that is, each node is connected to at
least 3 other nodes.
3. The diameter of the graph is at most 4. By this we mean that any node can be reached from
any other node in at most 4 hops. (This can be checked by any shortest path algorithm, or by
running a breadth-first search from every node.) That is, the diameter in our case refers to
the hop-distance, not to any kind of geometric distance. Note that this diameter bound implies
that the graph must be connected.
4. The total cost of the network topology is as low as possible, where the cost is measured by
the total geometric length of all links. This means, you have compute how long each link is
geometrically (that is, how far apart are its end-nodes), and then sum it up for all links that
exist in the network. This sum represents the total cost that we would like to minimize.

The goal is to create and implement two different heuristic algorithms for this
network topology design problem, and experiment with them

NETWORK TOPOLOGY:

Graphs have some properties that are very useful when unravelling the information that they
contain. It is important to realise that the purpose of any type of network analysis is to work
with the complexity of the network to extract meaningful information that you would not
have if the individual components were examined separately.

Network properties, and particularly topological properties, can help us identify relevant sub-
structures within a network.
Topology is the way in which the nodes and edges are arranged within a network.
Topological properties can apply to the network as a whole or to individual nodes and edges.
Network topology is the arrangement of the elements of a communication network.

Network topology is the topological structure of a network and may be depicted physically or
logically. It is an application of graph theory wherein communicating devices are modeled as
nodes and the connections between the devices are modeled as links or lines between the
nodes. Distances between nodes, physical interconnections, transmission rates, or signal
types may differ between two different networks, yet their topologies may be identical.
Network topology can be used to define or describe the arrangement of various types of
telecommunication networks, including command and control radio networks, industrial
fieldbusses, and computer networks.

3
ALGORITHMS:

1. Local Search Heuristic Algorithm

Local search is a heuristic method for solving computationally hard optimization problems.
Local search can be used on problems that can be formulated as finding a solution
maximizing a criterion among a number of candidate solutions. Local search algorithms
move from solution to solution in the space of candidate solutions (the search space) by
applying local changes, until a solution deemed optimal is found or a time bound is elapsed.

Local search is based on the oldest optimization method: trial and error. To systematize the
search a neighborhood structure is defined and build. The neighborhood of a given solution is
the set of feasible solutions that, somehow, are alike the given solution, i.e. com similar
elements and objective function values not very different.

Generic local search algorithm:


1. Generate an initial solution → s0.
2. Current solution si = s0.
3. Pick sj ∈ V (si).
4. If f(sj) < f(si), then si = sj .
5. Else, V (si) = V (si) − sj .
6. If V (si) 6= ∅, then go to 3.
7. Else, END.
Local optimal solution = si.
We say that a “movement” has happened each time a new solution is accepted as current
solution.
Local search procedure usually consists of the following steps.
1. Initialisation. Choose an initial schedule S to be the current solution and compute the
value of the objective function F(S).
2. Neighbour Generation. Select a neighbour S’ of the current solution S and compute F(S’).
3. Acceptance Test. Test whether to accept the move from S to S’. If the move is accepted,
then S’ replaces S as the current solution; otherwise S is retained as the current
solution.
4. Termination Test. Test whether the algorithm should terminate. If it terminates, output the
best solution generated; otherwise, return to the neighbour generation step.

2. Constructive Heuristic Algorithm

A constructive heuristic is a type of heuristic method which starts with an empty solution and
repeatedly extends the current solution until a complete solution is obtained. It differs from
local search heuristics which start with a complete solution and then try to improve the
current solution further via local moves.
It is essential to know the difference between:
a. Constructive methods
Extend empty solution until get complete solution
b. Local search
4
Take complete solution and try to improve it via local moves

Constructive heuristics generally give better answers than random methods


Very quick, but usually far from optimal
Widely used with other methods
Often used as initialization for meta-heuristics
Pick the best solution from several runs

Pseudo-code
A constructive algorithm (for minimization) can be described as follows:

Algorithm Greedy(I)
x := ∅;
x∗:= ∅;
f∗:= +∞; { Best incumbent solution }
While Ext(x) 6= ∅ do
i := arg min
i∈Ext(x)
φ (i, x);
x := x ∪ {i};
If x ∈ X and f (x) < f∗
then x∗:= x;
f∗:= f (x);
Return (x∗, f∗);

A constructive heuristic finds the optimum when the current subset x(t) at every iteration t is
contained in an optimal solution. This property is valid for x(0) = ∅, but is usually lost in
some later iteration t.
A constructive heuristic executes at most n = |E| iterations.
The complexity of each step is affected by
1. the computation of Ext(x);
2. the evaluation of φ (i, x) for each i ∈ Ext(x);
3. the selection of the minimum value and the corresponding element;
4. the update of x (and possibly other data-structures).

Constructive heuristics
1. are intuitive;
2. are rather simple to design, analyze and implement;
3. are very efficient
4. can be very different in effectiveness according to the different problems.
• optimality is guaranteed
• approximation is guaranteed
• feasible solution is guaranteed, but unreliable quality (most cases);
• no feasible solution is guaranteed.

5
RESULTS

a) Experiment-1

The points and their coordinates are:


Point number 0 is: (49,10)
Point number 1 is: (17,9)
Point number 2 is: (2,71)
Point number 3 is: (14,33)
Point number 4 is: (72,75)
Point number 5 is: (1,89)
Point number 6 is: (5,18)
Point number 7 is: (70,37)
Point number 8 is: (91,12)
Point number 9 is: (58,94)
Point number 10 is: (94,10)
Point number 11 is: (72,96)
Point number 12 is: (59,7)
Point number 13 is: (72,45)
Point number 14 is: (34,37)
Point number 15 is: (50,10)
Point number 16 is: (9,74)
Point number 17 is: (4,76)
Point number 18 is: (49,25)

The adjacency matrix denoting the node and the edges are:

6
The network topology graph is:

The result:

7
b. Experiment-2

The points are:


Point number 0 is: (97,3)
Point number 1 is: (47,88)
Point number 2 is: (45,59)
Point number 3 is: (55,16)
Point number 4 is: (86,12)
Point number 5 is: (25,49)
Point number 6 is: (90,18)
Point number 7 is: (34,26)
Point number 8 is: (74,15)
Point number 9 is: (32,28)
Point number 10 is: (21,81)
Point number 11 is: (8,49)
Point number 12 is: (57,59)
Point number 13 is: (62,64)
Point number 14 is: (41,63)
Point number 15 is: (75,77)
Point number 16 is: (48,86)
Point number 17 is: (46,28)
Point number 18 is: (64,68)

8
Adjacency matrix is:

Graph is:

9
The result:

c. Experiment-3

Points are:
Point number 0 is: (6,77)
Point number 1 is: (89,83)
Point number 2 is: (50,56)
Point number 3 is: (58,63)
Point number 4 is: (36,35)
Point number 5 is: (12,80)
Point number 6 is: (87,30)
Point number 7 is: (18,58)
10
Point number 8 is: (83,50)
Point number 9 is: (26,98)
Point number 10 is: (91,53)
Point number 11 is: (75,98)
Point number 12 is: (71,55)
Point number 13 is: (74,2)
Point number 14 is: (36,43)
Point number 15 is: (13,55)
Point number 16 is: (58,82)
Point number 17 is: (5,12)
Point number 18 is: (32,56)

Adjacency matrix is:

Graph is:

11
The result:

12
d. Experiment-4

Points are:
Point number 0 is: (22,56)
Point number 1 is: (89,6)
Point number 2 is: (45,97)
Point number 3 is: (96,92)
Point number 4 is: (8,11)
Point number 5 is: (23,36)
Point number 6 is: (71,24)
Point number 7 is: (95,66)
Point number 8 is: (60,12)
Point number 9 is: (97,37)
Point number 10 is: (7,64)
Point number 11 is: (19,36)
Point number 12 is: (18,19)
Point number 13 is: (41,93)
Point number 14 is: (8,65)
Point number 15 is: (9,11)
Point number 16 is: (18,61)
Point number 17 is: (52,61)
Point number 18 is: (4,38)

13
Adjacency matrix is:

Graph is:

14
The result:

15
e. Experiment-5

Points are:
Point number 0 is: (66,10)
Point number 1 is: (84,99)
Point number 2 is: (79,60)
Point number 3 is: (5,33)
Point number 4 is: (7,13)
Point number 5 is: (6,59)
Point number 6 is: (92,0)
Point number 7 is: (6,86)
Point number 8 is: (45,42)
Point number 9 is: (28,3)
Point number 10 is: (36,59)
Point number 11 is: (32,66)
Point number 12 is: (17,63)
Point number 13 is: (25,12)
Point number 14 is: (79,34)
Point number 15 is: (7,68)
Point number 16 is: (77,89)
Point number 17 is: (47,1)
Point number 18 is: (21,52)

16
Adjacency matrix is:

Graph is:

17
The result:

18
f. Experiment-6

Points are:
Point number 0 is: (62,4)
Point number 1 is: (25,34)
Point number 2 is: (56,72)
Point number 3 is: (16,9)
Point number 4 is: (86,16)
Point number 5 is: (56,43)
Point number 6 is: (95,0)
Point number 7 is: (18,54)
Point number 8 is: (99,95)
Point number 9 is: (32,96)
Point number 10 is: (49,86)
Point number 11 is: (75,66)
Point number 12 is: (4,82)
Point number 13 is: (26,66)
Point number 14 is: (2,36)
Point number 15 is: (99,73)
Point number 16 is: (44,93)
Point number 17 is: (75,78)
Point number 18 is: (84,45)

19
Adjacency matrix is:

Graph is:

20
The result:

21
OBSERVATION AND CONCLUSION:

We see that Constructive heuristic algorithm is way faster than local search and gives results
quickly. In each experiment, we see that after each iteration, the cost of both algorithm
decreases and the final value is less than the starting cost.

References:
1. www.wikipedia.com
2. Lecture notes
3. https://homes.di.unimi.it/righini/Didattica/AlgoritmiEuristici/MaterialeAE/6%20-
%20Constructive%20algorithms.pdf
4. http://www.cs.nott.ac.uk/~pszrq/files/2AIMconstruct.pdf
5. http://graphonline.ru/en/

22
APPENDIX

Algorithm1_ConstructiveHeuristics.java

package assignment3atn;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Algorithm1_ConstructiveHeuristics


{
public static void init(int n, HashMap<Integer, CoordinatePoints> points)
{
int[][] adjmatrix = new int[n][n];
List<Node_Edge> edge = new ArrayList<Node_Edge>();

/*Generates an empty graph*/


Graph graph = Graph_Impl.generateEmptyGraph(n ,points);
graph.setAdjMatrix(adjmatrix);

/*Generates edges */
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i<j)
{
edge.add(new Node_Edge(i, j, Graph_Impl.getEdgeWeight(i, j,
points)));
}
}
}

/*Sort the edge cost in ascending order*/


Collections.sort(edge);

/*Check the conditions (1),(2) and (3) of pdf i.e all the nodes are connected, degree is at least
3 and diameter is at most 4*/
boolean isNodeConnected = new CheckConnection_Nodes(graph).isNodeConnected();
boolean isAtLeastDegreeThree = Graph_Impl.isDegreeThree(graph, 3);
boolean isAtMostDiameterFour = Graph_Impl.isDiameterFour(graph, 4);
boolean allThreeConditionsSatisfied = isNodeConnected && isAtLeastDegreeThree &&
isAtMostDiameterFour;
double currCost = Double.POSITIVE_INFINITY;
System.out.println("Constructive Current Cost [fully disconnected]: " + currCost);

for (Node_Edge edg : edge)


{
int i = edg.getNodei();
int j = edg.getNodej();
graph.getAdjMatrix()[i][j] = 1;
graph.getAdjMatrix()[j][i] = 1;

isNodeConnected = new CheckConnection_Nodes(graph).isNodeConnected();


isAtLeastDegreeThree = Graph_Impl.isDegreeThree(graph, 3);
isAtMostDiameterFour = Graph_Impl.isDiameterFour(graph, 4);
allThreeConditionsSatisfied = isNodeConnected && isAtLeastDegreeThree &&
isAtMostDiameterFour;

//System.out.println("isNodeConnected: "+isNodeConnected);
//System.out.println("isAtLeastDegreeThree: "+isAtLeastDegreeThree);
//System.out.println("isAtMostDiameterFour: "+isAtMostDiameterFour);
23
//System.out.println("allThreeConditionsSatisfied: "+allThreeConditionsSatisfied);

if(allThreeConditionsSatisfied)
{
currCost = Graph_Impl.getCost(graph);
System.out.println("Constructive Current Cost [max] -> " + currCost);
break;
}
}

/*Track and save the edges that cannot be removed*/


HashSet<String> unremovableEdges = new HashSet<String>();

while(true)
{
/*Find the edge that has the maximum weight else break*/
List<Node_Edge> edg = graph.edges();
double wt = 0.0;
Node_Edge heaviestEdge = null;
for (Node_Edge ed : edg)
{
if(wt < ed.getWeight() && !unremovableEdges.contains(ed.getNodei() + ""
+ ed.getNodej()) && !unremovableEdges.contains(ed.getNodej() + "" + ed.getNodei()))
{
wt = ed.getWeight();
heaviestEdge = ed;
}
}

if(heaviestEdge==null)
{
break;
}
graph.getAdjMatrix()[heaviestEdge.getNodei()][heaviestEdge.getNodej()] = 0;
graph.getAdjMatrix()[heaviestEdge.getNodej()][heaviestEdge.getNodei()] = 0;

/*Check if all the 3 conditions satisfy*/


isNodeConnected = new CheckConnection_Nodes(graph).isNodeConnected();
isAtLeastDegreeThree = Graph_Impl.isDegreeThree(graph, 3);
isAtMostDiameterFour = Graph_Impl.isDiameterFour(graph, 4);
allThreeConditionsSatisfied = isNodeConnected && isAtLeastDegreeThree &&
isAtMostDiameterFour;

if(allThreeConditionsSatisfied)
{

currCost = Graph_Impl.getCost(graph);
System.out.println("Constructive Current Cost -> " + currCost);
}
else
{
graph.getAdjMatrix()[heaviestEdge.getNodei()][heaviestEdge.getNodej()] = 1;
graph.getAdjMatrix()[heaviestEdge.getNodej()][heaviestEdge.getNodei()] = 1;
unremovableEdges.add(heaviestEdge.getNodei() + "" + heaviestEdge.getNodej());
unremovableEdges.add(heaviestEdge.getNodej() + "" + heaviestEdge.getNodei());
}
}

}
}

Algorithm2_LocalSearch.java

package assignment3atn;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
24
import java.util.HashSet;
import java.util.List;

public class Algorithm2_LocalSearch


{

public static void init(int n, HashMap<Integer, CoordinatePoints> points)


{
/*Generate a fully connected graph and check if it satisfies all the 3 conditions*/
Graph graph = Graph_Impl.generateFullyConnectedGraph(n, points);

boolean isNodeConnected = new CheckConnection_Nodes(graph).isNodeConnected();


boolean isAtLeastDegreeThree = Graph_Impl.isDegreeThree(graph, 3);
boolean isAtMostDiameterFour = Graph_Impl.isDiameterFour(graph, 4);
boolean allThreeConditionsSatisfied = isNodeConnected && isAtLeastDegreeThree &&
isAtMostDiameterFour;

HashSet<String> unremovableEdges = new HashSet<String>();


double currentCost = Graph_Impl.getCost(graph);
System.out.println("Local Search Current Cost [fully connected] -> " + currentCost);

while(true)
{
/*Finds an edge with the largest weight and remove it else break*/
List<Node_Edge> edges = graph.edges();
double weight = 0.0;
Node_Edge heaviestEdge = null;
for (Node_Edge edge : edges)
{
if(weight < edge.getWeight() &&
!unremovableEdges.contains(edge.getNodei() + "" + edge.getNodej()) &&
!unremovableEdges.contains(edge.getNodej() + "" + edge.getNodei()))
{
weight = edge.getWeight();
heaviestEdge = edge;
}
}

if(heaviestEdge==null)
{
break;
}

graph.getAdjMatrix()[heaviestEdge.getNodei()][heaviestEdge.getNodej()] = 0;
graph.getAdjMatrix()[heaviestEdge.getNodej()][heaviestEdge.getNodei()] = 0;

isNodeConnected = new CheckConnection_Nodes(graph).isNodeConnected();


isAtLeastDegreeThree = Graph_Impl.isDegreeThree(graph, 3);
isAtMostDiameterFour = Graph_Impl.isDiameterFour(graph, 4);
allThreeConditionsSatisfied = isNodeConnected && isAtLeastDegreeThree &&
isAtMostDiameterFour;

if(allThreeConditionsSatisfied)
{
currentCost = Graph_Impl.getCost(graph);
int matrix[][] = graph.getAdjMatrix();
System.out.println("Adjancey matrix");
for(int k=0;k<matrix.length;k++)
{
//System.out.println("Adjancey matrix for " +k);
for (int h=0;h<matrix.length;h++)
{
//if(matrix[k][h]==1)
//System.out.println("with edge for " +h);

System.out.print(matrix[k][h] + ",");
}
25
System.out.println();
}
System.out.println("Local Search Current Cost -> " + currentCost);

}
else
{
graph.getAdjMatrix()[heaviestEdge.getNodei()][heaviestEdge.getNodej()] = 1;
graph.getAdjMatrix()[heaviestEdge.getNodej()][heaviestEdge.getNodei()] = 1;
unremovableEdges.add(heaviestEdge.getNodei() + "" + heaviestEdge.getNodej());
unremovableEdges.add(heaviestEdge.getNodej() + "" + heaviestEdge.getNodei());
}
}
}
}

Algorithms_Impl.java

package assignment3atn;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class Algorithms_Impl


{
/*Lets take 6 examples here*/
private static int numberOfExamples = 6;

/*Take n random points in the plane; n >= 15; lets take n = 19 here*/
private static int n = 18;
public static int x,y;
public static long Algo1Time1, Algo1Time2, Algo2Time1, Algo2Time2;
public static PQImpl<Double> pqMin;
public static void main(String[] args)
{
for(int ex=0;ex<numberOfExamples;ex++)
{
System.out.println("Experiment Number: "+(ex+1)+" starts here:");
HashMap<Integer, CoordinatePoints> points = new HashMap<Integer,
CoordinatePoints>();
NumberFormat nf = NumberFormat.getInstance();

/*Creates n number of points on plane by generating x and y coordinates from 0-


100*/
for(int i=0;i<=n;i++)
{
x = (int)(Math.random()*(100));
y = (int)(Math.random()*(100));
points.put(i, new CoordinatePoints(x, y));
//System.out.println("points: "+points.get(i));
}

for(Map.Entry<Integer, CoordinatePoints> entry: points.entrySet())


{
int key = entry.getKey();
CoordinatePoints value = entry.getValue();
System.out.println("Point number "+(key)+" is:
"+"("+(value.x)+","+(value.y)+")");
}

/*Running the Local Search Heuristic Algorithm*/


Algo1Time1 = System.currentTimeMillis();
Algorithm2_LocalSearch.init(n, points);
Algo1Time2 = System.currentTimeMillis();
System.out.println("The running time of Local Search Heuristic Algorithm:
"+(Algo1Time2-Algo1Time1)+" ms");
26
//run Constructive Heuristic Algorithm
Algo2Time1 = System.currentTimeMillis();
Algorithm1_ConstructiveHeuristics.init(n, points);
Algo2Time2 = System.currentTimeMillis();
System.out.println("The running time of Constructive Heuristic Algorithm:
"+(Algo2Time2-Algo2Time1)+" ms");

System.out.println("Experiment Number: "+(ex+1)+" ends here!");


}
}

CheckConnection_Nodes.java

package assignment3atn;

public class CheckConnection_Nodes


{
private boolean[] markVertex;
private int[] id;
private int[] size;
private int countConnections;

/*Checks a vertex is connected to how many other vertices*/


public CheckConnection_Nodes(Graph g)
{
markVertex = new boolean[g.nVertices()];
id = new int[g.nVertices()];
size = new int[g.nVertices()];
for (int i = 0; i < g.nVertices(); i++)
{
if (!markVertex[i])
{
DFS(g, i);
countConnections++;
}
}
}

/*Uses DFS to find the connections*/


public void DFS(Graph g, int i)
{
markVertex[i] = true;
id[i] = countConnections;
size[countConnections]++;
for (int j : g.adjacent(i))
{
if (!markVertex[j])
{
DFS(g, j);
}
}
}

/*Checks if all the nodes are connected*/


public boolean isNodeConnected()
{
if (countConnections == 1)
{
return true;
}
else
{
return false;
}
}

public int id(int i)


27
{
return id[i];
}

public int size(int i)


{
return size[id[i]];
}

public int countConnections()


{
return countConnections;
}

}
CoordinatesPoints.java

package assignment3atn;

public class CoordinatePoints


{
public int x;
public int y;

public CoordinatePoints(int x, int y)


{
this.x = x;
this.y = y;
}

public int getX()


{
return x;
}

public void setX(int x)


{
this.x = x;
}

public int getY()


{
return y;
}

public void setY(int y)


{
this.y = y;
}

DijkstraShortestPath.java

package assignment3atn;

import java.util.ArrayList;
import java.util.Vector;
import java.util.stream.Collectors;

public class DijkstraShortestPath


{
private Node_Edge[] edgeBtwn;
private double[] distBtwn;
private PQImpl<Double> pqMin;
public int count=0;

public double distBtwn(int i)


{
28
return distBtwn[i];
}

/*Checks the path between edges*/


public boolean hasPathTo(int i)
{
return distBtwn[i] < Double.POSITIVE_INFINITY;
}

/*Finds the Dijkstra's shortest path*/


public DijkstraShortestPath(Graph gg, int dt)
{
count++;
distBtwn = new double[gg.nVertices()];
edgeBtwn = new Node_Edge[gg.nVertices()];

for (int i=0;i<distBtwn.length;i++)


{
distBtwn[i]=Double.POSITIVE_INFINITY;
}

distBtwn[dt] = 0.0;
pqMin = new PQImpl<Double>(gg.nVertices());
pqMin.insert(dt, distBtwn[dt]);
// ArrayList<Integer> node_edge = new ArrayList<Integer>();
while (!pqMin.isEmpty())
{
int i = pqMin.delMin();

// if(!node_edge.contains(i)) {
// System.out.println("Adjacent edges of" + i + " are: " +
gg.adjacentEdges(i).stream().map(NodeEdge::getNodej).collect(Collectors.toList()));
// node_edge.add(i);
// }
for (Node_Edge e : gg.adjacentEdges(i))
{
relaxAndUpdate(e, i);
}
}
}

/*Relax an edge and updates its corresponding vertex*/


private void relaxAndUpdate(Node_Edge e, int i)
{
int j = e.other(i);
if (distBtwn[j] > distBtwn[i] + e.getWeight())
{
distBtwn[j] = distBtwn[i] + e.getWeight();
edgeBtwn[j] = e;
if (pqMin.contains(j))
{
pqMin.decreaseKey(j, distBtwn[j]);
}
else
{
pqMin.insert(j, distBtwn[j]);
}
}
}

Graph_Impl.java

package assignment3atn;

import java.util.HashMap;
29
public class Graph_Impl
{
/*Checks if the diameter of the graph is at most 4*/

public static boolean isDiameterFour(Graph graph, int hops)


{
Graph graphWithEqualDist = new Graph(graph.nVertices(), null);
int[][] adj = new int[graph.nVertices()][graph.nVertices()];
for(int i=0;i<graph.nVertices();i++)
{
for(int j=0;j<graph.nVertices();j++)
{
if(graph.getAdjMatrix()[i][j]==1)
{
adj[i][j] = 1;
}
}
}
graphWithEqualDist.setAdjMatrix(adj);

for (int i = 0; i < graphWithEqualDist.nVertices(); i++)


{
DijkstraShortestPath sp = new DijkstraShortestPath(graphWithEqualDist, i);
for (int j = 0; j < graphWithEqualDist.nVertices(); j++)
{
double d = sp.distBtwn(j);
//System.out.println("Distance between " + i + " & " + j + ": " + d);
if (d > 4.00)
{
return false;
}
}
}
return true;
}

/*Checks if each node is connected to at least 3 other nodes*/


public static boolean isDegreeThree(Graph g, int n)
{
for (int i=0;i<g.nVertices();i++)
{
if (g.degree(i)<3)
{
return false;
}
}
return true;
}

/*Generates a connected graph for the given nodes and points*/


public static Graph generateFullyConnectedGraph(int n, HashMap<Integer, CoordinatePoints> points)
{
Graph graph = new Graph(n, points);
int[][] adj = new int[n][n];
for(int i=0;i<adj.length;i++)
{
for(int j=0;j<adj.length;j++)
{
if(i!=j)
{
adj[i][j] = 1;
}
}
}
graph.setAdjMatrix(adj);
return graph;
}
30
/*Gives the cost of the graph*/
public static double getCost(Graph graph)
{
double wt = 0.0;
for(Node_Edge e: graph.edges())
{
wt = wt + e.getWeight();
}
return wt;
}

/*Generates an empty graph*/


public static Graph generateEmptyGraph(int n, HashMap<Integer, CoordinatePoints> points)
{
Graph graph = new Graph(n, points);
int[][] adj = new int[n][n];
graph.setAdjMatrix(adj);
return graph;
}

/*Get the edge weight between points*/


public static Double getEdgeWeight(int i, int j, HashMap<Integer, CoordinatePoints> points)
{
CoordinatePoints p1 = points.get(i);
CoordinatePoints p2 = points.get(j);
double x1 = p1.getX();
double x2 = p2.getX();
double y1 = p1.getY();
double y2 = p2.getY();
return Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2));
}
}

Graph.java

package assignment3atn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class Graph


{
private int nVertices;
private int[][] adjMatrix;
private HashMap<Integer, CoordinatePoints> points;

/*Generates a graph of n vertices*/


public Graph(int nVertices, HashMap<Integer, CoordinatePoints> points)
{
this.nVertices = nVertices;
this.adjMatrix = new int[nVertices][nVertices];
this.points = points;
}

public int nVertices()


{
return nVertices;
}

public void setAdjMatrix(int[][] adj)


{
this.adjMatrix = adj;
}

public int[][] getAdjMatrix()


31
{
return adjMatrix;
}

public HashMap<Integer, CoordinatePoints> getPoints()


{
return this.points;
}

/*Get all the edges*/


public List<Node_Edge> edges()
{
List<Node_Edge> edges = new ArrayList<Node_Edge>();
for(int i=0;i<nVertices;i++)
{
for(int j=0;j<nVertices;j++)
{
if(i<j && adjMatrix[i][j]==1)
{
edges.add(new Node_Edge(i, j, getWt(i, j)));
}
}
}
return edges;
}

/*Gets all the adjacent edges*/


public List<Node_Edge> adjacentEdges(int i)
{
List<Node_Edge> edges = new ArrayList<Node_Edge>();
for(int j=0;j<nVertices;j++)
{
if(adjMatrix[i][j]==1)
{
edges.add(new Node_Edge(i, j, getWt(i, j)));
}
}
//System.out.println("edges:
"+edges.stream().map(NodeEdge::getNodei).collect(Collectors.toList()));
return edges;
}

/*Returns edge weight*/


private Double getWt(int i, int j)
{
if(this.points==null)
return 1.0;
CoordinatePoints p1 = points.get(i);
CoordinatePoints p2 = points.get(j);
double x1 = p1.getX();
double x2 = p2.getX();
double y1 = p1.getY();
double y2 = p2.getY();
return Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2));
}

/*Returns vertex degree*/


public int degree(int i)
{
int sum=0;
for(int j=0;j<nVertices;j++)
{
sum=sum+adjMatrix[i][j];
}
return sum;
}

/*Returns the adjacent vertex*/


public List<Integer> adjacent(int i)
{
32
List<Integer> list = new ArrayList<Integer>();
for(int j=0;j<this.nVertices;j++)
{
if(adjMatrix[i][j]==1)
{
list.add(j);
}
}
return list;
}
}

Node_Edge.java

package assignment3atn;

//Creates an edge between two nodes in the graph


public class Node_Edge implements Comparable<Node_Edge>
{
private int nodei;
private int nodej;
private double weight;

public Node_Edge(int i, int j, double wt)


{
this.nodei = i;
this.nodej = j;
this.weight = wt;
}

public void setNodei(int i)


{
this.nodei = i;
}

public void setNodej(int j)


{
this.nodej = j;
}

public void setWeight(double wt)


{
this.weight = wt;
}

public int getNodei()


{
return nodei;
}

public int getNodej()


{
return nodej;
}

public double getWeight()


{
return weight;
}

public int other(int i)


{
if(i==this.nodei)
{
return this.nodej;
}
else if(i==this.nodej)
{
return this.nodei;
}
33
else
{
return -1;
}
}

//Compares the edge weight of two nodes


@Override
public int compareTo(Node_Edge e)
{
if(this.getWeight() > e.getWeight())
{
return +1;
}
else if(this.getWeight() == e.getWeight())
{
return 0;
}
else
{
return -1;
}
}

PQImpl.java

package assignment3atn;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class PQImpl<Key extends Comparable<Key>> implements Iterable<Integer>


{
private int maxN;
private int n;
private int[] pq;
private int[] qp;
private Key[] keys;

/*Initializes an empty indexed priority queue*/


public PQImpl(int maxN)
{
if (maxN < 0)
throw new IllegalArgumentException();
this.maxN = maxN;
n = 0;
keys = (Key[]) new Comparable[maxN + 1]; // make this of length maxN??
pq = new int[maxN + 1];
qp = new int[maxN + 1];
for (int i = 0; i <= maxN; i++)
qp[i] = -1;
}

/*Returns true if this priority queue is empty*/


public boolean isEmpty()
{
return n == 0;
}

/*Compares index */
public boolean contains(int i)
{
if (i < 0 || i >= maxN)
throw new IndexOutOfBoundsException();
return qp[i] != -1;
}

34
/*Gives the number of keys */
public int size()
{
return n;
}

/*Checks the item linked with the index*/


public void insert(int i, Key key)
{
if (i < 0 || i >= maxN)
throw new IndexOutOfBoundsException();
if (contains(i))
throw new IllegalArgumentException("index is already in the priority queue");
n++;
qp[i] = n;
pq[n] = i;
keys[i] = key;
swim(n);
}

/*Gives the item with minimum element*/


public int minIndex()
{
if (n == 0)
throw new NoSuchElementException("Priority queue underflow");
return pq[1];
}

/*Gives the minimum key*/


public Key minKey()
{
if (n == 0)
throw new NoSuchElementException("Priority queue underflow");
return keys[pq[1]];
}

/*Removes a minimum key and returns its associated index*/


public int delMin()
{
if (n == 0)
throw new NoSuchElementException("Priority queue underflow");
int min = pq[1];
exch(1, n--);
sink(1);
assert min == pq[n + 1];
qp[min] = -1; // delete
keys[min] = null; // to help with garbage collection
pq[n + 1] = -1; // not needed
return min;
}

/*Returns the key associated with index*/


public Key keyOf(int i)
{
if (i < 0 || i >= maxN)
throw new IndexOutOfBoundsException();
if (!contains(i))
throw new NoSuchElementException("index is not in the priority queue");
else
return keys[i];
}

/*Change the key associated with index i to the specified value*/


public void changeKey(int i, Key key)
{
if (i < 0 || i >= maxN)
throw new IndexOutOfBoundsException();
if (!contains(i))
throw new NoSuchElementException("index is not in the priority queue");
keys[i] = key;
35
swim(qp[i]);
sink(qp[i]);
}

/*Change the key associated with index i to the specified value*/


public void change(int i, Key key)
{
changeKey(i, key);
}

/*Decrease the key associated with index i to the specified value*/


public void decreaseKey(int i, Key key)
{
if (i < 0 || i >= maxN)
throw new IndexOutOfBoundsException();
if (!contains(i))
throw new NoSuchElementException("index is not in the priority queue");
if (keys[i].compareTo(key) <= 0)
throw new IllegalArgumentException("Calling decreaseKey() with given argument
would not strictly decrease the key");
keys[i] = key;
swim(qp[i]);
}

/*Increase the key associated with index i to the specified value*/


public void increaseKey(int i, Key key)
{
if (i < 0 || i >= maxN)
throw new IndexOutOfBoundsException();
if (!contains(i))
throw new NoSuchElementException("index is not in the priority queue");
if (keys[i].compareTo(key) >= 0)
throw new IllegalArgumentException(
"Calling increaseKey() with given argument would not strictly
increase the key");
keys[i] = key;
sink(qp[i]);
}

/*Remove the key associated with index*/


public void delete(int i)
{
if (i < 0 || i >= maxN)
throw new IndexOutOfBoundsException();
if (!contains(i))
throw new NoSuchElementException("index is not in the priority queue");
int index = qp[i];
exch(index, n--);
swim(index);
sink(index);
keys[i] = null;
qp[i] = -1;
}

private boolean greater(int i, int j)


{
return keys[pq[i]].compareTo(keys[pq[j]]) > 0;
}

private void exch(int i, int j)


{
int swap = pq[i];
pq[i] = pq[j];
pq[j] = swap;
qp[pq[i]] = i;
qp[pq[j]] = j;
}

private void swim(int k)


{
36
while (k > 1 && greater(k / 2, k))
{
exch(k, k / 2);
k = k / 2;
}
}

private void sink(int k)


{
while (2 * k <= n)
{
int j = 2 * k;
if (j < n && greater(j, j + 1))
j++;
if (!greater(k, j))
break;
exch(k, j);
k = j;
}
}

public Iterator<Integer> iterator()


{
return new HeapIterator();
}

private class HeapIterator implements Iterator<Integer>


{
private PQImpl<Key> copy;
public HeapIterator()
{
copy = new PQImpl<Key>(pq.length - 1);
for (int i = 1; i <= n; i++)
copy.insert(pq[i], keys[pq[i]]);
}

public boolean hasNext()


{
return !copy.isEmpty();
}

public void remove()


{
throw new UnsupportedOperationException();
}

public Integer next()


{
if (!hasNext())
throw new NoSuchElementException();
return copy.delMin();
}
}
}

37
Readme

1. Copy the code present in Appendix.


2. Open Eclipse and create a java project.
3. Create appropriate java class files and paste the above code into respective classes.
4. Run the code to get the results.

38

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy