How would you implement a node classs and an edge class to create a undirected and a directed
graph using c++
Please provide a default constructor, copy constructor, accessing functions , and destructor for
each of the classes to print out a graph
( node, edge , directed ,undirected )
V={1,3,3,4,5,6}
E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)}
How would you implement a node classs and an edge class to create a undirected and a directed
graph using c++
Please provide a default constructor, copy constructor, accessing functions , and destructor for
each of the classes to print out a graph
( node, edge , directed ,undirected )
V={1,3,3,4,5,6}
E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)}
Please provide a default constructor, copy constructor, accessing functions , and destructor for
each of the classes to print out a graph
( node, edge , directed ,undirected )
V={1,3,3,4,5,6}
E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)}
Solution
#include
#include
#include
#include
#include
using namespace std;
class Graph;
class Edge;
class Vertex;
class Edge {
int weight;
Vertex * vertex1;
Vertex * vertex2;
public:
int getWeight() const {return weight;}
Vertex* getV1() const {return vertex1;}
Vertex* getV2() const {return vertex2;}
void setWeight(int w){weight=w;}
void setV1(Vertex * v){vertex1=v;}
void setV2(Vertex * v){vertex2=v;}
Edge(int w, Vertex* v1, Vertex* v2){weight=w;vertex1=v1;vertex2=v2;}
};
class Vertex {
string label;
vector edgesLeavingMe;
bool visited;
public:
string getLabel() const {return label;}
vector getEdges()const{return edgesLeavingMe;}
Edge * getEdgeTo(string d){
for (vector::iterator it = edgesLeavingMe.begin(); it != edgesLeavingMe.end(); ++it){
if ((*it)->getV2()->getLabel()==d){
return (*it);
}
}
return 0;
}
void setVisited(bool v){visited=v;}
bool getVisited() {return visited;}
void addEdge(Edge * e){edgesLeavingMe.push_back(e);}
void removeEdge(Edge *
e){edgesLeavingMe.erase(remove(edgesLeavingMe.begin(),edgesLeavingMe.end(),e),edgesLea
vingMe.end());}
void removeEdgeTo(string l){
Edge * e = getEdgeTo(l);
removeEdge(e);
}
Vertex(string l){label=l; visited=false;}
};
class Graph {
vector edges;
map vertices;
public:
Vertex * addVertex(string label){
Vertex * v = new Vertex(label);
vertices[label]=v;
return v;
}
Edge * addEdge(int w, string from, string to);
void removeEdge(string from, string to);
Vertex * getVertexWithlabel(string l);
void removeVertex(string l);
};
class UnDirectedGraph {
vector edges;
map vertices;
public:
Vertex * addVertex(string label){
Vertex * v = new Vertex(label);
vertices[label]=v;
return v;
}
map getVertices(){return vertices;}
vector getEdges(){return edges;}
Edge * addEdge(int w, string from, string to){
if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){
Vertex * vfrom = vertices.find(from)->second;
Vertex * vto = vertices.find(to)->second;
Edge * e = new Edge(w,vfrom,vto);
(*vfrom).addEdge(e);
(*vto).addEdge(e);
edges.push_back(e.
Create a java project that - Draw a circle with three random init.pdfarihantmobileselepun
Create a java project that:
- Draw a circle with three random initial points on the circle.
- Link the points to form a triangle.
- Print the angles values in the triangle.
- Use the mouse to drag a point along the perimeter of the circle. As you drag it, the triangle and
angles are redisplayed dynamically.
Here is the formula to compute angles:
A = acos((a * a - b * b - c * c) / (-2 * b * c))
B = acos((b * b - a * a - c * c) / (-2 * a * c))
C = acos((c * c - b * b - a * a) / (-2 * a * b))
Solution
@Suppresswarnings(\"WeakerAccess\")
public class DragPoints extends Application {
@Override
public void start(Stage primaryStage) {
final PointPane pane = new PointPane(640, 480);
pane.setStyle(\"-fx-background-color: wheat;\");
Label label = new Label(\"Click and drag the points.\");
BorderPane borderPane = new BorderPane(pane);
BorderPane.setAlignment(label, Pos.CENTER);
label.setPadding(new Insets(5));
borderPane.setBottom(label);
Scene scene = new Scene(borderPane);
primaryStage.setTitle(\"Exercise15_21\");
primaryStage.setScene(scene);
primaryStage.show();
}
private class PointPane extends Pane {
final Circle circle = new Circle();
final Vertex[] v = new Vertex[3];
final int strokeWidth = 2;
final Color circleStroke = Color.GRAY, legStroke = Color.BLACK;
@SuppressWarnings(\"SameParameterValue\")
PointPane(double w, double h) {
this.setPrefSize(w, h);
this.setWidth(w);
this.setHeight(h);
circle.setStroke(circleStroke);
circle.setFill(Color.TRANSPARENT);
circle.setStrokeWidth(strokeWidth);
circle.radiusProperty().bind(this.heightProperty().multiply(0.4));
circle.centerXProperty().bind(this.widthProperty().divide(2));
circle.centerYProperty().bind(this.heightProperty().divide(2));
this.getChildren().add(circle);
for (int i = 0; i < v.length; i++) {
v[i] = new Vertex(circle, 2 * Math.PI / v.length * (i + Math.random()));
v[i].radiusProperty().bind(circle.radiusProperty().divide(10));
v[i].setPosition();
v[i].setStroke(new Color(i == 0 ? 1 : 0, i == 1 ? 1 : 0, i == 2 ? 1 : 0, 1));
v[i].setFill(Color.TRANSPARENT);
v[i].setStrokeWidth(strokeWidth);
this.getChildren().add(v[i]);
v[i].setOnMouseDragged(new EventHandler() {
@Override
public void handle(MouseEvent event) {
int i;
for (i = 0; i < v.length; i++)
if (v[i] == event.getSource())
break;
v[i].setAngle(event.getX(), event.getY());
moveUpdate((Vertex) event.getSource());
}
});
}
for (int i = 0; i < v.length; i++) {
int j = i + 1 < v.length ? i + 1 : 0;
int k = j + 1 < v.length ? j + 1 : 0;
v[i].bindLeg(v[j], v[k]);
v[i].leg.setStroke(legStroke);
v[i].leg.setStrokeWidth(strokeWidth);
this.getChildren().add(v[i].leg);
this.getChildren().add(v[i].text);
}
for(DoubleProperty p: new DoubleProperty[]
{circle.radiusProperty(), circle.centerXProperty(), circle.centerYProperty()})
p.addListener(new ResizeListener());
moveUpdate(v[0]);
}
void moveUpdate(Vertex vert) {
vert.setPosition();
double[] legLength = new double[3];
for (int i = 0; i < v.length; i++)
legLength[i] = v[i].getLegLength();
for (int i = .
topologicalsort-using c++ as development language.pptxjanafridi251
topological sort using c++ as programming language to search through a tree structureknljhcffxgchjkjhlkjkfhdffxgchvjbknlkjhgchvjbkjxfghjhiyuighjbyfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffvgvvvvvvvvnbbbbbbbbbfuyfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg
Create a java project that - Draw a circle with three random init.pdfarihantmobileselepun
Create a java project that:
- Draw a circle with three random initial points on the circle.
- Link the points to form a triangle.
- Print the angles values in the triangle.
- Use the mouse to drag a point along the perimeter of the circle. As you drag it, the triangle and
angles are redisplayed dynamically.
Here is the formula to compute angles:
A = acos((a * a - b * b - c * c) / (-2 * b * c))
B = acos((b * b - a * a - c * c) / (-2 * a * c))
C = acos((c * c - b * b - a * a) / (-2 * a * b))
Solution
@Suppresswarnings(\"WeakerAccess\")
public class DragPoints extends Application {
@Override
public void start(Stage primaryStage) {
final PointPane pane = new PointPane(640, 480);
pane.setStyle(\"-fx-background-color: wheat;\");
Label label = new Label(\"Click and drag the points.\");
BorderPane borderPane = new BorderPane(pane);
BorderPane.setAlignment(label, Pos.CENTER);
label.setPadding(new Insets(5));
borderPane.setBottom(label);
Scene scene = new Scene(borderPane);
primaryStage.setTitle(\"Exercise15_21\");
primaryStage.setScene(scene);
primaryStage.show();
}
private class PointPane extends Pane {
final Circle circle = new Circle();
final Vertex[] v = new Vertex[3];
final int strokeWidth = 2;
final Color circleStroke = Color.GRAY, legStroke = Color.BLACK;
@SuppressWarnings(\"SameParameterValue\")
PointPane(double w, double h) {
this.setPrefSize(w, h);
this.setWidth(w);
this.setHeight(h);
circle.setStroke(circleStroke);
circle.setFill(Color.TRANSPARENT);
circle.setStrokeWidth(strokeWidth);
circle.radiusProperty().bind(this.heightProperty().multiply(0.4));
circle.centerXProperty().bind(this.widthProperty().divide(2));
circle.centerYProperty().bind(this.heightProperty().divide(2));
this.getChildren().add(circle);
for (int i = 0; i < v.length; i++) {
v[i] = new Vertex(circle, 2 * Math.PI / v.length * (i + Math.random()));
v[i].radiusProperty().bind(circle.radiusProperty().divide(10));
v[i].setPosition();
v[i].setStroke(new Color(i == 0 ? 1 : 0, i == 1 ? 1 : 0, i == 2 ? 1 : 0, 1));
v[i].setFill(Color.TRANSPARENT);
v[i].setStrokeWidth(strokeWidth);
this.getChildren().add(v[i]);
v[i].setOnMouseDragged(new EventHandler() {
@Override
public void handle(MouseEvent event) {
int i;
for (i = 0; i < v.length; i++)
if (v[i] == event.getSource())
break;
v[i].setAngle(event.getX(), event.getY());
moveUpdate((Vertex) event.getSource());
}
});
}
for (int i = 0; i < v.length; i++) {
int j = i + 1 < v.length ? i + 1 : 0;
int k = j + 1 < v.length ? j + 1 : 0;
v[i].bindLeg(v[j], v[k]);
v[i].leg.setStroke(legStroke);
v[i].leg.setStrokeWidth(strokeWidth);
this.getChildren().add(v[i].leg);
this.getChildren().add(v[i].text);
}
for(DoubleProperty p: new DoubleProperty[]
{circle.radiusProperty(), circle.centerXProperty(), circle.centerYProperty()})
p.addListener(new ResizeListener());
moveUpdate(v[0]);
}
void moveUpdate(Vertex vert) {
vert.setPosition();
double[] legLength = new double[3];
for (int i = 0; i < v.length; i++)
legLength[i] = v[i].getLegLength();
for (int i = .
topologicalsort-using c++ as development language.pptxjanafridi251
topological sort using c++ as programming language to search through a tree structureknljhcffxgchjkjhlkjkfhdffxgchvjbknlkjhgchvjbkjxfghjhiyuighjbyfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffvgvvvvvvvvnbbbbbbbbbfuyfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg
Extended network and algorithm finding maximal flows IJECEIAES
Graph is a powerful mathematical tool applied in many fields as transportation, communication, informatics, economy, in ordinary graph the weights of edges and vertexes are considered independently where the length of a path is the sum of weights of the edges and the vertexes on this path. However, in many practical problems, weights at a vertex are not the same for all paths passing this vertex, but depend on coming and leaving edges. The paper develops a model of extended network that can be applied to modelling many practical problems more exactly and effectively. The main contribution of this paper is algorithm finding maximal flows on extended networks.
A graph G consists of a non empty set V called the set of nodes (points, vertices) of the graph, a set E, which is the set of edges of the graph and a mapping from the set of edges E to a pair of elements of V.
Any two nodes, which are connected by an edge in a graph are called "adjacent nodes".
In a graph G(V,E) an edge which is directed from one node to another is called a "directed edge", while an edge which has no specific direction is called an "undirected edge". A graph in which every edge is directed is called a "directed graph" or a "digraph". A graph in which every edge is undirected is called an "undirected graph".
If some of edges are directed and some are undirected in a graph then the graph is called a "mixed graph".
Any graph which contains some parallel edges is called a "multigraph".
If there is no more than one edge but a pair of nodes then, such a graph is called "simple graph."
A graph in which weights are assigned to every edge is called a "weighted graph".
In a graph, a node which is not adjacent to any other node is called "isolated node".
A graph containing only isolated nodes is called a "null graph". In a directed graph for any node v the number of edges which have v as initial node is called the "outdegree" of the node v. The number of edges to have v as their terminal node is called the "Indegree" of v and Sum of outdegree and indegree of a node v is called its total degree.
Complete the implementation of the Weighted Graph that we began in t.pdfmarketing413921
Complete the implementation of the Weighted Graph that we began in this chapter by provide
bodies for the methods isEmpty, isFull, hasVertex, clearMarks, markVertex, isMarked, and
getUnmarked in the WeightedGraph.java file. Test the completed implementation using the
UseGraph class. When implementing hasVertex, dont forget to use the equals mehtod to
compare vertices. Java Code.
// Incomplete version
//----------------------------------------------------------------------------
// WeightedGraph.java by Dale/Joyce/Weems Chapter 9
//
// Implements a directed graph with weighted edges.
// Vertices are objects of class T and can be marked as having been visited.
// Edge weights are integers.
// Equivalence of vertices is determined by the vertices\' equals method.
//
// General precondition: Except for the addVertex and hasVertex methods,
// any vertex passed as an argument to a method is in this graph.
//----------------------------------------------------------------------------
package ch09.graphs;
import ch05.queues.*;
public class WeightedGraph implements WeightedGraphInterface
{
public static final int NULL_EDGE = 0;
private static final int DEFCAP = 50; // default capacity
private int numVertices;
private int maxVertices;
private T[] vertices;
private int[][] edges;
private boolean[] marks; // marks[i] is mark for vertices[i]
public WeightedGraph()
// Instantiates a graph with capacity DEFCAP vertices.
{
numVertices = 0;
maxVertices = DEFCAP;
vertices = (T[]) new Object[DEFCAP];
marks = new boolean[DEFCAP];
edges = new int[DEFCAP][DEFCAP];
}
public WeightedGraph(int maxV)
// Instantiates a graph with capacity maxV.
{
numVertices = 0;
maxVertices = maxV;
vertices = (T[]) new Object[maxV];
marks = new boolean[maxV];
edges = new int[maxV][maxV];
}
public boolean isEmpty()
// Returns true if this graph is empty; otherwise, returns false.
{
}
public boolean isFull()
// Returns true if this graph is full; otherwise, returns false.
{
}
public void addVertex(T vertex)
// Preconditions: This graph is not full.
// Vertex is not already in this graph.
// Vertex is not null.
//
// Adds vertex to this graph.
{
vertices[numVertices] = vertex;
for (int index = 0; index < numVertices; index++)
{
edges[numVertices][index] = NULL_EDGE;
edges[index][numVertices] = NULL_EDGE;
}
numVertices++;
}
public boolean hasVertex(T vertex)
// Returns true if this graph contains vertex; otherwise, returns false.
{
}
private int indexIs(T vertex)
// Returns the index of vertex in vertices.
{
int index = 0;
while (!vertex.equals(vertices[index]))
index++;
return index;
}
public void addEdge(T fromVertex, T toVertex, int weight)
// Adds an edge with the specified weight from fromVertex to toVertex.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
edges[row][column] = weight;
}
public int weightIs(T fromVertex, T toVertex)
// If edge from fromVertex to toVertex exists, returns the weight of edge;
// otherwise, returns a special “null-edge” value..
Im looking for coding help I dont really need this to be explained.pdfcontact41
I'm looking for coding help I don't really need this to be explained
I'm currently trying to draw a grid and a cube but I also need that cube to rotate
issue is I've been given so much information at once and there are so many missing pieces
mostly do to it not being explained or I've forgotten how to do it that I'm just at a lost
Here's my current code
Defines.h
#pragma once
#define Width 500
#define Height 500
#define NumPixels (Width * Height)
unsigned colorArray[NumPixels];
void ColorBuffer(unsigned int color)
{
for (unsigned int i = 0; i < NumPixels; i++)
{
colorArray[i] = color;
}
}
void drawPixel(unsigned int x, unsigned int y, unsigned int color)
{
unsigned int index = convertCoords(x, y);
colorArray[index] = color;
}
struct Float4
{
union
{
struct
{
float V[4];
};
struct
{
float x;
float y;
float z;
float w;
};
};
};
struct Matrix4x4
{
union
{
struct
{
float V[16];
};
struct
{
float xx;
float xy;
float xz;
float xw;
float yx;
float yy;
float yz;
float yw;
float zx;
float zy;
float zz;
float zw;
float wx;
float wy;
float wz;
float ww;
};
struct
{
Float4 AxisX;
Float4 AxisY;
Float4 AxisZ;
Float4 AxisW;
};
};
};
struct Vertex {
Float4 Position;
unsigned int color;
};
MyMath.h
#pragma once
#include "Defines.h"
float DotProduct(Float4 v1, Float4 v2)
{
return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z) + (v1.w * v2.w);
}
Matrix4x4 MultiplyMatrixByMatrix(const matrix& m1, const matrix& m2)
{
Matrix4x4 mOut;
mOut.xx = DotProduct(m1.Row0, m2.Column0);
mOut.xy = DotProduct(m1.Row0, m2.Column1);
mOut.xz = DotProduct(m1.Row0, m2.Column2);
mOut.xw = DotProduct(m1.Row0, m2.Column3);
mOut.yx = DotProduct(m1.Row1, m2.Column0);
mOut.yy = DotProduct(m1.Row1, m2.Column1);
mOut.yz = DotProduct(m1.Row1, m2.Column2);
mOut.yw = DotProduct(m1.Row1, m2.Column3);
mOut.zx = DotProduct(m1.Row2, m2.Column0);
mOut.zy = DotProduct(m1.Row2, m2.Column1);
mOut.zz = DotProduct(m1.Row2, m2.Column2);
mOut.zw = DotProduct(m1.Row2, m2.Column3);
mOut.wx = DotProduct(m1.Row3, m2.Column0);
mOut.wy = DotProduct(m1.Row3, m2.Column1);
mOut.wz = DotProduct(m1.Row3, m2.Column2);
mOut.ww = DotProduct(m1.Row3, m2.Column3);
return mOut;
}
unsigned int convertCoords(unsigned int x, unsigned int y)
{
return y * Width + x;
}
RasterFunc.h
#pragma once
#include "Shaders.h"
// Draws a line using one of the line equations.
void DrawLine(const Vertex& start, const Vertex& end)
{
// Copy input data and send through shaders
Vertex copy_start = start;
Vertex copy_end = end;
// Use vertex shader to modify incoming copies only.
if (VertexShader)
{
VertexShader(copy_start);
VertexShader(copy_end);
}
// original plotting variables adapted to use new cartesian data
SCREEN_XY screen_start = CartesianToScreen(copy_start);
SCREEN_XY screen_end = CartesianToScreen(copy_end);
// Standard line drawing code follows using integer coordinates...
for (numPixels)
{
A_PIXEL copyColor = currColor; // Just like a Vertex, copy original.
if (PixelShader) PixelShader(copyColor); // Modify copy.
PlotPixel(currX, c.
2Part I1. Answer questions for the following graph, if .docxgilbertkpeters11344
2
Part I:
1. Answer questions for the following graph, if a new vertex is visited and there is more than one possibility to select, following the alphabet order. (
B
A
D
C
E
H
G
F
I
J
K
)
a. Depth-first traversal starting at vertex A.
b. Depth-first traversal starting at vertex F.
c. Breadth-first traversal starting at vertex A.
d. Breadth-first traversal starting at vertex F.
e. Shortest path from vertex A to vertex E using breadth-first search.
f. Shortest path from vertex G to vertex C using breadth-first search.
g. Shortest path from vertex F to vertex A using breadth-first search.
2. Answer questions for the following graph. For the same edge length, you could order the edges using the alphabet order. (For example, for length 2, the order is AB, AE, CD, CE)
(
B
A
D
C
E
H
G
F
I
3
2
5
3
2
4
1
7
5
2
2
1
3
6
1
)
a. Construct the minimal spanning tree using Kruskal's Algorithm
b. Construct the minimal spanning tree using Prim's Algorithm, using A as the root.
c. Construct the shortest path using Dijkstra's Algorithm, using A as the source node. Using a table to describe the status of each step
Part II: programming exercise
Modify the bfs.java program (Listing A) to find the minimum spanning tree using a breadth-first search, rather than the depth-first search shown in
mst.java (Listing B). In main(), create a graph with 9 vertices and 12 edges,
and find its minimum spanning tree.
Listing A: The bfs.java Program
// bfs.java
// demonstrates breadth-first search
// to run this program: C>java BFSApp
////////////////////////////////////////////////////////////////
class Queue
{
private final int SIZE = 20;
private int[] queArray;
private int front;
private int rear;
// -------------------------------------------------------------
public Queue() // constructor
{
queArray = new int[SIZE];
front = 0;
rear = -1;
}
// -------------------------------------------------------------
public void insert(int j) // put item at rear of queue
{
if(rear == SIZE-1)
rear = -1;
queArray[++rear] = j;
}
// -------------------------------------------------------------
public int remove() // take item from front of queue
{
int temp = queArray[front++];
if(front == SIZE)
front = 0;
return temp;
}
// -------------------------------------------------------------
public boolean isEmpty() // true if queue is empty
{
return ( rear+1==front || (front+SIZE-1==rear) );
}
// -------------------------------------------------------------
} // end class Queue
////////////////////////////////////////////////////////////////
class Vertex
{
public char label; // label (e.g. ‘A’)
public boolean wasVisited;
// -------------------------------------------------------------
public Vertex(char lab) // constructor
{
label = lab;
wasVisited = false;
}
// -------------------------------------------------------------
} // end class Vertex
////////////////////////////////////////////////////////////////
class Graph
{
private final int MAX_VERTS = 20;
private Vertex vertex.
Please implement in Java. comments would be appreciated 5.pdffms12345
Please i need help with these question, thanks.
4.) What is Total Revenue and How is it calculated (formula)? MacBook Air
Solution
Total revenue is the sum of the revenue generated by selling each unit of good. It is the revenues
which are generated by selling given level of input.
Total revenue can be computed by adding up Marginal revenue generated from selling each
additional unit of good.
Therefore, the Total revenue = MR1+MR2+MR3+MR4+.... MRn.
Pluto has been hard to measure from Earth because of its atmosphere. .pdfinfo309708
Pluto has been hard to measure from Earth because of its atmosphere. In 2007 Young, Young,
and Buie measured Pluto as having a diameter of 2322 km. The New Horizons probe traveled to
Pluto and measured it up close and we now know the actual size is 2372 km. What was the
percent error of the 2007 measurement?
Solution
Percentage error: (2372-2322)*100/2372 % = 2.108%.
Loops and ArraysObjectivesArrays are a series of elements consi.pdfinfo309708
Loops and Arrays
Objectives:
Arrays are a series of elements consisting of the same type (For ex: all integers), in a contiguous
chunk of memory. The elements can be individually referenced by indexing the array.
You must specify the type of data stored in an array, and each element in any array must be of
the same type.
An array has a static size -- they cannot grow any larger than the size you tell it to be when you
create it.
To access the value at that index of the array: for (int i = 0; i < 10; i++){
cout<< intArray[i]<< endl; }
To access the memory address of the array element: for (int i = 0; i < 10; i++){
cout << intArray + i << endl; }
Creating an Array and Initializing
When you declare an array, you will get an uninitialized section of memory. If you want to
create an array of numbers, you would do:
int intNumbers [10];
double dblNumbers[10];
Then, putting element in the array can be set up by using the index of the array element you want
to change:
intNumbers[0] = 3; intNumbers[1] = 5; intNumbers[2] = 6; intNumbers[3] = 8;
1. Write a program that uses a for loop.
2. Declare and initialize and array.
3. Practice the array operations print and modify.
When you create an array, you do so to capture a group of items that all need to be treated
separately, but also need to grouped together for some purpose. For example, when you think
about a song, each note in the song is a separate sound, but they all need to be included together
in a certain order to make up the song.
To initialize the array:
int intNum [5] = {16, 3, 20, 4, 21}; (Hint: notice the syntax difference initializing this array
versus the one above)
Retrieving/Adding/Changing elements
To access or retrieve individual elements in an array, the syntax is square brackets and the
element index (starting from 0):
intNumbers[0]; will be the first item in the intNumbers array. intNumbers[1]; will be the second
item in the intNumbers array.
Below is an example of a basic 2D array. It shows how we access certain elements shown in the
arrayName[row][column] format. This will be helpful for a future assignment.
We can change the values in the array using the index of the individual items, such as
Example 1:
int intNumbers[2];
intNumbers[0] = 5;
intNumbers[1] = 7;
intNumbers[1] = intNumbers[1] * 2 cout << intNumbers[1] << endl;
Example 2:
//this will print the value 14
intNumber[1] = 10;
Example 3:
for (int i = 0; i < 10; i++){
intArray[i] = i;
cout << intArray[i] << endl;
//this will update the value to 10 at that index
//will set what the values are in that position //will print out the value of i at each index
}
TO DO: Create an array in your main function
1) Create an array of 20 doubles, using a variable name of your choosing. Assign values to your
array using a for loop:
for (int i = 0; i < 20; i++) myDoubles[i] = i;
where myDoubles is the name of the variable created.
2) Print out the values in another for loop using: cout << “Stuff to print” << endl;
3) Now, using your array an.
More Related Content
Similar to How would you implement a node classs and an edge class to create .pdf
Extended network and algorithm finding maximal flows IJECEIAES
Graph is a powerful mathematical tool applied in many fields as transportation, communication, informatics, economy, in ordinary graph the weights of edges and vertexes are considered independently where the length of a path is the sum of weights of the edges and the vertexes on this path. However, in many practical problems, weights at a vertex are not the same for all paths passing this vertex, but depend on coming and leaving edges. The paper develops a model of extended network that can be applied to modelling many practical problems more exactly and effectively. The main contribution of this paper is algorithm finding maximal flows on extended networks.
A graph G consists of a non empty set V called the set of nodes (points, vertices) of the graph, a set E, which is the set of edges of the graph and a mapping from the set of edges E to a pair of elements of V.
Any two nodes, which are connected by an edge in a graph are called "adjacent nodes".
In a graph G(V,E) an edge which is directed from one node to another is called a "directed edge", while an edge which has no specific direction is called an "undirected edge". A graph in which every edge is directed is called a "directed graph" or a "digraph". A graph in which every edge is undirected is called an "undirected graph".
If some of edges are directed and some are undirected in a graph then the graph is called a "mixed graph".
Any graph which contains some parallel edges is called a "multigraph".
If there is no more than one edge but a pair of nodes then, such a graph is called "simple graph."
A graph in which weights are assigned to every edge is called a "weighted graph".
In a graph, a node which is not adjacent to any other node is called "isolated node".
A graph containing only isolated nodes is called a "null graph". In a directed graph for any node v the number of edges which have v as initial node is called the "outdegree" of the node v. The number of edges to have v as their terminal node is called the "Indegree" of v and Sum of outdegree and indegree of a node v is called its total degree.
Complete the implementation of the Weighted Graph that we began in t.pdfmarketing413921
Complete the implementation of the Weighted Graph that we began in this chapter by provide
bodies for the methods isEmpty, isFull, hasVertex, clearMarks, markVertex, isMarked, and
getUnmarked in the WeightedGraph.java file. Test the completed implementation using the
UseGraph class. When implementing hasVertex, dont forget to use the equals mehtod to
compare vertices. Java Code.
// Incomplete version
//----------------------------------------------------------------------------
// WeightedGraph.java by Dale/Joyce/Weems Chapter 9
//
// Implements a directed graph with weighted edges.
// Vertices are objects of class T and can be marked as having been visited.
// Edge weights are integers.
// Equivalence of vertices is determined by the vertices\' equals method.
//
// General precondition: Except for the addVertex and hasVertex methods,
// any vertex passed as an argument to a method is in this graph.
//----------------------------------------------------------------------------
package ch09.graphs;
import ch05.queues.*;
public class WeightedGraph implements WeightedGraphInterface
{
public static final int NULL_EDGE = 0;
private static final int DEFCAP = 50; // default capacity
private int numVertices;
private int maxVertices;
private T[] vertices;
private int[][] edges;
private boolean[] marks; // marks[i] is mark for vertices[i]
public WeightedGraph()
// Instantiates a graph with capacity DEFCAP vertices.
{
numVertices = 0;
maxVertices = DEFCAP;
vertices = (T[]) new Object[DEFCAP];
marks = new boolean[DEFCAP];
edges = new int[DEFCAP][DEFCAP];
}
public WeightedGraph(int maxV)
// Instantiates a graph with capacity maxV.
{
numVertices = 0;
maxVertices = maxV;
vertices = (T[]) new Object[maxV];
marks = new boolean[maxV];
edges = new int[maxV][maxV];
}
public boolean isEmpty()
// Returns true if this graph is empty; otherwise, returns false.
{
}
public boolean isFull()
// Returns true if this graph is full; otherwise, returns false.
{
}
public void addVertex(T vertex)
// Preconditions: This graph is not full.
// Vertex is not already in this graph.
// Vertex is not null.
//
// Adds vertex to this graph.
{
vertices[numVertices] = vertex;
for (int index = 0; index < numVertices; index++)
{
edges[numVertices][index] = NULL_EDGE;
edges[index][numVertices] = NULL_EDGE;
}
numVertices++;
}
public boolean hasVertex(T vertex)
// Returns true if this graph contains vertex; otherwise, returns false.
{
}
private int indexIs(T vertex)
// Returns the index of vertex in vertices.
{
int index = 0;
while (!vertex.equals(vertices[index]))
index++;
return index;
}
public void addEdge(T fromVertex, T toVertex, int weight)
// Adds an edge with the specified weight from fromVertex to toVertex.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
edges[row][column] = weight;
}
public int weightIs(T fromVertex, T toVertex)
// If edge from fromVertex to toVertex exists, returns the weight of edge;
// otherwise, returns a special “null-edge” value..
Im looking for coding help I dont really need this to be explained.pdfcontact41
I'm looking for coding help I don't really need this to be explained
I'm currently trying to draw a grid and a cube but I also need that cube to rotate
issue is I've been given so much information at once and there are so many missing pieces
mostly do to it not being explained or I've forgotten how to do it that I'm just at a lost
Here's my current code
Defines.h
#pragma once
#define Width 500
#define Height 500
#define NumPixels (Width * Height)
unsigned colorArray[NumPixels];
void ColorBuffer(unsigned int color)
{
for (unsigned int i = 0; i < NumPixels; i++)
{
colorArray[i] = color;
}
}
void drawPixel(unsigned int x, unsigned int y, unsigned int color)
{
unsigned int index = convertCoords(x, y);
colorArray[index] = color;
}
struct Float4
{
union
{
struct
{
float V[4];
};
struct
{
float x;
float y;
float z;
float w;
};
};
};
struct Matrix4x4
{
union
{
struct
{
float V[16];
};
struct
{
float xx;
float xy;
float xz;
float xw;
float yx;
float yy;
float yz;
float yw;
float zx;
float zy;
float zz;
float zw;
float wx;
float wy;
float wz;
float ww;
};
struct
{
Float4 AxisX;
Float4 AxisY;
Float4 AxisZ;
Float4 AxisW;
};
};
};
struct Vertex {
Float4 Position;
unsigned int color;
};
MyMath.h
#pragma once
#include "Defines.h"
float DotProduct(Float4 v1, Float4 v2)
{
return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z) + (v1.w * v2.w);
}
Matrix4x4 MultiplyMatrixByMatrix(const matrix& m1, const matrix& m2)
{
Matrix4x4 mOut;
mOut.xx = DotProduct(m1.Row0, m2.Column0);
mOut.xy = DotProduct(m1.Row0, m2.Column1);
mOut.xz = DotProduct(m1.Row0, m2.Column2);
mOut.xw = DotProduct(m1.Row0, m2.Column3);
mOut.yx = DotProduct(m1.Row1, m2.Column0);
mOut.yy = DotProduct(m1.Row1, m2.Column1);
mOut.yz = DotProduct(m1.Row1, m2.Column2);
mOut.yw = DotProduct(m1.Row1, m2.Column3);
mOut.zx = DotProduct(m1.Row2, m2.Column0);
mOut.zy = DotProduct(m1.Row2, m2.Column1);
mOut.zz = DotProduct(m1.Row2, m2.Column2);
mOut.zw = DotProduct(m1.Row2, m2.Column3);
mOut.wx = DotProduct(m1.Row3, m2.Column0);
mOut.wy = DotProduct(m1.Row3, m2.Column1);
mOut.wz = DotProduct(m1.Row3, m2.Column2);
mOut.ww = DotProduct(m1.Row3, m2.Column3);
return mOut;
}
unsigned int convertCoords(unsigned int x, unsigned int y)
{
return y * Width + x;
}
RasterFunc.h
#pragma once
#include "Shaders.h"
// Draws a line using one of the line equations.
void DrawLine(const Vertex& start, const Vertex& end)
{
// Copy input data and send through shaders
Vertex copy_start = start;
Vertex copy_end = end;
// Use vertex shader to modify incoming copies only.
if (VertexShader)
{
VertexShader(copy_start);
VertexShader(copy_end);
}
// original plotting variables adapted to use new cartesian data
SCREEN_XY screen_start = CartesianToScreen(copy_start);
SCREEN_XY screen_end = CartesianToScreen(copy_end);
// Standard line drawing code follows using integer coordinates...
for (numPixels)
{
A_PIXEL copyColor = currColor; // Just like a Vertex, copy original.
if (PixelShader) PixelShader(copyColor); // Modify copy.
PlotPixel(currX, c.
2Part I1. Answer questions for the following graph, if .docxgilbertkpeters11344
2
Part I:
1. Answer questions for the following graph, if a new vertex is visited and there is more than one possibility to select, following the alphabet order. (
B
A
D
C
E
H
G
F
I
J
K
)
a. Depth-first traversal starting at vertex A.
b. Depth-first traversal starting at vertex F.
c. Breadth-first traversal starting at vertex A.
d. Breadth-first traversal starting at vertex F.
e. Shortest path from vertex A to vertex E using breadth-first search.
f. Shortest path from vertex G to vertex C using breadth-first search.
g. Shortest path from vertex F to vertex A using breadth-first search.
2. Answer questions for the following graph. For the same edge length, you could order the edges using the alphabet order. (For example, for length 2, the order is AB, AE, CD, CE)
(
B
A
D
C
E
H
G
F
I
3
2
5
3
2
4
1
7
5
2
2
1
3
6
1
)
a. Construct the minimal spanning tree using Kruskal's Algorithm
b. Construct the minimal spanning tree using Prim's Algorithm, using A as the root.
c. Construct the shortest path using Dijkstra's Algorithm, using A as the source node. Using a table to describe the status of each step
Part II: programming exercise
Modify the bfs.java program (Listing A) to find the minimum spanning tree using a breadth-first search, rather than the depth-first search shown in
mst.java (Listing B). In main(), create a graph with 9 vertices and 12 edges,
and find its minimum spanning tree.
Listing A: The bfs.java Program
// bfs.java
// demonstrates breadth-first search
// to run this program: C>java BFSApp
////////////////////////////////////////////////////////////////
class Queue
{
private final int SIZE = 20;
private int[] queArray;
private int front;
private int rear;
// -------------------------------------------------------------
public Queue() // constructor
{
queArray = new int[SIZE];
front = 0;
rear = -1;
}
// -------------------------------------------------------------
public void insert(int j) // put item at rear of queue
{
if(rear == SIZE-1)
rear = -1;
queArray[++rear] = j;
}
// -------------------------------------------------------------
public int remove() // take item from front of queue
{
int temp = queArray[front++];
if(front == SIZE)
front = 0;
return temp;
}
// -------------------------------------------------------------
public boolean isEmpty() // true if queue is empty
{
return ( rear+1==front || (front+SIZE-1==rear) );
}
// -------------------------------------------------------------
} // end class Queue
////////////////////////////////////////////////////////////////
class Vertex
{
public char label; // label (e.g. ‘A’)
public boolean wasVisited;
// -------------------------------------------------------------
public Vertex(char lab) // constructor
{
label = lab;
wasVisited = false;
}
// -------------------------------------------------------------
} // end class Vertex
////////////////////////////////////////////////////////////////
class Graph
{
private final int MAX_VERTS = 20;
private Vertex vertex.
Please implement in Java. comments would be appreciated 5.pdffms12345
Please i need help with these question, thanks.
4.) What is Total Revenue and How is it calculated (formula)? MacBook Air
Solution
Total revenue is the sum of the revenue generated by selling each unit of good. It is the revenues
which are generated by selling given level of input.
Total revenue can be computed by adding up Marginal revenue generated from selling each
additional unit of good.
Therefore, the Total revenue = MR1+MR2+MR3+MR4+.... MRn.
Pluto has been hard to measure from Earth because of its atmosphere. .pdfinfo309708
Pluto has been hard to measure from Earth because of its atmosphere. In 2007 Young, Young,
and Buie measured Pluto as having a diameter of 2322 km. The New Horizons probe traveled to
Pluto and measured it up close and we now know the actual size is 2372 km. What was the
percent error of the 2007 measurement?
Solution
Percentage error: (2372-2322)*100/2372 % = 2.108%.
Loops and ArraysObjectivesArrays are a series of elements consi.pdfinfo309708
Loops and Arrays
Objectives:
Arrays are a series of elements consisting of the same type (For ex: all integers), in a contiguous
chunk of memory. The elements can be individually referenced by indexing the array.
You must specify the type of data stored in an array, and each element in any array must be of
the same type.
An array has a static size -- they cannot grow any larger than the size you tell it to be when you
create it.
To access the value at that index of the array: for (int i = 0; i < 10; i++){
cout<< intArray[i]<< endl; }
To access the memory address of the array element: for (int i = 0; i < 10; i++){
cout << intArray + i << endl; }
Creating an Array and Initializing
When you declare an array, you will get an uninitialized section of memory. If you want to
create an array of numbers, you would do:
int intNumbers [10];
double dblNumbers[10];
Then, putting element in the array can be set up by using the index of the array element you want
to change:
intNumbers[0] = 3; intNumbers[1] = 5; intNumbers[2] = 6; intNumbers[3] = 8;
1. Write a program that uses a for loop.
2. Declare and initialize and array.
3. Practice the array operations print and modify.
When you create an array, you do so to capture a group of items that all need to be treated
separately, but also need to grouped together for some purpose. For example, when you think
about a song, each note in the song is a separate sound, but they all need to be included together
in a certain order to make up the song.
To initialize the array:
int intNum [5] = {16, 3, 20, 4, 21}; (Hint: notice the syntax difference initializing this array
versus the one above)
Retrieving/Adding/Changing elements
To access or retrieve individual elements in an array, the syntax is square brackets and the
element index (starting from 0):
intNumbers[0]; will be the first item in the intNumbers array. intNumbers[1]; will be the second
item in the intNumbers array.
Below is an example of a basic 2D array. It shows how we access certain elements shown in the
arrayName[row][column] format. This will be helpful for a future assignment.
We can change the values in the array using the index of the individual items, such as
Example 1:
int intNumbers[2];
intNumbers[0] = 5;
intNumbers[1] = 7;
intNumbers[1] = intNumbers[1] * 2 cout << intNumbers[1] << endl;
Example 2:
//this will print the value 14
intNumber[1] = 10;
Example 3:
for (int i = 0; i < 10; i++){
intArray[i] = i;
cout << intArray[i] << endl;
//this will update the value to 10 at that index
//will set what the values are in that position //will print out the value of i at each index
}
TO DO: Create an array in your main function
1) Create an array of 20 doubles, using a variable name of your choosing. Assign values to your
array using a for loop:
for (int i = 0; i < 20; i++) myDoubles[i] = i;
where myDoubles is the name of the variable created.
2) Print out the values in another for loop using: cout << “Stuff to print” << endl;
3) Now, using your array an.
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdfinfo309708
Modern Database Management 11th Edition by Jeffrey A. Hoffer
Use the UNION statement to provide a combined listing of care center names and their locations
as well as laboratories and their location. The list should be sorted by location, in ascending
order. (You should use aliases to rename the fields in this query.)
Please provide results!
Solution
The UNION operator is used to combine the result-set of two or more SELECT statements.The
UNION operator selects only distinct values by default. To allow duplicate values, use the ALL
keyword with UNION.
Syntax:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Now Let us consider that there are two tables namely care_center_t and laboratory_t where the
care_center_t contains rows like care_center name ,location1 and the laboratory_t consists of
rows such as laboratories and Locations2.
SELECT operator is used in selecting of particular rows from the table. So, now we select rows
namely care_center_name and location1 from care_center_t table and Loboratories and location2
from laboratory_t table.
The Database Query for the above problem is
SELECT care_center_name as name,location1 as location from care_center_t
UNION all
Select laboratory as name ,location2 as location from laboratory_t.
Let f X Y be a function.True or FalseA sufficient condition for f .pdfinfo309708
Let f: X Y be a function.True or False?A sufficient condition for f to be one-to-one is that for all
elements y in Ym there is at most one x in X with f(x)= y.
Solution
true.
A function f from X to Y is called one-to-one (or 1-1) if whenever
f (x) = f (y) then x = y.
No element of Y is the image of more than one element in X.
that is one-one function has an inverse that is also a function..
Its your third week on the job at Panache Inc. Last week, you made.pdfinfo309708
It\'s your third week on the job at Panache Inc. Last week, you made sure all investment
transactions for trading, available-for-sale, held-to-maturity, and equity securities were properly
recorded. You are reviewing the financial statement reporting for the securities and have found a
newspaper clipping dated December 31 that indicates the price of the stock of Omni company
had dropped the day before because of the company\'s severe financial difficulties. While the
company is not expected to fail, the article states the earnings of the company have permanently
declined due to changes in the new-homes market. You do a quick check of the stock price on
that day and find that the stock closed at $8 per share. Panache owns 10,000 shares of Omni\'s
stock as an available-for-sale security. The original cost of the stock was $20 per share, and the
fair value at the last reporting date (September 30, 2016) was $15 per share. You have just begun
to write a memo to the president of the company, Mr. Cartwright, about this investment when he
stops by your office and says, \"I have a question for you.\" He says, \"As you know, we use a
special metal called tellurium in our cars. It takes 10 pounds for each car we build. I had a
feeling last summer that tellurium prices were going to go up in October, so Mr. Brown told me
he could lock the prices in by using a dirigible. Did he do that?\" \"It was probably a derivative,
Mr. Cartwright,\" you reply. \"Let me look through the files and see what I can find, and I\'ll get
back to you. I\'ll include my findings in the memo I\'m writing to you about another
investment.\" You locate a file labeled tellurium futures, and inside you find several documents.
The first one is a handwritten note dated August 31, 2015, that says: Agreed to tellurium futures
contract expiring December 31, 2015; agreement gives Panache the right to purchase 2,000
pounds of tellurium at a price of $500 per pound. Signed, C. Brown 8/31/2015. The second paper
is a schedule showing prices of tellurium: Date Price 8/31/2015 $500 9/30/2015 $530
10/31/2015 $550 The third document is an invoice for the purchase of 2,000 pounds of tellurium
on October 31 at $550 per pound. There is a note on the invoice in Ms. Brown\'s handwriting
that says: Settled futures contract today. C. Brown 10/31/2015. You know that tellurium
purchased in October would have been used to produce the 200 cars made in November. The
cars produced in November were sold in December for $15,000 each. The total cost to produce
the cars was $12,000 each. You are required to: Prepare all journal entries that should have been
recorded related to the futures contract, including any entries needed for the September 30, 2016,
financial statements; the purchase of the tellurium; and the sale of the cars in December. Create
the journal entries in an Excel spreadsheet. Write a 2-page memo to Mr. Cartwright that
includes: A discussion of the investment in Omni company stock and the requir.
In JAVA Write a program that uses a two-dimensional array to sto.pdfinfo309708
In JAVA
Write a program that uses a two-dimensional array to store the highest and lowest temperatures
for each month of the year. The program should output the average high, average low, and
highest and lowest temperatures of the year. Your program must consist of the following
methods:
a. Method getData: This method reads and stores the data in the two-dimensional array.
b. Method averageHigh: This method calculates and returns the average high temperature of the
year.
c. Method averageLow: This method calculates and returns the average low temperature of the
year.
d. Method indexHighTemp: This method returns the index of the highest temperature in the
array.
e. Method indexLowTemp: This method returns the index of the lowest temperature in the array.
(These methods must all have the appropriate parameters.)
Solution
CODE
package test;
import java.util.Scanner;
public class Temperatures {
//declaring temperatures as a static array
public static double[][] temperatures = new double[12][2];
public static void main(String[] args) {
getData();
System.out.println(\"Average high is : \"+averageHigh());
System.out.println(\"Average low is : \"+averageLow());
System.out.println(\"Month of highest temperature is : \"+indexHighTemp());
System.out.println(\"Month of lowest temperature is : \"+indexLowTemp());
}
//to get data of temperatures for all months from user
public static void getData() {
System.out.println(\"Enter details\");
Scanner in = new Scanner(System.in);
for (int i = 0; i < 12; i++) {
System.out.println(\"Enter highest temperature for month \" + (i + 1));
temperatures[i][0] = in.nextDouble();
System.out.println(\"Enter lowest temperature for month \" + (i + 1));
temperatures[i][1] = in.nextDouble();
}
}
//to get avegare of highest temperatures of all months
public static double averageHigh() {
double avg = 0;
for (int i = 0; i < 12; i++) {
avg += temperatures[i][0];
}
return avg / 12;
}
//to get sverage of lowest temperatures of all months
public static double averageLow() {
double avg = 0;
for (int i = 0; i < 12; i++) {
avg += temperatures[i][1];
}
return avg / 12;
}
//to get index of highest tempeartures of all months
public static int indexHighTemp() {
int index = 0;
double max = Double.MIN_VALUE;
for (int i = 0; i < 12; i++)
if (temperatures[i][0] > max)
{
index = i;
max =temperatures[i][0];
}
return index+1;
}
//to get index of lowest tempeartures of all months
public static int indexLowTemp() {
int index = 0;
double min = Double.MAX_VALUE;
for (int i = 0; i < 12; i++)
if (temperatures[i][1] < min)
{
index = i;
min = temperatures[i][1];
}
return index+1;
}
}
SAMPLE OUTPUT
Enter details
Enter highest temperature for month 1
60
Enter lowest temperature for month 1
50
Enter highest temperature for month 2
50
Enter lowest temperature for month 2
40
Enter highest temperature for month 3
40
Enter lowest temperature for month 3
30
Enter highest temperature for month 4
30
Enter lowest temperature for month 4
20
Enter highest temperature f.
How do CCMI model help with the improvements and comparison of the p.pdfinfo309708
How do CCMI model help with the improvements and comparison of the process life cycle?
Solution
CCMI: Capability improvement model integration which is a method of improvement model
which includes the top perfomances advanced in improvement of software,acquired from
industry .CMMI isolates the top perfomance knowledge to discrete levels ,and every level
advances to elevated level.each and every level inscribe growth and nurture of the life cycle.
CMMI is uniquely applied to software evolution organisations and focus on uniterrupted
improvement..
How do you evaluate your own global mind set levelsSolutionAN.pdfinfo309708
How do you evaluate your own global mind set levels?
Solution
ANSWER:
A global mindset is refers to a special trait of global leadership which is associated with
manager-employee relationship, trust, and organizational commitment. There are prime three
features of global mindset namely- intellectual capital, psychological capital and social capital.
While evaluating my own global mind set levels I have to consider all these features. Intellectual
capital is my ability to understand and process new information, which are helpful to learn about
people of different cultures and know how to respond. Psychological capital, is evaluating my
openness, cognitive flexibility and willingness to work with other cultures. Social capital is the
relationships network that I have with their colleagues from different cultures, and can help me
to act in a trustworthy manner and build relationship with others from different cultures. The
development of a global mindset that sub-includes cultural intelligence and global business
orientation will help me to think globally and swiftly act to maintain the competitiveness in
multicultural organizations and international markets. Keeping all these above points, I can
properly designed questionnaire survey can be of useful in global mindset evaluation for me as
well as others. My global mindset affects the cognitive capabilities and the decision-making
patterns, thus exerting significant influence on the strategic capabilities of firms as well as my
personal life..
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdfinfo309708
Here are two datasets:
Dataset A: 64 65 66 68 70 71 72
Dataset B: 64 65 66 68 70 71 720
For dataset A, the mean and median are 68. Looking at dataset B, notice that all of the
observations except the last one are close together. Which measure will be affected by this last
observation in dataset B?
Mean
or
Median
Solution
Data set B: Mean will be affected since we have outlier(720) in the data hence we know that
outlers are very much affected by mean . But no affect on the Median.
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
Getting Started
Create a class called Lab8. Use the same setup for setting up your class and main method as you
did for the previous assignments. Be sure to name your file Lab8.java. Additionally, make
another file called Arrays.java. This file will be an object, so simply start it off by declaring an
Arrays class. You can copy the following skeleton and fill in the appropriate code below each of
the comments:
public class Arrays {
/ Instance Variables
// Constructors
// findMin 1
// findMax
// calcSum
// calcAverage
// toString
}
Task Overview
Your task for this lab is to create a class called Arrays with some array processing methods. This
class will maintain an array and the number of elements present in it. Additionally, methods will
be available to display the current min and max elements along with the average of all of them.
Finally, a toString() method will be available to cleanly display all the array elements. Finally,
you will write a simple driver class to test out the above Arrays class.
Part 1: Instance Variables for Arrays
The first thing to do for the Arrays class is to set up its instance variables. Declare the following
(private) instance variables:
• An int array called array ? this will be the array we will be writing methods for.
• An int called count - this represents the number of valid elements in the array.
Part 2:
Constructors for Arrays The Arrays class will have two constructors. The first constructor takes
the maximum size of the array as input as a parameter and initializes the array instance variable
appropriately. It also sets count to size. Finally, it will initialize all of the array elements to some
values between 0 and 10, inclusive. To create this constructor, follow these steps:
• Import java.util.Random to make use of the random number generator.
• Create a constructor with the following header: public Arrays(int size)
• Initialize your array variable and set its size to size (see the chart on page 252 for reference on
initializing arrays). Be very careful that you are setting the value of your array instance variable,
as opposed to creating a new variable called array.
• Set the value of the count variable to size because we will be populating the entire array.
• Copy the following code to the constructor in order to generate random values between 0 and
10, inclusive:
Random rand = new Random();
for (int i = 0; i < count; i++)
{
array[i] = (rand.nextInt(10));
}
Next, create another constructor with the following header: public Arrays(int[] arr). This
constructor will initialize the class by using the passed arr argument in order to fill its instance
variables. The following things need to be done inside of this constructor:
• Set the array variable equal to arr.
• Set the count variable equal to the length of the array.
Part 3: Displaying the Output findMin()
The first method of this class will search the array for the minimum element. Copy the following
code for the findMin method. Note how the count i.
For this homework, you will develop a class called VendingMachine th.pdfinfo309708
For this homework, you will develop a class called VendingMachine that simulates an imaginary
vending machine at CSUMB. In the program, a user can buy a bottle of water ($1.50), a coffee
($2.00), a bag of chips ($1.00),
and a chocolate bar ($2.50) from the machine. The user can buy several items if they are
available
in the machine. For the payment, a user can use only cash (including coins). Additionally, an
administrator of the machine can reset or refill the machine.
1 Demo Program
The following code presents a demo program that uses the VendingMachine class.
public class VendingMachineDemo {
public static void main(String[] args) {
VendingMachine machine1 = new VendingMachine(100);
VendingMachine machine2 = new VendingMachine(200, \"Library\");
System.out.println(\"===== Welcome to the CSUMB Vending Machine =====\");
System.out.println(machine1);
System.out.println(\"\");
System.out.println(machine2);
System.out.println(\"\ === Compare Two Machines ===\");
System.out.println(machine1.equals(machine2));
machine1.setLocation(\"BIT104\");
machine1.setName(50);
machine1.setName(100);
System.out.println(\"\ === Machine Reset ===\");
machine1.reset(4, 5, 0, 6); // In this method, we assume that a machine
// administrator resets the contents of
// a machine.
machine1.addItems(1,2,3,4); // A system admin can add items to the machine
System.out.println(machine1);
System.out.println(\"\");
machine1.displayMenu();
System.out.println(\"\ === Buy an Item ===\");
machine1.buyItem();
System.out.println(\"\ === Buy another Item ===\");
1
if(machine1.buyItem(1, 4) == false) {
System.exit(1);
}
System.out.println(\"\ === Return Two Items ===\");
machine1.returned(1, 2);
machine1.returned(2, 3);
System.out.println(\"\ === Buy another Item ===\");
machine1.buyItem(3, 5);
System.out.println(\"\ === Pay for items selected. ===\");
if(machine1.payment()) {
System.out.println(\"\ === Valid payment. ===\");
machine1.displayReceipt();
} else {
System.out.println(\"\ === Invalid payment. Try one more time. ===\");
if(machine1.payment()) {
System.out.println(\"\ === Print Receipt ===\");
machine1.displayReceipt();
} else {
System.exit(1);
}
}
machine1.addItems(5,5,5,5);
System.out.println(\"\ === Machine Status ===\");
machine1.status();
System.out.println(\"\ ===== Thank you! =====\");
}
}
Sample Run of the Demo Program: The following presents a sample result of the demo
program.
Read the result very carefully to identify the operations of the program.
===== Welcome to the CSUMB Vending Machine =====
Serial Number: 100
Location: UNKNOWN
Contents:
Water: 0
Coffee: 0
Sun Chips: 0
Chocolate Bar: 0
Serial Number: 200
Location: Library
Contents:
Water: 0
Coffee: 0
Sun Chips: 0
2
Chocolate Bar: 0
=== Compare Two Machines ===
false
=== Machine Reset ===
Serial Number: 100
Location: BIT104
Contents:
Water: 5
Coffee: 7
Sun Chips: 3
Chocolate Bar: 10
===== Vending Machine Menu =====
1. Water............$1.50
2. Regular Coffee...$2.00
3. Sun Chips........$1.00
4. Chocolate Ba.
Discuss what is SSH and the advantages and disadvantages of using it.pdfinfo309708
Discuss what is SSH and the advantages and disadvantages of using it on your Linux
distribution.
Also discuss how to control ssh access and how you configure this service.
Solution
SSH is also known as Secure Socket Shell. It is a network protocol that provides administrators
with a secure way to access a remote computer.
For advantages of it, SSH is widely used by network administrators for managing systems and
applications remotely. It allows them to log in to another computer over a network, execute
commands and move files from one computer to another.
The biggest disadvantage would be people logging in as the computer\'s administrator over SSH
and this can be done by brute force for the password.
To limit ssh access to a linux machine based on originating IP address, edit /etc/hosts.allow:.
Describe the differences between the three major physical connection .pdfinfo309708
Describe the differences between the three major physical connection mediums: twisted-pair
cable, coaxial cable, and fiber-optic cable.
Solution
Below is the Difference Between Fiber Optic Cable, Twisted Pair and coaxial Cable :
Twisted Pair Cables
Twisted pair cable consists of a pair of insulated wires twisted together, which is adapted in the
field of telecommunication for a long time. With the cable twisting together, it helps to reduce
noise from outside sources and crosstalk on multi-pair cables. Twisted pair cable works well on
transferring balanced differential signals, the merits of which are extremely valuable in wide
bandwidth and high fidelity system. Basically, twisted pair cable can be divided into two types:
unshielded twisted-pair (UTP) and shielded twisted-pair (STP). The former serves as the most
commonly used one with merely two insulated wires twisted together. Any data communication
cables and normal telephone cables belong to this category. However, shielded twisted pair
distinguishes itself from UTP in that it consists of a foil jacket which helps to prevent crosstalk
and noise from outside source. It is typically used to eliminate inductive and capacitive coupling,
so it can be applied between equipment, racks and buildings. With the advancement of
technology, the twisted pair cables are now being phased out by more technically developed and
reliable media.
Coaxial Cables
Coaxial cable acts as a high-frequency transmission cable which contains a single solid-copper
core. A coaxial cable has over 80 times the transmission capability of the twisted-pair. It is
commonly used to deliver television signals and to connect computers in a network as well, so
people may get more familiar with this kind of cable. Coaxial cable has always been the
mainstay of high speed communication and has also been applied to network with 10 gigabit
links data centers, because it is proved to be cost efficient for short links within 10 m and for
residential network. Besides, it features anti-jamming capability, stable transmission of data and
money saving. Coaxial cable is widely employed in feedlines connecting radio transmitters and
receivers, computer network connection, digital audio and television signals distribution.
Moreover, coaxial cable can effectively protect signals from being interfered by external
electromagnetic influence.
Fiber Optic Cables
Computing and data communications are fast-moving technologies. There comes a new
generation of transmission media—fiber optic cable. It refers to the complete assembly of fibers,
which contain one or more optical fibers that are used to transmit data. Each of the optical fiber
elements is individually coated by plastic layers and contained in a protective tube. Fiber optic
cable transmits data as pulses of light go through tiny tubes of glass, the transmission capacity of
which is 26,000 times higher than that of twisted-pair cable. When comparing with coaxial
cables, fiber optic cables ar.
Create a student record management system using linked list and queu.pdfinfo309708
Create a student record management system using linked list and queue using Java language and
database to save files and GUI Java swing to create background and also use HTML.
With the following properties
A . register students(assume each students has ID, first name ,last name and middle name)
B.register students with courses(course no ,course title crh)
C.able to maintain grade on which course they are registered
d.searches students by ID displays if found
E.searches by course name
F. sorts student name in alphabetical order
G.displays the details of all students
H.Deletes a student by id
I.Deletes a course by courseNo
J. Handles errors in informative ways .
Solution
public class StudentRegistration extends JFrame implements ActionListener{
JLabel idLabel, fnameLabel, midnameLabel, lastnameLabel, courseLabel;
JTextField idField, fnameField, midnameField, lastnameField, courseField;
JButton registerButton;
JPanel panel;
List list = new ArrayList();
StudentRegistration() {
setSize(800, 400);
setLayout(null);
idLabel = new JLabel(\"ID\");
fnameLabel = new JLabel(\"First Name\");
midnameLabel = new JLabel(\"Mid Name\");
lastnameLabel = new JLabel(\"Last Name\");
courseLabel = new JLabel(\"Course\");
// Defining ID field
idField = new JTextField();
idField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
}
});
// Defining Name field
fnameField = new JTextField();
fnameField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
}
});
registerButton
= new JButton(\"Register\");
registerButton.addActionListener(this);
add(idLabel);
add(fnameLabel);
add(midnameLabel);
add(lastnameLabel);
add(courseLabel);
add(idField);
add(fnameField);
add(midnameField);
add(lastnameField);
add(courseField);
add(registerButton);
list.add(new User(idField.getText(), fnameField.getText(),midnameField.getText(),
lastnameField.getText(),courseField.getText()));
saveValues();
JOptionPane.showMessageDialog(this,
\"Student Successfully Registered\");
}
}
public void saveValues() throws SQLException {
User str = list.get(list.size()-1);
Connection connection = null;
Class.forName(\"com.mysql.jdbc.Driver\");
String url = \"jdbc:mysql://localhost/testdb\";
String user = \"root\";
String password = \"\";
connection = DriverManager.getConnection(url,
user, password);
Statement stmt = connection.createStatement();
String sql = \"INSERT INTO students(str.fname,str.midname,str.lastname,str.course) \";
stmt.execute(sql);
}
public static void
main(String[] args) {
new StudentRegistration();
}
}.
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdfinfo309708
Coca-Cola company
Strategic Goals and Objectives
i. Objectives are the specific, measurable steps that will help you achieve your mission. Develop
objectives that are SMART: specific, measurable, achievable (eventually), relevant to your
mission, and timed (with a date for completion.).
Solution
The strategic goals and objectives to the Coca-Cola Company will be framed as,.
C programming. Answer question only in C code Ninth Deletion with B.pdfinfo309708
C programming. Answer question only in C code Ninth: Deletion with Binary Search Tree (20
points) In the ninth part, you will extend the binary search tree in the eighth part to support the
deletion of a node. The deletion of a node is slightly trickier compared to the search and insert in
the eighth The deletion is straightforward if the node to be deleted has only one child. You make
the parent of the node to be deleted point to that child. In this scenario, special attention must be
paid only when the node to be deleted is the root Deleting a node with two children requires
some more work. In this case, you must find the minimum element in the right subtree of the
node to be deleted. Then you insert that node in the place where the node to be deleted was. This
process needs to be repeated to delete the minimum node that was just moved In either case, if
the node to be deleted is the root, you must update the pointer to the root to point to the new root
node Input format: This program takes a file name as argument from the command line. The file
is either blank or contains successive lines of input. Each line contains a character, \'i or \'d\'
followed by a tab and an integer. For each line that starts with \'i\', your program should insert
that number in the binary search tree if it is not already there. If the line starts with a \'s, your
program should search for that value. If the line starts with a \'d\', your program should delete
that value from the tree output format: For each line in the input file, your program should print
the status/result of the operation. For insert and search, the output is the same as in the Eighth
Part: For an insert operation, the program should print either \"inserted\" with a single space
followed by a number the height of the inserted mode in the tree, or \"duplicate\" if the value is
already present in the tree. The height of the root node is 1. For a search, the program should
either print \"present\" followed by the height of the node, or absent\" based on the outcome of
the search. For a delete, the program should print \"success or \"fail\" based on the whether the
value was present or not. Again, as in the Eight Part, your program should print \"error\" (and
nothing else) if the file does not exist or for input lines with improper structure Example
Execution: Lets assume we have a file filel.txt with the following contents: i 5 i 3 i 4 i 1 i 6 i 2 s
1 d 3 s 2 Executing the program in the following fashion should produce the output shown
below:
Solution
// C program to demonstrate delete operation in binary search tree
#include
#include
struct node
{
int key;
struct node *left, *right;
};
// A utility function to create a new BST node
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
.
Biology LabThe poisonous wastes of diptheria germs are called (A).pdfinfo309708
Biology Lab:
The poisonous wastes of diptheria germs are called (A) antitoxins (B) antibodies (C) immunities
(D) toxins
Solution
Biology Lab ANS: (D) toxins
Explanation:
A toxin is a poisonous substance which produced by some bacteria or an organism
Diphtheria is mainly caused by the corynebacterium diphtheriae bacteria. It is a gram positive,
non-endospore forming, pleiomorphic bacteria.
Poisonous wastes of diptheria germs (C.diphtheriae) can produce diphtheria toxin. It causes sore
throat and fever. This toxins prevents protein synthesis and causes cell death..
Aside from the expansion of industrial capitalism, what factors affe.pdfinfo309708
Aside from the expansion of industrial capitalism, what factors affected American development
during the late 19th centry? How important are those factors in comparison to capitalism’s
growth?
Solution
ANSWER:
During the late nineteenth Americans believed for the expansion of national borders in order to
keep the America running upright. Moreover, the Americans believed that the United States was
the most powerful of nations, and that they could take any land they pleased. The expansion of
American started after the Civil War. The war made substantial use of the telegraph and
railroads. Moreover there was a crucial expansion of railroads with a motive on combing the
Atlantic and Pacific coasts, with movement.
This growing population and an advanced transportation is one of the main causes of expansions
of America in late 19th century. Europeans with surplus wealth joined Americans in investing
the economic expansion of the nation. Also the farmers during this time required arable land for
livestock and crops which was unavailable due to overcrowding. Thus financial panics uprooted
them and sent them west for a new start. Furthermore, the American government also motivated
the citizens to move west, with the motive of acquisition of new territory from foreign powers.
The above discussed factors are different from the factors in capitalism’s growth. Capitalism is a
system in an economy where private entities own the factors of production namely
entrepreneurship, natural resources, capital goods and labor; and ensures that an economy will
produce the most desired products at an acceptable price. The owners of capital goods,
entrepreneurship and natural resources exercise control through companies..
Yates (2009) notes that unions have a purpose broader than serving t.pdfinfo309708
Yates (2009) notes that unions have a purpose broader than serving their members. What
arguments does he make in that regard? What do you think of his arguments, and why?
Solution
Yates says that unions actually mean better pay, benefits, and slao working conditions for their
members and they indeed force employers to treat employees with dignity and respect; and at
their maximum best, they provide the workers to work in the society with utmost satisfaction on
the whole. Yates used simple language with suffiecient examples to tell that how unions popped
out to be helpful at certain troublesome instants on the whole. His arguments exactly carried on
to tell the importance of unions and he advises all the workers to join in the unions which would
be ultimately beneficial to them on the whole..
write a C program for blinking light using function make sure it.pdfinfo309708
write a C program for blinking light using function
** make sure it will compile
Solution
GPIO is General purpose input output it is very useful for blinking a led.
GPIO is configured with input and output. itis micro controller.
#include
/* PORT B0 is the microcontroller */
int main()
{
unsigned int signal =0;
/* Configure GPIO with input and output */
DDRB = 0x01;
while(1)
{
for (signal =0;signal <50000;signal ++)
{
PORTB = 0x00;
}
for (signal =0;signal <50000;signal ++)
{
PORTB = 0x01;
}
}
return 0;
}.
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
The Indian economy is classified into different sectors to simplify the analysis and understanding of economic activities. For Class 10, it's essential to grasp the sectors of the Indian economy, understand their characteristics, and recognize their importance. This guide will provide detailed notes on the Sectors of the Indian Economy Class 10, using specific long-tail keywords to enhance comprehension.
For more information, visit-www.vavaclasses.com
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
The French Revolution Class 9 Study Material pdf free download
How would you implement a node classs and an edge class to create .pdf
1. How would you implement a node classs and an edge class to create a undirected and a directed
graph using c++
Please provide a default constructor, copy constructor, accessing functions , and destructor for
each of the classes to print out a graph
( node, edge , directed ,undirected )
V={1,3,3,4,5,6}
E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)}
How would you implement a node classs and an edge class to create a undirected and a directed
graph using c++
Please provide a default constructor, copy constructor, accessing functions , and destructor for
each of the classes to print out a graph
( node, edge , directed ,undirected )
V={1,3,3,4,5,6}
E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)}
Please provide a default constructor, copy constructor, accessing functions , and destructor for
each of the classes to print out a graph
2. ( node, edge , directed ,undirected )
V={1,3,3,4,5,6}
E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)}
Solution
#include
#include
#include
#include
#include
using namespace std;
class Graph;
class Edge;
class Vertex;
class Edge {
int weight;
Vertex * vertex1;
Vertex * vertex2;
public:
int getWeight() const {return weight;}
Vertex* getV1() const {return vertex1;}
Vertex* getV2() const {return vertex2;}
void setWeight(int w){weight=w;}
void setV1(Vertex * v){vertex1=v;}
void setV2(Vertex * v){vertex2=v;}
Edge(int w, Vertex* v1, Vertex* v2){weight=w;vertex1=v1;vertex2=v2;}
};
class Vertex {
string label;
4. Vertex * getVertexWithlabel(string l);
void removeVertex(string l);
};
class UnDirectedGraph {
vector edges;
map vertices;
public:
Vertex * addVertex(string label){
Vertex * v = new Vertex(label);
vertices[label]=v;
return v;
}
map getVertices(){return vertices;}
vector getEdges(){return edges;}
Edge * addEdge(int w, string from, string to){
if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){
Vertex * vfrom = vertices.find(from)->second;
Vertex * vto = vertices.find(to)->second;
Edge * e = new Edge(w,vfrom,vto);
(*vfrom).addEdge(e);
(*vto).addEdge(e);
edges.push_back(e);
return e;
}
else{
//needt o handle case where vertices did not exist.
return 0;
}
}
Edge * getEdge(string from, string to){
if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){
Vertex * v1 = vertices.find(from)->second;
Vertex* v2 = vertices.find(to)->second;
Edge * e = (*v1).getEdgeTo(to);
return e;
}
5. else {
//need to handle case where vertices did not exist.
return 0;
}
}
void removeEdge(string from, string to){
Edge * e = getEdge(from,to);
if (e != 0){
edges.erase(remove(edges.begin(),edges.end(),e),edges.end());
(*e).getV1()->removeEdge(e);
(*e).getV2()->removeEdge(e);
}
//handle case where edge did not exist?
}
Vertex * getVertexWithLabel(string l){
if (vertices.find(l) != vertices.end())
return vertices.find(l)->second;
else
return 0;
}
void removeVertex(string l){
Vertex * v = getVertexWithLabel(l);
if (v != 0){
vector edges = getVertexWithLabel(l)->getEdges();
for (vector::iterator it = edges.begin(); it != edges.end(); ++it){
string from = (*it)->getV1()->getLabel();
string to = (*it)->getV2()->getLabel();
removeEdge(from,to);
}
vertices.erase(l);
}
else {
//Need to handle case where vertex does not exist.
}
}
vector whereCanIGo(Vertex * v)
6. {
vector destinations;
vector edges = v->getEdges();
for (vector::const_iterator it = edges.begin(); it != edges.end(); ++it) {
if ((*it)->getV1() != v){
destinations.push_back((*it)->getV1());
}
if ((*it)->getV2() !=v) {
destinations.push_back((*it)->getV2());
}
}
destinations.push_back(v);
return destinations;
}
};
class DirectedGraph {
vector edges;
map vertices;
public:
Vertex * addVertex(string label){
Vertex * v = new Vertex(label);
vertices[label]=v;
return v;
}
map getVertices(){return vertices;}
vector getEdges(){return edges;}
Edge * addEdge(int w, string from, string to){
if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){
Vertex * vfrom = vertices.find(from)->second;
Vertex * vto = vertices.find(to)->second;
Edge * e = new Edge(w,vfrom,vto);
(*vfrom).addEdge(e);
edges.push_back(e);
return e;
}
else{
7. //handle case where vertcies did not exist.
return 0;
}
}
Edge * getEdge(string from, string to){
if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){
Vertex * v1 = vertices.find(from)->second;
Vertex* v2 = vertices.find(to)->second;
Edge * e = (*v1).getEdgeTo(to);
return e;
}
else {
return 0;
}
}
void removeEdge(string from, string to){
Edge * e = getEdge(from,to);
if (e != 0){
edges.erase(remove(edges.begin(),edges.end(),e),edges.end());
(*e).getV1()->removeEdge(e);
}
}
Vertex * getVertexWithLabel(string l){
if (vertices.find(l) != vertices.end())
return vertices.find(l)->second;
else
return 0;
}
void removeVertex(string l){
Vertex * v = getVertexWithLabel(l);
if (v != 0){
vector edges = getVertexWithLabel(l)->getEdges();
for (vector::iterator it = edges.begin(); it != edges.end(); ++it){
string from = (*it)->getV1()->getLabel();
string to = (*it)->getV2()->getLabel();
removeEdge(from,to);
8. }
vertices.erase(l);
}
else {
//handle case where vertex did not exist.
}
}
vector whereCanIGo(Vertex * v)
{
vector destinations;
vector edges = v->getEdges();
for (vector::const_iterator it = edges.begin(); it != edges.end(); ++it) {
if ((*it)->getV2() !=v) {
destinations.push_back((*it)->getV2());
}
}
destinations.push_back(v);
return destinations;
}
};
template
void printGraph(T * t){
map vertices = t->getVertices();
for (map::iterator it = vertices.begin(); it != vertices.end(); ++it){
cout << it->first <<": ";
vector edges = it->second->getEdges();
for (vector::iterator jit = edges.begin(); jit != edges.end(); ++jit){
string l1 = (*jit)->getV1()->getLabel();
string l2=(*jit)->getV2()->getLabel();
if (l1 != it->first){cout << l1 << ", ";}
if (l2 != it->first){cout << l2 << ", ";}
}
cout << endl;
}
}
template
9. bool isPath(T * t, string from, string to)
{
Vertex * vfrom = t->getVertexWithLabel(from);
Vertex * vto = t->getVertexWithLabel(to);
if (vfrom == 0 || vto == 0) {
return false;
}
if (from==to) {
return true;
}
T g = *t;
map vertices = t->getVertices();
vector edges = t->getEdges();
vector verticesToCheck;
verticesToCheck.push_back(vfrom);
vertices.erase(from);
while (verticesToCheck.size() != 0){
vector destinations = t->whereCanIGo(verticesToCheck[0]);
verticesToCheck.erase(verticesToCheck.begin());
for (vector::const_iterator it = destinations.begin(); it != destinations.end(); ++it) {
//
if (vertices.find((*it)->getLabel()) != vertices.end()) {
if ((*it)->getLabel()==to) {
return true;
}
verticesToCheck.push_back((*it));
vertices.erase((*it)->getLabel());
}
}
}
return false;
}
int main(){
UnDirectedGraph g;
g.addVertex("v1");
g.addVertex("v2");