complete the following functions in c++ singleRotation putNo.pdfabbecindia
complete the following functions in c++
singleRotation
putNode: Insert or update the entry in the extended AVL tree map (TreeMapStats) using
the inputted key and value. In addition, efficiently update the statistics information of only
the nodes affected by the insertion of the new entry into the map
eraseNode: Remove the entry in the extended AVL tree map (TreeMapStats) with the
inputted key, if the key is in the map, if necessary. In addition, efficiently update the statistics
information of only the nodes affected by the removal of the new entry from the map
also right a function updateStats
class TreeMapStats : public AVLTreeMap {
public:
// embedded node class extension of an AVL-Tree node
class Node : public AVLTreeMap::Node {
private:
// stats class to account for basic statistics/information of subtree rooted at each node
class Stats {
private:
// data members: number of nodes/map entries stored in the subtree; sum of all the map values of
map entries stored in the subtree; the minimum map value of all the map entries stored in the
subtree; the maximum map value of the map entries stored in the subtree
int num;
int sum;
int min;
int max;
public:
// stats constructors
Stats() { };
Stats(int v, Node *l, Node* r) : num(1), sum(v), min(v), max(v) {
};
// stats destructor
~Stats() { };
// overloading output stream for a representation of stats s
friend ostream& operator<<(ostream& os, const Stats& s) {
os << "{" << s.num << "," << s.sum << "," << s.min << "," << s.max << "}";
return os;
};
};
// data member: node info/stats
Stats *info;
public:
// tree node constructors
Node() : AVLTreeMap::Node() { };
Node(int k, int v, Node* l, Node* r, Node* p) : AVLTreeMap::Node(k,v,l,r,p) {
info = new Stats(v, l, r);
};
// tree node destructor
virtual ~Node() { if (this->info) delete this->info; };
// overloading output stream for a representation of TreeMapStats node w
friend ostream& operator<<(ostream& os, const Node& w) {
os << ((AVLTreeMap::Node) w) << *(w.info) ;
return os;
};
// (overloading) print utility for a node, including map entry and additional info and stats
void printStats() { cout << *this << endl; }
/*
# PRECONDITION: the info values for the left and right nodes for the children of the node have
been properly set, consistent with the subtree that they root
# POSTCONDITION: the info values for the node have been properly set, consistent with the
subtree that it roots
*/
};
// print utilities
void printTreeMapStats();
void printTreeMapStats(Node* w);
void printTreeMap();
// tree constructor
TreeMapStats() { };
// tree desctructor
virtual ~TreeMapStats() { };
protected:
// (overloadable) auxiliary node creation utility
virtual Node* createNode(int k, int v, BSTMap::Node* l, BSTMap::Node* r, BSTMap::Node* p) {
return new Node(k,v,(Node*) l, (Node*) r, (Node*) p); };
// prints a representation of AVL node w
// (overloadable)
// INPUT: node w
virtual void printNode(const BSTMap::Node* w) const { if (w) cout << *((Node*) w); };
// (overloa.
Write a program that reads a graph from a file and determines whether.docxajoy21
The document describes a program that reads a graph from a file, determines if the graph is connected, and performs depth-first search (DFS) on the graph. It prompts the user for a file, reads the graph data, creates an unweighted graph, prints the edges, and uses DFS to check if the number of visited vertices matches the total. If so, the graph is connected.
This document contains the details of a programming project submitted by a student of class 12. It includes an acknowledgement section thanking the computer science teacher for guidance. It also includes a certificate signed by the teacher certifying that the student completed the project. The document then lists 23 programming problems/exercises addressed by the student with descriptions and signatures. It appears to be the final report submitted by the student for a programming assignment.
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
in this assignment you are asked to write a simple driver program and set of functions (maybein
a library) that can be performed on a binary search tree.
Your program should allow user to insert/delete integer values into the binary search tree along
with several other operations on the binary search tree. You can use the code given in slides. But
this time your key will be int! Specifically, your program will ask user to enter a command and
related parameters (if any) in a loop, and then perform the given commands. Here is the list of
commands that your program must implement:
* insert
*find\'
*delete
*list inorder
*list preorder
*list postorder
*list levelorder
* max
* min
* height
*count
* sum
*quit
As always, make sure you release (free) the dynamically allocated memories if you allocate any
memory in your programs. So, before submitting your program, run it with valgrind to see if
there is any memory leakage
//my proggram in C
struct tree_node {
int data;
struct tree_node *left, *right;
}
typedef struct nodeT {
int key;
struct nodeT *left, *right;
} nodeT, *treeT;
int main(){
while (TRUE) {
printf(\"> \");
line = GetLine();
ch = toupper(line[0]);
switch (ch) {
case \'I\': insert(); break;
case \'F\': find(); break;
case \'D\': delete(); break;
case \'LI\': listInorder; break;
case \'LPR\': listPreorder(); break;
case \'LPO\': listPostorder(); break;
case \'MAX\': max(); break;
case \'min\': min(); break;
case \'H\': height(); break;
case \'C\': count(); break;
case \'S\': sum(); break;
case \'Q\': exit(0);
default:printf(\"Illegal command\ \"); break;
}
}
}
nodeT *FindNode(nodeT *t, int key){
while(t !=NULL) {
if (key == t->key) return t;
if (key < t->key) {
t = t->left;
} else {
t = t->right;
}
return NULL;
}
void delete(nodeT **p){
nodeT
*target;
target=*p;
if (target->left==NULL && target->right==NULL) {
*p=NULL;
} else if (target->left == NULL) {
*p=target->right;
} else
if (target->right == NULL) {
*p=target->left;
} else {
/* target has two children, see next slide */
}
free(target);
}
void listInorder(nodeT *T){
if (t != NULL) {
DisplayTree(t->left);
printf(“%d “, t->key);
DisplayTree(t->right);
}
}
void listPreorder(nodeT *t) {
if (t != NULL) {
printf(“%d “, t->key);
DisplayTree(t->left);
DisplayTree(t->right);
}
}
void listPostOrder(nodeT *t){
if (t != NULL) {
DisplayTree(t->left);
DisplayTree(t->right);
printf(“%d “, t->key);
}
}
void intsert(nodeT **tptr, int key){
nodeT*t, *tmp;
t=*tptr;
if (t == NULL) {
tmp=New(nodeT*);
tmp->key = key;
tmp->left=tmp->right=NULL;
*tptr=tmp;
return;
}
if (key < t->key) {
InsertNode
(&t->left, key);
} else {
InsertNode(&t->right, key);
}
}
int height(nodeT *t){
if (t == NULL)
return 0;
else
return (1 + maximumof(
height(t->left),
height(t->right)) );
}
int sum(struct tree_node *p){
if (p == NULL)
return 0;
else
return (p->data +
sum(p->left) +
sum(p->right) );
}
Solution
1. /*
2. * Java Program to Implement Binary Search Tree
3. */
4.
5. import java.util.Scanner;
6.
7. /* Class BSTNode */
8. cl.
I have compilation errors that I'm struggling with in my code- please.pdfColinjHJParsonsa
I have compilation errors that I'm struggling with in my code, please can you help me fix the
errors. I'm trying to make a road map, where each place is a vertex and each road between two
places is an edge. Each edge stores a number indicating the length of the road. Assume that there
is at most one road directly connecting two given places, so that there is at most one edge
between two vertices. The map is loaded in via a text file that starts with a line that contains the
number of vertices and the number of edges. After the line mentioned, there are two sections of
content. The initial section holds details regarding the vertices, where each line represents a
single vertex. The information stored for each vertex includes its name and the availability of
charging stations, represented as an integer with 1 indicating availability and 0 indicating
unavailability. The second section stores information about the edges, with each line
corresponding to one edge. Each line contains three numbers: the first two are 0-based indices of
its two incident vertices within the places array; the last number is the edge length. An example
of the map input would look like this as a txt file:
import java.util.*;
import java.io.*;
class Vertex {
// Constructor: set name, chargingStation and index according to given values,
// initilaize incidentRoads as empty array
public Vertex(String placeName, boolean chargingStationAvailable, int idx) {
name = placeName;
incidentRoads = new ArrayList<Edge>();
index = idx;
chargingStation = chargingStationAvailable;
}
public String getName() {
return name;
}
public boolean hasChargingStation() {
return chargingStation;
}
public ArrayList<Edge> getIncidentRoads() {
return incidentRoads;
}
// Add a road to the array incidentRoads
public void addIncidentRoad(Edge road) {
incidentRoads.add(road);
}
public int getIndex() {
return index;
}
private String name; // Name of the place
private ArrayList<Edge> incidentRoads; // Incident edges
private boolean chargingStation; // Availability of charging station
private int index; // Index of this vertex in the vertex array of the map
}
class Edge {
public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) {
length = roadLength;
incidentPlaces = new Vertex[] { firstPlace, secondPlace };
}
public Vertex getFirstVertex() {
return incidentPlaces[0];
}
public Vertex getSecondVertex() {
return incidentPlaces[1];
}
public int getLength() {
return length;
}
private int length;
private Vertex[] incidentPlaces;
}
// A class that represents a sparse matrix
public class RoadMap {
// Default constructor
public RoadMap() {
places = new ArrayList<Vertex>();
roads = new ArrayList<Edge>();
}
// Auxiliary function that prints out the command syntax
public static void printCommandError() {
System.err.println("ERROR: use one of the following commands");
System.err.println(" - Load a map and print information:");
System.err.println(" java RoadMap -i <MapFile>");
System.err.println(" - Load a map an.
Write CC++ a program that inputs a weighted undirected graph and fi.pdf4babies2010
Write a shell command to search all the files in the working directory with names containing one
character extension for the lines that does not start with a character A or character B.
Solution
Answer:
#!/bin/bash
# to search all the files in the working directory with names containing one character extension
#for the lines that does not start with a character A or character B
find . -type f -name \"*.?\" | -not -name \'[ac]*\' -type f.
Need to revise working code below,A good design means the applicat.pdfarchgeetsenterprises
Need to revise working code below,
A good design means the application should scale easily -- that is, the application should be
designed so that additional processing requirements can be added without making having to
rewrite the application each time. Revise code below to add the following design features:
Move the code to display the menu to it\'s own method.
Create a method to handle capturing the shape dimensions. One approach may be to pass to the
method the dimension to enter (\"base\", \"height\", \"side\" or \"radius\") as a String.
Processing for each of the shapes matched in the switch statement should also be moved to their
own methods.
Notes -
The program should \"look and feel\" like the code below.
The program should display the menu and prompt the user for a shape (or an exit).
If the user enters a value that corresponds to a shape, program control (via the switch statement)
should transfer control to a method specific to the shape that will pass control to prompt for the
appropriate dimensions to another method, then calculate the area and perimeter (circumference)
as directed in PLP06, and display the result.
The program should repeat from step 1 above.
import java.util.Scanner;
public class Pickashape {
//Declaring constant
public static final double PI = 3.14159;
public static void main(String[] args) {
//Declaring variable
int choice;
//Scanner class Obejct is used to read the inputs entered by the user
Scanner sc = new Scanner(System.in);
//This loop continues to execute until user enters choice \'5\'
do {
//Displaying the menu
System.out.println(\"\ \ Choose the shape\");
System.out.println(\"1. Square\");
System.out.println(\"2. Rectangle\");
System.out.println(\"3. Circle\");
System.out.println(\"4. Triangle\");
System.out.println(\"5. Quit\");
System.out.print(\"Enter your choice:\");
choice = sc.nextInt();
//Based on the User selection the corresponding case will be executed
switch (choice) {
//This case will calculate the area and perimeter of the square
case 1: {
//Declaring variables
double side, area, perimeter;
//Getting the side of the square entered by the user
System.out.print(\"Enter the side (as a decimal):\");
side = sc.nextDouble();
//calculating the area of the square
area = side * side;
//calculating the perimeter of the square
perimeter = 4 * side;
//Displaying the area of the square
System.out.println(\"The area is \" + area);
//Displaying the perimeter of the square;
System.out.println(\"The perimeter is \" + perimeter);
break;
}
case 2: {
//Declaring variables
double firstside, secondside, area, perimeter;
//Getting the first side of the rectangle
System.out.print(\"Enter the first side (as a decimal):\");
firstside = sc.nextDouble();
//Getting the second side of the rectangle
System.out.print(\"Enter the second side (as a decimal):\");
secondside = sc.nextDouble();
//Calculating the area of the rectangle
area = firstside * secondside;
//Calculating the perimeter of the rectangle
perimeter = 2 * fi.
This document provides code for algorithms to solve the Travelling Salesman Problem (TSP) using different approaches:
1) Brute force exhaustive enumeration that calculates the route length for every possible permutation to find the shortest route.
2) Stochastic optimization that starts with a random route and iteratively improves it by swapping pairs of cities and evaluating new routes to find shorter ones.
3) Main code implements the pair swapping approach, generating new routes by swapping city pairs n times and returning the shortest route found.
complete the following functions in c++ singleRotation putNo.pdfabbecindia
complete the following functions in c++
singleRotation
putNode: Insert or update the entry in the extended AVL tree map (TreeMapStats) using
the inputted key and value. In addition, efficiently update the statistics information of only
the nodes affected by the insertion of the new entry into the map
eraseNode: Remove the entry in the extended AVL tree map (TreeMapStats) with the
inputted key, if the key is in the map, if necessary. In addition, efficiently update the statistics
information of only the nodes affected by the removal of the new entry from the map
also right a function updateStats
class TreeMapStats : public AVLTreeMap {
public:
// embedded node class extension of an AVL-Tree node
class Node : public AVLTreeMap::Node {
private:
// stats class to account for basic statistics/information of subtree rooted at each node
class Stats {
private:
// data members: number of nodes/map entries stored in the subtree; sum of all the map values of
map entries stored in the subtree; the minimum map value of all the map entries stored in the
subtree; the maximum map value of the map entries stored in the subtree
int num;
int sum;
int min;
int max;
public:
// stats constructors
Stats() { };
Stats(int v, Node *l, Node* r) : num(1), sum(v), min(v), max(v) {
};
// stats destructor
~Stats() { };
// overloading output stream for a representation of stats s
friend ostream& operator<<(ostream& os, const Stats& s) {
os << "{" << s.num << "," << s.sum << "," << s.min << "," << s.max << "}";
return os;
};
};
// data member: node info/stats
Stats *info;
public:
// tree node constructors
Node() : AVLTreeMap::Node() { };
Node(int k, int v, Node* l, Node* r, Node* p) : AVLTreeMap::Node(k,v,l,r,p) {
info = new Stats(v, l, r);
};
// tree node destructor
virtual ~Node() { if (this->info) delete this->info; };
// overloading output stream for a representation of TreeMapStats node w
friend ostream& operator<<(ostream& os, const Node& w) {
os << ((AVLTreeMap::Node) w) << *(w.info) ;
return os;
};
// (overloading) print utility for a node, including map entry and additional info and stats
void printStats() { cout << *this << endl; }
/*
# PRECONDITION: the info values for the left and right nodes for the children of the node have
been properly set, consistent with the subtree that they root
# POSTCONDITION: the info values for the node have been properly set, consistent with the
subtree that it roots
*/
};
// print utilities
void printTreeMapStats();
void printTreeMapStats(Node* w);
void printTreeMap();
// tree constructor
TreeMapStats() { };
// tree desctructor
virtual ~TreeMapStats() { };
protected:
// (overloadable) auxiliary node creation utility
virtual Node* createNode(int k, int v, BSTMap::Node* l, BSTMap::Node* r, BSTMap::Node* p) {
return new Node(k,v,(Node*) l, (Node*) r, (Node*) p); };
// prints a representation of AVL node w
// (overloadable)
// INPUT: node w
virtual void printNode(const BSTMap::Node* w) const { if (w) cout << *((Node*) w); };
// (overloa.
Write a program that reads a graph from a file and determines whether.docxajoy21
The document describes a program that reads a graph from a file, determines if the graph is connected, and performs depth-first search (DFS) on the graph. It prompts the user for a file, reads the graph data, creates an unweighted graph, prints the edges, and uses DFS to check if the number of visited vertices matches the total. If so, the graph is connected.
This document contains the details of a programming project submitted by a student of class 12. It includes an acknowledgement section thanking the computer science teacher for guidance. It also includes a certificate signed by the teacher certifying that the student completed the project. The document then lists 23 programming problems/exercises addressed by the student with descriptions and signatures. It appears to be the final report submitted by the student for a programming assignment.
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
in this assignment you are asked to write a simple driver program and set of functions (maybein
a library) that can be performed on a binary search tree.
Your program should allow user to insert/delete integer values into the binary search tree along
with several other operations on the binary search tree. You can use the code given in slides. But
this time your key will be int! Specifically, your program will ask user to enter a command and
related parameters (if any) in a loop, and then perform the given commands. Here is the list of
commands that your program must implement:
* insert
*find\'
*delete
*list inorder
*list preorder
*list postorder
*list levelorder
* max
* min
* height
*count
* sum
*quit
As always, make sure you release (free) the dynamically allocated memories if you allocate any
memory in your programs. So, before submitting your program, run it with valgrind to see if
there is any memory leakage
//my proggram in C
struct tree_node {
int data;
struct tree_node *left, *right;
}
typedef struct nodeT {
int key;
struct nodeT *left, *right;
} nodeT, *treeT;
int main(){
while (TRUE) {
printf(\"> \");
line = GetLine();
ch = toupper(line[0]);
switch (ch) {
case \'I\': insert(); break;
case \'F\': find(); break;
case \'D\': delete(); break;
case \'LI\': listInorder; break;
case \'LPR\': listPreorder(); break;
case \'LPO\': listPostorder(); break;
case \'MAX\': max(); break;
case \'min\': min(); break;
case \'H\': height(); break;
case \'C\': count(); break;
case \'S\': sum(); break;
case \'Q\': exit(0);
default:printf(\"Illegal command\ \"); break;
}
}
}
nodeT *FindNode(nodeT *t, int key){
while(t !=NULL) {
if (key == t->key) return t;
if (key < t->key) {
t = t->left;
} else {
t = t->right;
}
return NULL;
}
void delete(nodeT **p){
nodeT
*target;
target=*p;
if (target->left==NULL && target->right==NULL) {
*p=NULL;
} else if (target->left == NULL) {
*p=target->right;
} else
if (target->right == NULL) {
*p=target->left;
} else {
/* target has two children, see next slide */
}
free(target);
}
void listInorder(nodeT *T){
if (t != NULL) {
DisplayTree(t->left);
printf(“%d “, t->key);
DisplayTree(t->right);
}
}
void listPreorder(nodeT *t) {
if (t != NULL) {
printf(“%d “, t->key);
DisplayTree(t->left);
DisplayTree(t->right);
}
}
void listPostOrder(nodeT *t){
if (t != NULL) {
DisplayTree(t->left);
DisplayTree(t->right);
printf(“%d “, t->key);
}
}
void intsert(nodeT **tptr, int key){
nodeT*t, *tmp;
t=*tptr;
if (t == NULL) {
tmp=New(nodeT*);
tmp->key = key;
tmp->left=tmp->right=NULL;
*tptr=tmp;
return;
}
if (key < t->key) {
InsertNode
(&t->left, key);
} else {
InsertNode(&t->right, key);
}
}
int height(nodeT *t){
if (t == NULL)
return 0;
else
return (1 + maximumof(
height(t->left),
height(t->right)) );
}
int sum(struct tree_node *p){
if (p == NULL)
return 0;
else
return (p->data +
sum(p->left) +
sum(p->right) );
}
Solution
1. /*
2. * Java Program to Implement Binary Search Tree
3. */
4.
5. import java.util.Scanner;
6.
7. /* Class BSTNode */
8. cl.
I have compilation errors that I'm struggling with in my code- please.pdfColinjHJParsonsa
I have compilation errors that I'm struggling with in my code, please can you help me fix the
errors. I'm trying to make a road map, where each place is a vertex and each road between two
places is an edge. Each edge stores a number indicating the length of the road. Assume that there
is at most one road directly connecting two given places, so that there is at most one edge
between two vertices. The map is loaded in via a text file that starts with a line that contains the
number of vertices and the number of edges. After the line mentioned, there are two sections of
content. The initial section holds details regarding the vertices, where each line represents a
single vertex. The information stored for each vertex includes its name and the availability of
charging stations, represented as an integer with 1 indicating availability and 0 indicating
unavailability. The second section stores information about the edges, with each line
corresponding to one edge. Each line contains three numbers: the first two are 0-based indices of
its two incident vertices within the places array; the last number is the edge length. An example
of the map input would look like this as a txt file:
import java.util.*;
import java.io.*;
class Vertex {
// Constructor: set name, chargingStation and index according to given values,
// initilaize incidentRoads as empty array
public Vertex(String placeName, boolean chargingStationAvailable, int idx) {
name = placeName;
incidentRoads = new ArrayList<Edge>();
index = idx;
chargingStation = chargingStationAvailable;
}
public String getName() {
return name;
}
public boolean hasChargingStation() {
return chargingStation;
}
public ArrayList<Edge> getIncidentRoads() {
return incidentRoads;
}
// Add a road to the array incidentRoads
public void addIncidentRoad(Edge road) {
incidentRoads.add(road);
}
public int getIndex() {
return index;
}
private String name; // Name of the place
private ArrayList<Edge> incidentRoads; // Incident edges
private boolean chargingStation; // Availability of charging station
private int index; // Index of this vertex in the vertex array of the map
}
class Edge {
public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) {
length = roadLength;
incidentPlaces = new Vertex[] { firstPlace, secondPlace };
}
public Vertex getFirstVertex() {
return incidentPlaces[0];
}
public Vertex getSecondVertex() {
return incidentPlaces[1];
}
public int getLength() {
return length;
}
private int length;
private Vertex[] incidentPlaces;
}
// A class that represents a sparse matrix
public class RoadMap {
// Default constructor
public RoadMap() {
places = new ArrayList<Vertex>();
roads = new ArrayList<Edge>();
}
// Auxiliary function that prints out the command syntax
public static void printCommandError() {
System.err.println("ERROR: use one of the following commands");
System.err.println(" - Load a map and print information:");
System.err.println(" java RoadMap -i <MapFile>");
System.err.println(" - Load a map an.
Write CC++ a program that inputs a weighted undirected graph and fi.pdf4babies2010
Write a shell command to search all the files in the working directory with names containing one
character extension for the lines that does not start with a character A or character B.
Solution
Answer:
#!/bin/bash
# to search all the files in the working directory with names containing one character extension
#for the lines that does not start with a character A or character B
find . -type f -name \"*.?\" | -not -name \'[ac]*\' -type f.
Need to revise working code below,A good design means the applicat.pdfarchgeetsenterprises
Need to revise working code below,
A good design means the application should scale easily -- that is, the application should be
designed so that additional processing requirements can be added without making having to
rewrite the application each time. Revise code below to add the following design features:
Move the code to display the menu to it\'s own method.
Create a method to handle capturing the shape dimensions. One approach may be to pass to the
method the dimension to enter (\"base\", \"height\", \"side\" or \"radius\") as a String.
Processing for each of the shapes matched in the switch statement should also be moved to their
own methods.
Notes -
The program should \"look and feel\" like the code below.
The program should display the menu and prompt the user for a shape (or an exit).
If the user enters a value that corresponds to a shape, program control (via the switch statement)
should transfer control to a method specific to the shape that will pass control to prompt for the
appropriate dimensions to another method, then calculate the area and perimeter (circumference)
as directed in PLP06, and display the result.
The program should repeat from step 1 above.
import java.util.Scanner;
public class Pickashape {
//Declaring constant
public static final double PI = 3.14159;
public static void main(String[] args) {
//Declaring variable
int choice;
//Scanner class Obejct is used to read the inputs entered by the user
Scanner sc = new Scanner(System.in);
//This loop continues to execute until user enters choice \'5\'
do {
//Displaying the menu
System.out.println(\"\ \ Choose the shape\");
System.out.println(\"1. Square\");
System.out.println(\"2. Rectangle\");
System.out.println(\"3. Circle\");
System.out.println(\"4. Triangle\");
System.out.println(\"5. Quit\");
System.out.print(\"Enter your choice:\");
choice = sc.nextInt();
//Based on the User selection the corresponding case will be executed
switch (choice) {
//This case will calculate the area and perimeter of the square
case 1: {
//Declaring variables
double side, area, perimeter;
//Getting the side of the square entered by the user
System.out.print(\"Enter the side (as a decimal):\");
side = sc.nextDouble();
//calculating the area of the square
area = side * side;
//calculating the perimeter of the square
perimeter = 4 * side;
//Displaying the area of the square
System.out.println(\"The area is \" + area);
//Displaying the perimeter of the square;
System.out.println(\"The perimeter is \" + perimeter);
break;
}
case 2: {
//Declaring variables
double firstside, secondside, area, perimeter;
//Getting the first side of the rectangle
System.out.print(\"Enter the first side (as a decimal):\");
firstside = sc.nextDouble();
//Getting the second side of the rectangle
System.out.print(\"Enter the second side (as a decimal):\");
secondside = sc.nextDouble();
//Calculating the area of the rectangle
area = firstside * secondside;
//Calculating the perimeter of the rectangle
perimeter = 2 * fi.
This document provides code for algorithms to solve the Travelling Salesman Problem (TSP) using different approaches:
1) Brute force exhaustive enumeration that calculates the route length for every possible permutation to find the shortest route.
2) Stochastic optimization that starts with a random route and iteratively improves it by swapping pairs of cities and evaluating new routes to find shorter ones.
3) Main code implements the pair swapping approach, generating new routes by swapping city pairs n times and returning the shortest route found.
This document provides a summary of new features in JavaScript, including let/const block scoping, arrow functions, template strings, classes, generators, async/await, and more. It explains each feature in 1-3 sentences and includes code examples.
This document contains code for several Java programs that perform various calculations and operations:
1. A FiveNumberSum program that declares integer variables, sums 5 numbers, and prints the result.
2. An ArithmeticTest program that performs arithmetic operations (addition, subtraction, multiplication, division, remainder) on two integers, prints the results, and demonstrates increment/decrement operators.
3. Additional programs include ones for a triangle class/tester, decimal-binary conversions, trigonometric functions, and determining if a number is odd or even.
The document discusses functions in C++ and provides examples of defining and calling functions. It explains that a function allows structuring programs in a modular way and accessing structured programming capabilities. A function is defined with a return type, name, parameters, and body. Parameters allow passing arguments when calling the function. The function examples demonstrate defining an addition function, calling it from main to add two numbers and return the result. It also covers function scope, with local variables only accessible within the function and global variables accessible anywhere.
C++ BinaryTree Help Creating main function for Trees...Here are .pdfforecastfashions
C++ BinaryTree Help : Creating main function for Trees...
Here are the header files :
PrintExpressionTour.H:
#ifndef _PRINTEXPRESSIONTOUR_H_
#define _PRINTEXPRESSIONTOUR_H_
#include \"EulerTour.h\"
#include
template
class PrintExpressionTour : public EulerTour {
protected: // ...same type name shortcuts as in EvaluateExpressionTour
public:
inline void execute( const BinaryTree& T ) { // execute the tour
initialize( T );
std::cout << \"Expression: \"; eulerTour( T.root() ); std::cout << std::endl;
}
protected: // leaf: print value
virtual void visitExternal( const Position& p, Result& r ) const {
std::cout << *p;
}
// left: open new expression
virtual void visitLeft( const Position& p, Result& r ) const {
std::cout << \"(\";
}
// below: print operator
virtual void visitBelow( const Position& p, Result& r ) const {
std::cout << *p;
}
// right: close expression
virtual void visitRight( const BinaryTree::Position& p, Result& r ) const {
std::cout << \")\";
}
};
#endif // _PRINTEXPRESSIONTOUR_H_
BinaryTree.h:
#ifndef _BINARYTREE_H_
#define _BINARYTREE_H_
#include
#include
typedef std::string Elem; // base element type
class BinaryTree {
protected:
struct Node { // a node of the tree
Elem elt; // element value
Node* par; // parent
Node* left; // left child
Node* right; // right child
Node() : elt(), par( NULL ), left( NULL ), right( NULL ) {} // constructor
};
public:
class Position { // position in the tree
private:
Node* v; // pointer to the node
public:
Position( Node* _v = NULL ) : v( _v ) {} // constructor
Elem& operator*() const // get element
{
return v->elt;
}
Position left() const // get left child
{
return Position( v->left );
}
Position right() const // get right child
{
return Position( v->right );
}
Position parent() const // get parent
{
return Position( v->par );
}
bool isRoot() const // root of the tree?
{
return v->par == NULL;
}
bool isExternal() const // an external node?
{
return v->left == NULL && v->right == NULL;
}
friend class BinaryTree; // give tree access
};
typedef std::list PositionList; // list of positions
public:
BinaryTree(); // constructor
int size() const; // number of nodes
bool empty() const; // is tree empty?
Position root() const; // get the root
PositionList positions() const; // list of nodes
void addRoot(); // add root to empty tree
void expandExternal( const Position& p ); // expand external node
Position removeAboveExternal( const Position& p ); // remove p and parent
// housekeeping functions omitted...
protected: // local utilities
void preorder( Node* v, PositionList& pl ) const; // preorder utility
private:
Node* _root; // pointer to the root
int n; // number of nodes
};
#endif // _BINARYTREE_H_
EulerTour.h:
#ifndef _EULERTOUR_H_
#define _EULERTOUR_H_
#include \"BinaryTree.h\"
template // element and result types
class EulerTour { // a template for Euler tour
protected:
struct Result { // stores tour results
R leftResult; // result from left subtree
R rightResult; // result from right subtree
R finalR.
#include
#include
#include //scanf,printf
#include
#include //istringstream
using namespace std;
//maps
#include \"MapGeneric.h\"
#include \"MapTriple.h\"
#include \"MapAbsoluteValue.h\"
#include \"MapSquare.h\"
//filters
#include \"FilterGeneric.h\"
#include \"filterEven.h\"
#include \"filterPositive.h\"
#include \"filterPositiveTwoDigit.h\"
//reduce
#include \"ReduceGeneric.h\"
#include \"ReduceMinimum.h\"
#include \"ReduceGCD.h\"
int main()
{
deque L,L1,L2;
int i;
string line;
getline(cin,line);
if(line.size() == 0)
return 0;
line.erase(remove(line.begin(), line.end(), \',\'), line.end());
istringstream s(line);
while(s>>i)
{
L.push_back(i);
}
if(L.size() != 20)
return 0;
//converting L -> 3*|L| aka L1
MapTriple triple; MapAbsoluteValue abs;
L1 = triple.map(abs.map(L));
//converting L1 -> positive two digit integers -> even intergers aka L2
filterEven even; filterPositiveTwoDigit p2;
L2 = p2.filter(L1);
if(L2.size() <2)
return 0;
L2 = even.filter(L2);
if(L2.size() <2)
return 0;
//finding the minimum and GCD from L2 respectively
ReduceMinimum min; ReduceGCD gcd;
printf(\"%d %d\ \",min.reduce(L2),gcd.reduce(L2));
}
FilterGeneric.cpp
#include
#include
#include \"FilterGeneric.h\"
using namespace std;
deque FilterGeneric::filter(deque deq)
{
//calling recursive function with deq and its length
select(deq,deq.size()-1);
return filterDeq;
}
//int i is the index that will start from the length of deque till 0
void FilterGeneric::select(deque deq, int i)
{
if(i == 0)
{
bool val = f(deq[i]);
if(val)
filterDeq.push_front(deq[i]);
return;
}
bool val = f(deq[i]);
if(val)
filterDeq.push_front(deq[i]);
return select(deq,i-1);
}
FilterGeneric.h
#ifndef FILTERGENERIC_H
#define FILTERGENERIC_H
#include
class FilterGeneric
{
public:
std::deque filter(std::deque);
void select(std::deque,int);
protected:
//this deque will store the integers after filtration.
std::deque filterDeq;
private:
virtual bool f(int)=0;
};
#endif
MapAbsoluteValue.cpp
#include
#include
#include
#include \"MapGeneric.h\" //base
#include \"MapAbsoluteValue.h\"
using namespace std;
int MapAbsoluteValue::f(int num)
{
return abs(num);
}
MapAbsoluteValue.h
#ifndef MAPABSOLUTEVALUE_H
#define MAPABSOLUTEVALUE_H
#include
//this class will map a given input N, using the function map(input), to |N|
class MapAbsoluteValue: public MapGeneric
{
public:
//overwriting pure virtual function making N -> |N|
int f(int);
private:
};
#endif
MapGeneric.cpp
#include
#include
#include \"MapGeneric.h\"
using namespace std;
deque MapGeneric::map(deque deq)
{
//calling recursive function with deq and its length
calculate(deq,deq.size()-1);
return mapDeq;
}
//int i is the index that will start from the length of deque till 0
void MapGeneric::calculate(deque deq, int i)
{
if(i == 0)
{
int val = f(deq[i]);
mapDeq.push_front(val);
return;
}
int val = f(deq[i]);
mapDeq.push_front(val);
return calculate(deq,i-1);
}
MapGeneric.h
#ifndef MAPGENERIC_H
#define MAPGENERIC_H
#include
class MapGeneric
{
public:
std::deque ma.
This document provides an overview of ES6 (ECMAScript 2015) features including: let, const and var; template strings; arrow functions; destructuring; default parameters; rest and spread syntax; iterators; classes; modules; maps, sets, weakmaps and weaksets; promises; and more. It explains each feature and provides code examples to demonstrate usage and differences from ES5. Browser compatibility notes are also included to advise on safe usage of new features across environments.
Using an Array include ltstdiohgt include ltmpih.pdfgiriraj65
Using an Array:
#include <stdio.h>
#include <mpi.h>
int main(int argc, char** argv) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Define topology
int topology[5][2] = {{1, 4}, {0, 2, 3}, {1,-1}, {0, 4}, {0, 3}};
// Initialize index and edge arrays
int index[5] = {0};
int edges[5][3] = {{0}};
// Add edges into index array
int i =0;
int j =0;
for (i = 0; i < 5; i++)
{
index[i] = sizeof(topology[i]) / sizeof(int);
for (j = 0; j < index[i]; j++)
{
edges[i][j] = topology[i][j];
}
}
// Display topology for each process
for (i = 0; i < size; i++)
{
if (rank == i)
{
printf("Process %d has %d neighbors: ", i, index[i]);
for (j = 0; j < index[i]; j++)
{
printf("%d ", edges[i][j]);
}
printf("n");
}
MPI_Barrier(MPI_COMM_WORLD);
}
MPI_Finalize();
return 0;
}
MPI Functions:
#include <mpi.h>
#include <stdio.h>
int main(int argc, char** argv)
{
int rank, size;
MPI_Init(&argc, &argv); // Initialize MPI
MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get the rank of the current process
MPI_Comm_size(MPI_COMM_WORLD, &size); // Get the total number of processes
int nnodes = 5; // Number of nodes in the topology
int nedges = 8; // Number of edges in the topolofy
// Index of the first edge for each node
int index[5] = {2, 5, 6, 8, 9};
int edges[9] = {4, 1, 0, 2, 3, 1, 4, 0, 3}; // List of all edges
MPI_Comm graph_comm; // Create a new communicator for the graph topology
MPI_Graph_create(MPI_COMM_WORLD, nnodes, index, edges, 0, &graph_comm); // Create the
graph topology
int count; // Number of neighbors
int* neighbors; // Neighbor Ranks
MPI_Graph_neighbors_count(graph_comm, rank, &count); // Get the number of neighbors for the
current process
neighbors = (int*) malloc(count * sizeof(int)); // Allocate memory for the array of neighbor ranks
MPI_Graph_neighbors(graph_comm, rank, count, neighbors); // Get the neighbor ranks for the
current process
// Display process and the node in the topologies neighbors
printf("Process %d has %d neighbors:", rank, count);
int i;
for (i = 0; i < count; i++)
{
printf(" %d", neighbors[i]); // Print the neighbor ranks
}
printf("n");
MPI_Finalize();
return 0;
}
ive provided my own code above in case that helps or makes it easier on you guys.
My output isnt quite right ive been at it for a while if someone could fix the output and explain it to
me id be very happy :)
4. Use Graph topology to create following one. Once you create your topology, use one process
(e.g., process 0 ) to display the number of neighbors and its neighbors at each node (i.e.,
process). Use following two methods to check your topology. (20 points) i) Use two arrays, index
and edges, to display number of neighbors and its neighbors for each node. ii) Use two functions
in MPI, "MPI Graph neighbors count" and "MPI Graph neighbors". llinn@scholar-fe06: /470 $
mpirun -n 5 ./hmwk5q4-b Process 0 has 2 neighbors: 41 Process 1 has 3 neighbors: 023 Process
2 has 1 neighbors: 1 Process 3 has 2 neighbors: 40.
Im having trouble figuring out how to code these sections for an a.pdfrishteygallery
I\'m having trouble figuring out how to code these sections for an assignment... (Sections 4 and 5
are in a .cpp file without a main. Section 6 is in a seperate file that\'s only purpose is to test using
a main method.) For further information, a link to the assignment can be found here -
http://www.cs.ecu.edu/~karl/2530/fall16/Assn/Assn6/assn6.html
4. Reading the Graph
Document and define a function to read a graph. Use the adjacency list representation. Only store
the graph once.
5. Printing a Graph
Document and define a function to print a graph. .
6. Testing
Test reading and echoing the graph. Do not move on until you are satisfied that this much works.
(Testing is done in the main method, not the .cpp file).
How would I code this using the following code?
#include
using namespace std;
struct Edge{
int vertexNumber;
int weight;
struct Edge* next;
Edge( int vn, int wgt, struct Edge* nxt ){
vertexNumber = vn;
weight = wgt;
next = nxt;
};
};
struct Vertex{
struct Edge* adjacencyList;
double shortestDistance;
int vertexNumber;
Vertex(){
vertexNumber = shortestDistance = -1;
adjacencyList = NULL;
}
};
struct Graph{
int nVertices;
int nEdges;
struct Vertex* vertices;
Graph( int nVert ){
vertices = new struct Vertex[nVert];
nEdges = 0;
}
};
typedef struct Edge Edge;
typedef struct Vertex Vertex;
typedef struct Graph Graph;
int main(){
}
4. Reading the Graph
Document and define a function to read a graph. Use the adjacency list representation. Only
store the graph once.
5. Printing a Graph
Document and define a function to print a graph. .
6. Testing
Test reading and echoing the graph. Do not move on until you are satisfied that this much
works.
(Testing is done in the main method, not the .cpp file).
Solution
4)
// A C Program to demonstrate adjacency list representation of graphs
#include
#include
// A structure to represent an adjacency list node
struct AdjListNode
{
int dest;
struct AdjListNode* next;
};
// A structure to represent an adjacency list
struct AdjList
{
struct AdjListNode *head; // pointer to head node of list
};
// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
int V;
struct AdjList* array;
};
// A utility function to create a new adjacency list node
struct AdjListNode* newAdjListNode(int dest)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// A utility function that creates a graph of V vertices
struct Graph* createGraph(int V)
{
struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;
// Create an array of adjacency lists. Size of array will be V
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
// Initialize each adjacency list as empty by making head as NULL
int i;
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}
// Adds an edge to an undirected graph
void addEd.
Using Java, please write the program for the following prompt in the.pdfforecastfashions
Using Java, please write the program for the following prompt in the first picture. The second
and third picture show a sample execution of the program. Collections and generics are
acceptable to use. You just cannot use java methods to iterate through an array list, it must be
iterated through using a for loop. Thank you! A. Objectives l Use at least one array of Strings.
(10 points) 2. Use at least one 2-dimensional array. (10 points) 3. Use sorting to arrange data. (10
points) 1. Use methods to do separate and rcpetitive work. The main method should not have
more than 20 lines of code (10 points) 5. Implement the project correctly. (50 points) 10 points
will be awarded for use of meaningful identificrs, consistent indentation, cxplanatory comments
in your code and properly formatted output. B. Description Each spring brings hope for National
Football League (NFL) teams, especially for those that had poor win-loss records in the previous
season. The NFL draft is held in April and is the opportunity for teams to improve their roster by
adding those college players considered to be the most talented in the world NFL teams develop
their player rosters through three methods: free-agent signings, trading their players for players
from other teams, and drafting college players who have doclared themselves oligiblc for the
NFL draft. The NFL draft is a two-day event in which all 32 teams take their turns selecting
these players. In this project we are going to simulate a limited version of the draft process. This
simulated draft would involve 8 teams and 32 players. Pick any 8 teams from the actual NFL and
32 players of your choice. Be creative! l. Assign a random winning percentage to each of the
teams for the previous season. 2. Based on the winning percentage, rank the teams in order
starting with the one that had the worst performance 3. Each team can now select players in the
order they were ranked 4, Assign numbers l to 4 to the players randomly indicating the round in
which they can be picked. 5. In each round, the teams in order of their numbers will choose
randomly from the players eligible for that round and select them. 6. At thc end of 4 rounds, cach
of the 8 teams will have 4 players they picked.
Solution
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.util.*;
//Primary class for the game
public class Asteroids extends Applet implements Runnable, KeyListener{
/**
*
*/
private static final long serialVersionUID = 1L;
//the main thread becomes the game loop
Thread gameloop;
//use this as a double buffer
BufferedImage backbuffer;
//the main drawing object for the back buffer
Graphics2D g2d;
//toggle for drawing bounding boxes
boolean showBounds = false;
//create the asteroid array
int ASTEROIDS = 20;
Asteroid[] ast = new Asteroid[ASTEROIDS];
//create the bullet array
int BULLETS = 10;
Bullet[] bullet = new Bullet[BULLETS];
int currentBullet = 0;
//the player\'.
need help with code I wrote. This code is a maze gui, and i need hel.pdfarcotstarsports
need help with code I wrote. This code is a maze gui, and i need help with the method
shorterstpath(); here is my code:
******mazeApp*******
package mazepackage;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TextInputDialog;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MazeApp extends Application
{
// default canvas size is DEFAULT_SIZE-by-DEFAULT_SIZE
private static final int DEFAULT_SIZE = 768;
private int width = DEFAULT_SIZE;
private int height = DEFAULT_SIZE;
// The graphics context is needed to enable drawing on the canvas
private GraphicsContext gc;
// boundary of drawing canvas, 0% border
// private static final double BORDER = 0.05;
private static final double BORDER = 0.00;
private double xmin, ymin, xmax, ymax;
public static void main(String[] args)
{
launch(args);
}
@Override
public void start(Stage primaryStage)
{
Group root = new Group();
Canvas canvas = new Canvas(width, height);
gc = canvas.getGraphicsContext2D();
gc.setLineWidth(2);
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, width, height);
root.getChildren().add(canvas);
TextInputDialog tid = new TextInputDialog();
tid.setTitle(\"Maze Size\");
tid.setHeaderText(\"Enter maze size between 10 and 50\");
tid.showAndWait();
int size = Integer.parseInt(tid.getResult());
if (size > 50)
size = 50;
if (size < 10)
size = 10;
primaryStage.setTitle(\"Maze Application\");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
// Make sure that the application goes away when then window is closed
primaryStage.setOnCloseRequest(e -> System.exit(0));
primaryStage.show();
Maze maze = new Maze(this, size);
// Must solve the maze in a separate thread or else
// the GUI wont update until the end.....
Thread solver = new Thread(
new Runnable () {
public void run()
{
while(true)
{
maze.buildAndDrawMaze();
maze.findShortestPath();
try
{
Thread.sleep(5000);
}
catch(Exception e) { }
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, width, height);
}
}
});
solver.start();
}
/**
* Sets the pen color to the specified color.
*
* @param color the color to make the pen
*/
public void setPenColor(Color color) {
gc.setStroke(color);
}
/**
* Sets the pen color to the specified color.
*
* @param color the color to make the pen
*/
public void setFillColor(Color color) {
gc.setFill(color);
}
/**
* Sets the x-scale to the specified range.
*
* @param min the minimum value of the x-scale
* @param max the maximum value of the x-scale
* @throws IllegalArgumentException if {@code (max == min)}
*/
public void setXscale(double min, double max) {
double size = max - min;
if (size == 0.0) {
throw new IllegalArgumentException(\"the min and max are the same\");
}
xmin = min - BORDER * size;
xmax = max + BORDER * size;
}
/**
* Sets the y-scale to the specified range.
*
* @param min the minimum valu.
Create the equivalent of a four function calculator. The program should request the user to enter a number, an operator, and another number. carry out the specified arithmetical operation: adding, subtracting, multiplying, or dividing the two numbers. (Using switch statement ).ThesisScientist.com
Deeplearn.js is a deep learning library that runs models in the browser using WebGL acceleration. It represents models as computation graphs of nodes and tensors. Kernels are implemented to run operations on GPUs or CPUs. The library can import models from TensorFlow and allows both training and inference. Future work includes directly importing TensorFlow models and improving demos.
i have written ths code as per your requirements with clear comments.pdfanandf0099
i have written ths code as per your requirements with clear comments as shown below with
output
package com.sanfoundry.hardgraph;
import java.util.Scanner;
import java.util.Vector;
class Node1
{
int name; // node ID, started from 0 to n-1
Vector preds; // predecessors (String)
Vector neibs; // neighbors (String)
Vector backs; // backward edges -node is end vertex (Integer)
Vector fors; // forward edges -node is start vertex (Integer)
int pNode; // previous node on the augmenting path
int pEdge; // from which edge this node comes on the augmenting
// path
public Node1(int id)
{
name = id;
backs = new Vector();
fors = new Vector();
pNode1 = -1;
pEdge = -1;
}
}
class Edge
{
int name; // edge ID, started from 0 to n-1
int start; // start vertex of this edge
int end; // end vertex of this edge
int direct; // forwards (+1) or backwards (-1) on augmenting path
// if 0 then not part of augmenting path
int capacity; // capacity
int flow; // current flow
public Edge(int id)
{
name = id;
start = -1;
end = -1;
direct = 0; // default is neither
capacity = 0;
flow = 0;
}
public String toString()
{
return name + \": s=\" + start + \" e=\" + end + \" d=\" + direct;
}
}
public class LongestPathinDAG
{
int n; // number of nodes
int target; // destination node
int minLength; // the minimal length of each path
Node1[] v; // used to store Nodes
Edge[] e; // used to store Edges
int[] path; // used to store temporary path
int length = 0; // length of the path
int distance = 0; // distance of the path
int[] bestPath; // used to store temporary path
int bestLength = 0; // length of the longest path
int bestDistance = -1000000; // distance of the longest path
int[] visited; // used to mark a node as visited if set as
// 1
public LongestPathinDAG()
{
Scanner sc = new Scanner(System.in);
System.out.println(\"Enter the number of vertices: \");
n = sc.nextInt();
System.out.println(\"Enter the number of edges: \");
int m = sc.nextInt();
v = new Node1[n];
e = new Edge[m];
System.out.println(n + \" nodes and \" + m + \" edges.\");
for (int i = 0; i < n; i++)
v[i] = new Node1(i);
int i = 0;
while (i < e.length)
{
Edge edge = new Edge(i);
int sVal = sc.nextInt();
edge.start = sVal;// sc.nextInt();
int eVal = sc.nextInt();
edge.end = eVal;// sc.nextInt();
edge.capacity = sc.nextInt();
System.out.println(\" edge: \" + edge.start + \" - \" + edge.end
+ \" : \" + edge.capacity);
edge.flow = 0;
e[i] = edge;
v[sVal].fors.add(i);
v[eVal].backs.add(i);
i++;
if (i == m)
break;
}
visited = new int[v.length];
path = new int[v.length];
bestPath = new int[v.length];
sc.close();
}
/*
* this function looks for a longest path starting from being to end,
* using the backtrack depth-first search.
*/
public boolean findLongestPath(int begin, int end, int minLen)
{
/*
* compute a longest path from begin to end
*/
target = end;
bestDistance = -100000000;
minLength = minLen;
dfsLongestPath(begin);
if (bestDistance == -100000000)
return false;
else
return true;
}
private void dfsLongestPath(int curr.
The document contains instructions for 15 computer graphics experiments to be completed in a Computer Graphics lab course. The experiments include programs to draw lines and shapes using algorithms like DDA, Bresenham, midpoint circle and ellipse algorithms. Programs for transformations like rotation, translation, scaling and shearing of shapes are also included. Boundary fill and flood fill algorithms are among the programs listed.
Pointers allow programs to store and manipulate memory addresses. A pointer variable contains the address of another variable. Pointers are useful for passing data between functions, returning multiple values from functions, and dynamically allocating memory at runtime. Pointers can also be used to access elements of arrays indirectly and implement multidimensional arrays more efficiently. Pointer notation provides an alternative way to access array elements through pointer arithmetic rather than subscripts.
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
Today, we almost exclusively think of code in software projects as a collection of text files. The tools that we use (version control systems, IDEs, code analyzers) also use text as the primary storage format for code. In fact, the belief that “code is text” is so deeply ingrained in our heads that we never question its validity or even become aware of the fact that there are other ways to look at code.
In my talk I will explain why treating code as text is a very bad idea which actively holds back our understanding and creates a range of problems in large software projects. I will then show how we can overcome (some of) these problems by treating and storing code as data, and more specifically as a graph. I will show specific examples of how we can use this approach to improve our understanding of large code bases, increase code quality and automate certain aspects of software development.
Finally, I will outline my personal vision of the future of programming, which is a future where we no longer primarily interact with code bases using simple text editors. I will also give some ideas on how we might get to that future.
Apache Flink Training: DataStream API Part 2 Advanced Flink Forward
Flink can handle many data types and provides a type system to identify types for serialization and comparisons. Composite types like Tuples and POJOs can be used and fields within them can define keys. Windows provide a way to perform aggregations over finite slices of infinite streams. Connected streams allow correlating and joining multiple streams. Stateful functions have access to local and partitioned state for stateful stream processing. Kafka integration allows consuming from and producing to Kafka topics.
This is Function Class public abstract class Function { .pdfamitbagga0808
This document describes a Java program that graphs functions. It includes abstract Function and GraphManager classes, and subclasses that implement specific functions. The GraphManager handles function selection and calculating graph extents. The GUI displays the functions, prompts the user to select one and input bounds, and calls GraphManager to draw the function on a Canvas between the bounds. Any errors from user input are caught and handled.
This document discusses binary search trees and provides source code to implement binary search tree traversal operations. It explains that a binary search tree is a binary tree where the left child of a node is less than the parent and the right child is greater. It provides code for preorder, inorder, and postorder traversals of the binary search tree and outputs the traversal order for a sample tree.
SaveI need help with this maze gui that I wrote in java, I am tryi.pdfarihantstoneart
Save
I need help with this maze gui that I wrote in java, I am trying to find the shortest path but I dont
know how to implement the FindshortestPath Method.
I was given this as a stragedy to solve the findshortestpathMethod():
Create two LinkedLists of MazeMap objects. One will be the list of map objects for cells at
distance x from the center. The other will be the list of map objects for cells at distance x + 1.
Initialize the list at distance x to contain a MazeMap object which refers to the center cell of the
maze. Since this map object refers to the center cell, it does not need to refer to any other
MazeMap object, so its MazeMap reference can be set to null. Set the center cell’s visited field
to true to indicate that this cell has already been added to the map.
Set up a loop to run until the maze entrance is mapped. This loop does the following:
Set up a loop to process each map object from the list at distance x. This loop does the following:
i.Get the cell from the map object
ii.If this cell is the entrance cell, set the entrance and break out of the loop!
iii.Check each direction from this cell and for an accessible neighbor cell
Get a reference to that neighbor cell
If the neighbor cell has not already been visited
Set the cell’s visited field to true so its only processed once
Create a MazeMap object that refers to this neighbor cell
Make this MazeMap object refer to the current map object being processed – ie the cell one step
closer to center
Add this MazeMap object to the list at distance x + 1
List at distance x has been processed. The list at distance x + 1 is now complete, so make the list
at distance x refer to list at distance x + 1. Then create a new empty list for the list at distance x +
1.
At this point, the entrance points at the map object which refers to cell 1,1. That map object also
refers to a map object which is one step closer to the center. Write a loop that traverses this trail
of references until it reaches the end (a null reference). For each map object:
Get the cell referred to.
Call the drawCircle method with a color, the cell’s row and column, and SMALL.
Call the delay method with a SHORT delay. This slows down the drawing process so you can
watch the path being displayed.
Advance to the next map object in the list.
here is the code so far*********
here is my code: ******mazeApp*******
package mazepackage;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TextInputDialog;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MazeApp extends Application
{
// default canvas size is DEFAULT_SIZE-by-DEFAULT_SIZE
private static final int DEFAULT_SIZE = 768;
private int width = DEFAULT_SIZE;
private int height = DEFAULT_SIZE;
// The graphics context is needed to enable drawing on the canvas
private Graphics.
Discover the Beauty and Functionality of The Expert Remodeling Serviceobriengroupinc04
Unlock your kitchen's true potential with expert remodeling services from O'Brien Group Inc. Transform your space into a functional, modern, and luxurious haven with their experienced professionals. From layout reconfiguration to high-end upgrades, they deliver stunning results tailored to your style and needs. Visit obriengroupinc.com to elevate your kitchen's beauty and functionality today.
This document provides a summary of new features in JavaScript, including let/const block scoping, arrow functions, template strings, classes, generators, async/await, and more. It explains each feature in 1-3 sentences and includes code examples.
This document contains code for several Java programs that perform various calculations and operations:
1. A FiveNumberSum program that declares integer variables, sums 5 numbers, and prints the result.
2. An ArithmeticTest program that performs arithmetic operations (addition, subtraction, multiplication, division, remainder) on two integers, prints the results, and demonstrates increment/decrement operators.
3. Additional programs include ones for a triangle class/tester, decimal-binary conversions, trigonometric functions, and determining if a number is odd or even.
The document discusses functions in C++ and provides examples of defining and calling functions. It explains that a function allows structuring programs in a modular way and accessing structured programming capabilities. A function is defined with a return type, name, parameters, and body. Parameters allow passing arguments when calling the function. The function examples demonstrate defining an addition function, calling it from main to add two numbers and return the result. It also covers function scope, with local variables only accessible within the function and global variables accessible anywhere.
C++ BinaryTree Help Creating main function for Trees...Here are .pdfforecastfashions
C++ BinaryTree Help : Creating main function for Trees...
Here are the header files :
PrintExpressionTour.H:
#ifndef _PRINTEXPRESSIONTOUR_H_
#define _PRINTEXPRESSIONTOUR_H_
#include \"EulerTour.h\"
#include
template
class PrintExpressionTour : public EulerTour {
protected: // ...same type name shortcuts as in EvaluateExpressionTour
public:
inline void execute( const BinaryTree& T ) { // execute the tour
initialize( T );
std::cout << \"Expression: \"; eulerTour( T.root() ); std::cout << std::endl;
}
protected: // leaf: print value
virtual void visitExternal( const Position& p, Result& r ) const {
std::cout << *p;
}
// left: open new expression
virtual void visitLeft( const Position& p, Result& r ) const {
std::cout << \"(\";
}
// below: print operator
virtual void visitBelow( const Position& p, Result& r ) const {
std::cout << *p;
}
// right: close expression
virtual void visitRight( const BinaryTree::Position& p, Result& r ) const {
std::cout << \")\";
}
};
#endif // _PRINTEXPRESSIONTOUR_H_
BinaryTree.h:
#ifndef _BINARYTREE_H_
#define _BINARYTREE_H_
#include
#include
typedef std::string Elem; // base element type
class BinaryTree {
protected:
struct Node { // a node of the tree
Elem elt; // element value
Node* par; // parent
Node* left; // left child
Node* right; // right child
Node() : elt(), par( NULL ), left( NULL ), right( NULL ) {} // constructor
};
public:
class Position { // position in the tree
private:
Node* v; // pointer to the node
public:
Position( Node* _v = NULL ) : v( _v ) {} // constructor
Elem& operator*() const // get element
{
return v->elt;
}
Position left() const // get left child
{
return Position( v->left );
}
Position right() const // get right child
{
return Position( v->right );
}
Position parent() const // get parent
{
return Position( v->par );
}
bool isRoot() const // root of the tree?
{
return v->par == NULL;
}
bool isExternal() const // an external node?
{
return v->left == NULL && v->right == NULL;
}
friend class BinaryTree; // give tree access
};
typedef std::list PositionList; // list of positions
public:
BinaryTree(); // constructor
int size() const; // number of nodes
bool empty() const; // is tree empty?
Position root() const; // get the root
PositionList positions() const; // list of nodes
void addRoot(); // add root to empty tree
void expandExternal( const Position& p ); // expand external node
Position removeAboveExternal( const Position& p ); // remove p and parent
// housekeeping functions omitted...
protected: // local utilities
void preorder( Node* v, PositionList& pl ) const; // preorder utility
private:
Node* _root; // pointer to the root
int n; // number of nodes
};
#endif // _BINARYTREE_H_
EulerTour.h:
#ifndef _EULERTOUR_H_
#define _EULERTOUR_H_
#include \"BinaryTree.h\"
template // element and result types
class EulerTour { // a template for Euler tour
protected:
struct Result { // stores tour results
R leftResult; // result from left subtree
R rightResult; // result from right subtree
R finalR.
#include
#include
#include //scanf,printf
#include
#include //istringstream
using namespace std;
//maps
#include \"MapGeneric.h\"
#include \"MapTriple.h\"
#include \"MapAbsoluteValue.h\"
#include \"MapSquare.h\"
//filters
#include \"FilterGeneric.h\"
#include \"filterEven.h\"
#include \"filterPositive.h\"
#include \"filterPositiveTwoDigit.h\"
//reduce
#include \"ReduceGeneric.h\"
#include \"ReduceMinimum.h\"
#include \"ReduceGCD.h\"
int main()
{
deque L,L1,L2;
int i;
string line;
getline(cin,line);
if(line.size() == 0)
return 0;
line.erase(remove(line.begin(), line.end(), \',\'), line.end());
istringstream s(line);
while(s>>i)
{
L.push_back(i);
}
if(L.size() != 20)
return 0;
//converting L -> 3*|L| aka L1
MapTriple triple; MapAbsoluteValue abs;
L1 = triple.map(abs.map(L));
//converting L1 -> positive two digit integers -> even intergers aka L2
filterEven even; filterPositiveTwoDigit p2;
L2 = p2.filter(L1);
if(L2.size() <2)
return 0;
L2 = even.filter(L2);
if(L2.size() <2)
return 0;
//finding the minimum and GCD from L2 respectively
ReduceMinimum min; ReduceGCD gcd;
printf(\"%d %d\ \",min.reduce(L2),gcd.reduce(L2));
}
FilterGeneric.cpp
#include
#include
#include \"FilterGeneric.h\"
using namespace std;
deque FilterGeneric::filter(deque deq)
{
//calling recursive function with deq and its length
select(deq,deq.size()-1);
return filterDeq;
}
//int i is the index that will start from the length of deque till 0
void FilterGeneric::select(deque deq, int i)
{
if(i == 0)
{
bool val = f(deq[i]);
if(val)
filterDeq.push_front(deq[i]);
return;
}
bool val = f(deq[i]);
if(val)
filterDeq.push_front(deq[i]);
return select(deq,i-1);
}
FilterGeneric.h
#ifndef FILTERGENERIC_H
#define FILTERGENERIC_H
#include
class FilterGeneric
{
public:
std::deque filter(std::deque);
void select(std::deque,int);
protected:
//this deque will store the integers after filtration.
std::deque filterDeq;
private:
virtual bool f(int)=0;
};
#endif
MapAbsoluteValue.cpp
#include
#include
#include
#include \"MapGeneric.h\" //base
#include \"MapAbsoluteValue.h\"
using namespace std;
int MapAbsoluteValue::f(int num)
{
return abs(num);
}
MapAbsoluteValue.h
#ifndef MAPABSOLUTEVALUE_H
#define MAPABSOLUTEVALUE_H
#include
//this class will map a given input N, using the function map(input), to |N|
class MapAbsoluteValue: public MapGeneric
{
public:
//overwriting pure virtual function making N -> |N|
int f(int);
private:
};
#endif
MapGeneric.cpp
#include
#include
#include \"MapGeneric.h\"
using namespace std;
deque MapGeneric::map(deque deq)
{
//calling recursive function with deq and its length
calculate(deq,deq.size()-1);
return mapDeq;
}
//int i is the index that will start from the length of deque till 0
void MapGeneric::calculate(deque deq, int i)
{
if(i == 0)
{
int val = f(deq[i]);
mapDeq.push_front(val);
return;
}
int val = f(deq[i]);
mapDeq.push_front(val);
return calculate(deq,i-1);
}
MapGeneric.h
#ifndef MAPGENERIC_H
#define MAPGENERIC_H
#include
class MapGeneric
{
public:
std::deque ma.
This document provides an overview of ES6 (ECMAScript 2015) features including: let, const and var; template strings; arrow functions; destructuring; default parameters; rest and spread syntax; iterators; classes; modules; maps, sets, weakmaps and weaksets; promises; and more. It explains each feature and provides code examples to demonstrate usage and differences from ES5. Browser compatibility notes are also included to advise on safe usage of new features across environments.
Using an Array include ltstdiohgt include ltmpih.pdfgiriraj65
Using an Array:
#include <stdio.h>
#include <mpi.h>
int main(int argc, char** argv) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Define topology
int topology[5][2] = {{1, 4}, {0, 2, 3}, {1,-1}, {0, 4}, {0, 3}};
// Initialize index and edge arrays
int index[5] = {0};
int edges[5][3] = {{0}};
// Add edges into index array
int i =0;
int j =0;
for (i = 0; i < 5; i++)
{
index[i] = sizeof(topology[i]) / sizeof(int);
for (j = 0; j < index[i]; j++)
{
edges[i][j] = topology[i][j];
}
}
// Display topology for each process
for (i = 0; i < size; i++)
{
if (rank == i)
{
printf("Process %d has %d neighbors: ", i, index[i]);
for (j = 0; j < index[i]; j++)
{
printf("%d ", edges[i][j]);
}
printf("n");
}
MPI_Barrier(MPI_COMM_WORLD);
}
MPI_Finalize();
return 0;
}
MPI Functions:
#include <mpi.h>
#include <stdio.h>
int main(int argc, char** argv)
{
int rank, size;
MPI_Init(&argc, &argv); // Initialize MPI
MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get the rank of the current process
MPI_Comm_size(MPI_COMM_WORLD, &size); // Get the total number of processes
int nnodes = 5; // Number of nodes in the topology
int nedges = 8; // Number of edges in the topolofy
// Index of the first edge for each node
int index[5] = {2, 5, 6, 8, 9};
int edges[9] = {4, 1, 0, 2, 3, 1, 4, 0, 3}; // List of all edges
MPI_Comm graph_comm; // Create a new communicator for the graph topology
MPI_Graph_create(MPI_COMM_WORLD, nnodes, index, edges, 0, &graph_comm); // Create the
graph topology
int count; // Number of neighbors
int* neighbors; // Neighbor Ranks
MPI_Graph_neighbors_count(graph_comm, rank, &count); // Get the number of neighbors for the
current process
neighbors = (int*) malloc(count * sizeof(int)); // Allocate memory for the array of neighbor ranks
MPI_Graph_neighbors(graph_comm, rank, count, neighbors); // Get the neighbor ranks for the
current process
// Display process and the node in the topologies neighbors
printf("Process %d has %d neighbors:", rank, count);
int i;
for (i = 0; i < count; i++)
{
printf(" %d", neighbors[i]); // Print the neighbor ranks
}
printf("n");
MPI_Finalize();
return 0;
}
ive provided my own code above in case that helps or makes it easier on you guys.
My output isnt quite right ive been at it for a while if someone could fix the output and explain it to
me id be very happy :)
4. Use Graph topology to create following one. Once you create your topology, use one process
(e.g., process 0 ) to display the number of neighbors and its neighbors at each node (i.e.,
process). Use following two methods to check your topology. (20 points) i) Use two arrays, index
and edges, to display number of neighbors and its neighbors for each node. ii) Use two functions
in MPI, "MPI Graph neighbors count" and "MPI Graph neighbors". llinn@scholar-fe06: /470 $
mpirun -n 5 ./hmwk5q4-b Process 0 has 2 neighbors: 41 Process 1 has 3 neighbors: 023 Process
2 has 1 neighbors: 1 Process 3 has 2 neighbors: 40.
Im having trouble figuring out how to code these sections for an a.pdfrishteygallery
I\'m having trouble figuring out how to code these sections for an assignment... (Sections 4 and 5
are in a .cpp file without a main. Section 6 is in a seperate file that\'s only purpose is to test using
a main method.) For further information, a link to the assignment can be found here -
http://www.cs.ecu.edu/~karl/2530/fall16/Assn/Assn6/assn6.html
4. Reading the Graph
Document and define a function to read a graph. Use the adjacency list representation. Only store
the graph once.
5. Printing a Graph
Document and define a function to print a graph. .
6. Testing
Test reading and echoing the graph. Do not move on until you are satisfied that this much works.
(Testing is done in the main method, not the .cpp file).
How would I code this using the following code?
#include
using namespace std;
struct Edge{
int vertexNumber;
int weight;
struct Edge* next;
Edge( int vn, int wgt, struct Edge* nxt ){
vertexNumber = vn;
weight = wgt;
next = nxt;
};
};
struct Vertex{
struct Edge* adjacencyList;
double shortestDistance;
int vertexNumber;
Vertex(){
vertexNumber = shortestDistance = -1;
adjacencyList = NULL;
}
};
struct Graph{
int nVertices;
int nEdges;
struct Vertex* vertices;
Graph( int nVert ){
vertices = new struct Vertex[nVert];
nEdges = 0;
}
};
typedef struct Edge Edge;
typedef struct Vertex Vertex;
typedef struct Graph Graph;
int main(){
}
4. Reading the Graph
Document and define a function to read a graph. Use the adjacency list representation. Only
store the graph once.
5. Printing a Graph
Document and define a function to print a graph. .
6. Testing
Test reading and echoing the graph. Do not move on until you are satisfied that this much
works.
(Testing is done in the main method, not the .cpp file).
Solution
4)
// A C Program to demonstrate adjacency list representation of graphs
#include
#include
// A structure to represent an adjacency list node
struct AdjListNode
{
int dest;
struct AdjListNode* next;
};
// A structure to represent an adjacency list
struct AdjList
{
struct AdjListNode *head; // pointer to head node of list
};
// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
int V;
struct AdjList* array;
};
// A utility function to create a new adjacency list node
struct AdjListNode* newAdjListNode(int dest)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// A utility function that creates a graph of V vertices
struct Graph* createGraph(int V)
{
struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;
// Create an array of adjacency lists. Size of array will be V
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
// Initialize each adjacency list as empty by making head as NULL
int i;
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}
// Adds an edge to an undirected graph
void addEd.
Using Java, please write the program for the following prompt in the.pdfforecastfashions
Using Java, please write the program for the following prompt in the first picture. The second
and third picture show a sample execution of the program. Collections and generics are
acceptable to use. You just cannot use java methods to iterate through an array list, it must be
iterated through using a for loop. Thank you! A. Objectives l Use at least one array of Strings.
(10 points) 2. Use at least one 2-dimensional array. (10 points) 3. Use sorting to arrange data. (10
points) 1. Use methods to do separate and rcpetitive work. The main method should not have
more than 20 lines of code (10 points) 5. Implement the project correctly. (50 points) 10 points
will be awarded for use of meaningful identificrs, consistent indentation, cxplanatory comments
in your code and properly formatted output. B. Description Each spring brings hope for National
Football League (NFL) teams, especially for those that had poor win-loss records in the previous
season. The NFL draft is held in April and is the opportunity for teams to improve their roster by
adding those college players considered to be the most talented in the world NFL teams develop
their player rosters through three methods: free-agent signings, trading their players for players
from other teams, and drafting college players who have doclared themselves oligiblc for the
NFL draft. The NFL draft is a two-day event in which all 32 teams take their turns selecting
these players. In this project we are going to simulate a limited version of the draft process. This
simulated draft would involve 8 teams and 32 players. Pick any 8 teams from the actual NFL and
32 players of your choice. Be creative! l. Assign a random winning percentage to each of the
teams for the previous season. 2. Based on the winning percentage, rank the teams in order
starting with the one that had the worst performance 3. Each team can now select players in the
order they were ranked 4, Assign numbers l to 4 to the players randomly indicating the round in
which they can be picked. 5. In each round, the teams in order of their numbers will choose
randomly from the players eligible for that round and select them. 6. At thc end of 4 rounds, cach
of the 8 teams will have 4 players they picked.
Solution
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.util.*;
//Primary class for the game
public class Asteroids extends Applet implements Runnable, KeyListener{
/**
*
*/
private static final long serialVersionUID = 1L;
//the main thread becomes the game loop
Thread gameloop;
//use this as a double buffer
BufferedImage backbuffer;
//the main drawing object for the back buffer
Graphics2D g2d;
//toggle for drawing bounding boxes
boolean showBounds = false;
//create the asteroid array
int ASTEROIDS = 20;
Asteroid[] ast = new Asteroid[ASTEROIDS];
//create the bullet array
int BULLETS = 10;
Bullet[] bullet = new Bullet[BULLETS];
int currentBullet = 0;
//the player\'.
need help with code I wrote. This code is a maze gui, and i need hel.pdfarcotstarsports
need help with code I wrote. This code is a maze gui, and i need help with the method
shorterstpath(); here is my code:
******mazeApp*******
package mazepackage;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TextInputDialog;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MazeApp extends Application
{
// default canvas size is DEFAULT_SIZE-by-DEFAULT_SIZE
private static final int DEFAULT_SIZE = 768;
private int width = DEFAULT_SIZE;
private int height = DEFAULT_SIZE;
// The graphics context is needed to enable drawing on the canvas
private GraphicsContext gc;
// boundary of drawing canvas, 0% border
// private static final double BORDER = 0.05;
private static final double BORDER = 0.00;
private double xmin, ymin, xmax, ymax;
public static void main(String[] args)
{
launch(args);
}
@Override
public void start(Stage primaryStage)
{
Group root = new Group();
Canvas canvas = new Canvas(width, height);
gc = canvas.getGraphicsContext2D();
gc.setLineWidth(2);
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, width, height);
root.getChildren().add(canvas);
TextInputDialog tid = new TextInputDialog();
tid.setTitle(\"Maze Size\");
tid.setHeaderText(\"Enter maze size between 10 and 50\");
tid.showAndWait();
int size = Integer.parseInt(tid.getResult());
if (size > 50)
size = 50;
if (size < 10)
size = 10;
primaryStage.setTitle(\"Maze Application\");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
// Make sure that the application goes away when then window is closed
primaryStage.setOnCloseRequest(e -> System.exit(0));
primaryStage.show();
Maze maze = new Maze(this, size);
// Must solve the maze in a separate thread or else
// the GUI wont update until the end.....
Thread solver = new Thread(
new Runnable () {
public void run()
{
while(true)
{
maze.buildAndDrawMaze();
maze.findShortestPath();
try
{
Thread.sleep(5000);
}
catch(Exception e) { }
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, width, height);
}
}
});
solver.start();
}
/**
* Sets the pen color to the specified color.
*
* @param color the color to make the pen
*/
public void setPenColor(Color color) {
gc.setStroke(color);
}
/**
* Sets the pen color to the specified color.
*
* @param color the color to make the pen
*/
public void setFillColor(Color color) {
gc.setFill(color);
}
/**
* Sets the x-scale to the specified range.
*
* @param min the minimum value of the x-scale
* @param max the maximum value of the x-scale
* @throws IllegalArgumentException if {@code (max == min)}
*/
public void setXscale(double min, double max) {
double size = max - min;
if (size == 0.0) {
throw new IllegalArgumentException(\"the min and max are the same\");
}
xmin = min - BORDER * size;
xmax = max + BORDER * size;
}
/**
* Sets the y-scale to the specified range.
*
* @param min the minimum valu.
Create the equivalent of a four function calculator. The program should request the user to enter a number, an operator, and another number. carry out the specified arithmetical operation: adding, subtracting, multiplying, or dividing the two numbers. (Using switch statement ).ThesisScientist.com
Deeplearn.js is a deep learning library that runs models in the browser using WebGL acceleration. It represents models as computation graphs of nodes and tensors. Kernels are implemented to run operations on GPUs or CPUs. The library can import models from TensorFlow and allows both training and inference. Future work includes directly importing TensorFlow models and improving demos.
i have written ths code as per your requirements with clear comments.pdfanandf0099
i have written ths code as per your requirements with clear comments as shown below with
output
package com.sanfoundry.hardgraph;
import java.util.Scanner;
import java.util.Vector;
class Node1
{
int name; // node ID, started from 0 to n-1
Vector preds; // predecessors (String)
Vector neibs; // neighbors (String)
Vector backs; // backward edges -node is end vertex (Integer)
Vector fors; // forward edges -node is start vertex (Integer)
int pNode; // previous node on the augmenting path
int pEdge; // from which edge this node comes on the augmenting
// path
public Node1(int id)
{
name = id;
backs = new Vector();
fors = new Vector();
pNode1 = -1;
pEdge = -1;
}
}
class Edge
{
int name; // edge ID, started from 0 to n-1
int start; // start vertex of this edge
int end; // end vertex of this edge
int direct; // forwards (+1) or backwards (-1) on augmenting path
// if 0 then not part of augmenting path
int capacity; // capacity
int flow; // current flow
public Edge(int id)
{
name = id;
start = -1;
end = -1;
direct = 0; // default is neither
capacity = 0;
flow = 0;
}
public String toString()
{
return name + \": s=\" + start + \" e=\" + end + \" d=\" + direct;
}
}
public class LongestPathinDAG
{
int n; // number of nodes
int target; // destination node
int minLength; // the minimal length of each path
Node1[] v; // used to store Nodes
Edge[] e; // used to store Edges
int[] path; // used to store temporary path
int length = 0; // length of the path
int distance = 0; // distance of the path
int[] bestPath; // used to store temporary path
int bestLength = 0; // length of the longest path
int bestDistance = -1000000; // distance of the longest path
int[] visited; // used to mark a node as visited if set as
// 1
public LongestPathinDAG()
{
Scanner sc = new Scanner(System.in);
System.out.println(\"Enter the number of vertices: \");
n = sc.nextInt();
System.out.println(\"Enter the number of edges: \");
int m = sc.nextInt();
v = new Node1[n];
e = new Edge[m];
System.out.println(n + \" nodes and \" + m + \" edges.\");
for (int i = 0; i < n; i++)
v[i] = new Node1(i);
int i = 0;
while (i < e.length)
{
Edge edge = new Edge(i);
int sVal = sc.nextInt();
edge.start = sVal;// sc.nextInt();
int eVal = sc.nextInt();
edge.end = eVal;// sc.nextInt();
edge.capacity = sc.nextInt();
System.out.println(\" edge: \" + edge.start + \" - \" + edge.end
+ \" : \" + edge.capacity);
edge.flow = 0;
e[i] = edge;
v[sVal].fors.add(i);
v[eVal].backs.add(i);
i++;
if (i == m)
break;
}
visited = new int[v.length];
path = new int[v.length];
bestPath = new int[v.length];
sc.close();
}
/*
* this function looks for a longest path starting from being to end,
* using the backtrack depth-first search.
*/
public boolean findLongestPath(int begin, int end, int minLen)
{
/*
* compute a longest path from begin to end
*/
target = end;
bestDistance = -100000000;
minLength = minLen;
dfsLongestPath(begin);
if (bestDistance == -100000000)
return false;
else
return true;
}
private void dfsLongestPath(int curr.
The document contains instructions for 15 computer graphics experiments to be completed in a Computer Graphics lab course. The experiments include programs to draw lines and shapes using algorithms like DDA, Bresenham, midpoint circle and ellipse algorithms. Programs for transformations like rotation, translation, scaling and shearing of shapes are also included. Boundary fill and flood fill algorithms are among the programs listed.
Pointers allow programs to store and manipulate memory addresses. A pointer variable contains the address of another variable. Pointers are useful for passing data between functions, returning multiple values from functions, and dynamically allocating memory at runtime. Pointers can also be used to access elements of arrays indirectly and implement multidimensional arrays more efficiently. Pointer notation provides an alternative way to access array elements through pointer arithmetic rather than subscripts.
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
Today, we almost exclusively think of code in software projects as a collection of text files. The tools that we use (version control systems, IDEs, code analyzers) also use text as the primary storage format for code. In fact, the belief that “code is text” is so deeply ingrained in our heads that we never question its validity or even become aware of the fact that there are other ways to look at code.
In my talk I will explain why treating code as text is a very bad idea which actively holds back our understanding and creates a range of problems in large software projects. I will then show how we can overcome (some of) these problems by treating and storing code as data, and more specifically as a graph. I will show specific examples of how we can use this approach to improve our understanding of large code bases, increase code quality and automate certain aspects of software development.
Finally, I will outline my personal vision of the future of programming, which is a future where we no longer primarily interact with code bases using simple text editors. I will also give some ideas on how we might get to that future.
Apache Flink Training: DataStream API Part 2 Advanced Flink Forward
Flink can handle many data types and provides a type system to identify types for serialization and comparisons. Composite types like Tuples and POJOs can be used and fields within them can define keys. Windows provide a way to perform aggregations over finite slices of infinite streams. Connected streams allow correlating and joining multiple streams. Stateful functions have access to local and partitioned state for stateful stream processing. Kafka integration allows consuming from and producing to Kafka topics.
This is Function Class public abstract class Function { .pdfamitbagga0808
This document describes a Java program that graphs functions. It includes abstract Function and GraphManager classes, and subclasses that implement specific functions. The GraphManager handles function selection and calculating graph extents. The GUI displays the functions, prompts the user to select one and input bounds, and calls GraphManager to draw the function on a Canvas between the bounds. Any errors from user input are caught and handled.
This document discusses binary search trees and provides source code to implement binary search tree traversal operations. It explains that a binary search tree is a binary tree where the left child of a node is less than the parent and the right child is greater. It provides code for preorder, inorder, and postorder traversals of the binary search tree and outputs the traversal order for a sample tree.
SaveI need help with this maze gui that I wrote in java, I am tryi.pdfarihantstoneart
Save
I need help with this maze gui that I wrote in java, I am trying to find the shortest path but I dont
know how to implement the FindshortestPath Method.
I was given this as a stragedy to solve the findshortestpathMethod():
Create two LinkedLists of MazeMap objects. One will be the list of map objects for cells at
distance x from the center. The other will be the list of map objects for cells at distance x + 1.
Initialize the list at distance x to contain a MazeMap object which refers to the center cell of the
maze. Since this map object refers to the center cell, it does not need to refer to any other
MazeMap object, so its MazeMap reference can be set to null. Set the center cell’s visited field
to true to indicate that this cell has already been added to the map.
Set up a loop to run until the maze entrance is mapped. This loop does the following:
Set up a loop to process each map object from the list at distance x. This loop does the following:
i.Get the cell from the map object
ii.If this cell is the entrance cell, set the entrance and break out of the loop!
iii.Check each direction from this cell and for an accessible neighbor cell
Get a reference to that neighbor cell
If the neighbor cell has not already been visited
Set the cell’s visited field to true so its only processed once
Create a MazeMap object that refers to this neighbor cell
Make this MazeMap object refer to the current map object being processed – ie the cell one step
closer to center
Add this MazeMap object to the list at distance x + 1
List at distance x has been processed. The list at distance x + 1 is now complete, so make the list
at distance x refer to list at distance x + 1. Then create a new empty list for the list at distance x +
1.
At this point, the entrance points at the map object which refers to cell 1,1. That map object also
refers to a map object which is one step closer to the center. Write a loop that traverses this trail
of references until it reaches the end (a null reference). For each map object:
Get the cell referred to.
Call the drawCircle method with a color, the cell’s row and column, and SMALL.
Call the delay method with a SHORT delay. This slows down the drawing process so you can
watch the path being displayed.
Advance to the next map object in the list.
here is the code so far*********
here is my code: ******mazeApp*******
package mazepackage;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TextInputDialog;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MazeApp extends Application
{
// default canvas size is DEFAULT_SIZE-by-DEFAULT_SIZE
private static final int DEFAULT_SIZE = 768;
private int width = DEFAULT_SIZE;
private int height = DEFAULT_SIZE;
// The graphics context is needed to enable drawing on the canvas
private Graphics.
Similar to AI Lab menu for ptu students and easy to use and best quality and help for 6th sem students (20)
Discover the Beauty and Functionality of The Expert Remodeling Serviceobriengroupinc04
Unlock your kitchen's true potential with expert remodeling services from O'Brien Group Inc. Transform your space into a functional, modern, and luxurious haven with their experienced professionals. From layout reconfiguration to high-end upgrades, they deliver stunning results tailored to your style and needs. Visit obriengroupinc.com to elevate your kitchen's beauty and functionality today.
SATTA MATKA DPBOSS KALYAN MATKA RESULTS KALYAN CHART KALYAN MATKA MATKA RESULT KALYAN MATKA TIPS SATTA MATKA MATKA COM MATKA PANA JODI TODAY BATTA SATKA MATKA PATTI JODI NUMBER MATKA RESULTS MATKA CHART MATKA JODI SATTA COM INDIA SATTA MATKA MATKA TIPS MATKA WAPKA ALL MATKA RESULT LIVE ONLINE MATKA RESULT KALYAN MATKA RESULT DPBOSS MATKA 143 MAIN MATKA KALYAN MATKA RESULTS KALYAN CHART
Prescriptive analytics BA4206 Anna University PPTFreelance
Business analysis - Prescriptive analytics Introduction to Prescriptive analytics
Prescriptive Modeling
Non Linear Optimization
Demonstrating Business Performance Improvement
63662490260Kalyan chart, satta matta matka 143, satta matka jodi fix , matka boss OTC 420, Indian Satta, India matka, matka ank, spbossmatka, online satta matka game play, live satta matka results, fix fix fix satta namber, free satta matka games, Kalyan matka jodi chart, Kalyan weekly final anl matka 420
SATTA MATKA DPBOSS KALYAN MATKA RESULTS KALYAN CHART KALYAN MATKA MATKA RESULT KALYAN MATKA TIPS SATTA MATKA MATKA COM MATKA PANA JODI TODAY BATTA SATKA MATKA PATTI JODI NUMBER MATKA RESULTS MATKA CHART MATKA JODI SATTA COM INDIA SATTA MATKA MATKA TIPS MATKA WAPKA ALL MATKA RESULT LIVE ONLINE MATKA RESULT KALYAN MATKA RESULT DPBOSS MATKA 143 MAIN MATKA KALYAN MATKA RESULTS KALYAN CHART
Adani Group's Active Interest In Increasing Its Presence in the Cement Manufa...Adani case
Time and again, the business group has taken up new business ventures, each of which has allowed it to expand its horizons further and reach new heights. Even amidst the Adani CBI Investigation, the firm has always focused on improving its cement business.
Satta matka fixx jodi panna all market dpboss matka guessing fixx panna jodi kalyan and all market game liss cover now 420 matka office mumbai maharashtra india fixx jodi panna
Call me 9040963354
WhatsApp 9040963354
SATTA MATKA DPBOSS KALYAN MATKA RESULTS KALYAN CHART KALYAN MATKA MATKA RESULT KALYAN MATKA TIPS SATTA MATKA MATKA COM MATKA PANA JODI TODAY BATTA SATKA MATKA PATTI JODI NUMBER MATKA RESULTS MATKA CHART MATKA JODI SATTA COM INDIA SATTA MATKA MATKA TIPS MATKA WAPKA ALL MATKA RESULT LIVE ONLINE MATKA RESULT KALYAN MATKA RESULT DPBOSS MATKA 143 MAIN MATKA KALYAN MATKA RESULTS KALYAN CHART
SATTA MATKA DPBOSS KALYAN MATKA RESULTS KALYAN CHART KALYAN MATKA MATKA RESULT KALYAN MATKA TIPS SATTA MATKA MATKA COM MATKA PANA JODI TODAY BATTA SATKA MATKA PATTI JODI NUMBER MATKA RESULTS MATKA CHART MATKA JODI SATTA COM INDIA SATTA MATKA MATKA TIPS MATKA WAPKA ALL MATKA RESULT LIVE ONLINE MATKA RESULT KALYAN MATKA RESULT DPBOSS MATKA 143 MAIN MATKA KALYAN MATKA RESULTS KALYAN CHART INDIA MATKA KALYAN SATTA MATKA 420 INDIAN MATKA SATTA KING MATKA FIX JODI FIX FIX FIX SATTA NAMBAR MATKA INDIA SATTA BATTA
AI Transformation Playbook: Thinking AI-First for Your BusinessArijit Dutta
I dive into how businesses can stay competitive by integrating AI into their core processes. From identifying the right approach to building collaborative teams and recognizing common pitfalls, this guide has got you covered. AI transformation is a journey, and this playbook is here to help you navigate it successfully.
Presentation by Herman Kienhuis (Curiosity VC) on Investing in AI for ABS Alu...Herman Kienhuis
Presentation by Herman Kienhuis (Curiosity VC) on developments in AI, the venture capital investment landscape and Curiosity VC's approach to investing, at the alumni event of Amsterdam Business School (University of Amsterdam) on June 13, 2024 in Amsterdam.
Kirill Klip GEM Royalty TNR Gold Lithium Presentation
AI Lab menu for ptu students and easy to use and best quality and help for 6th sem students
1. ST. SOLDIER INSTITUTE OF
ENGINEERING & TECHNOLOGY
SESSION – (2019-2023)
PRACTICAL FILE OF ARTIFICIAL
INTELLIGENCE LAB
(BTCS 605-18)
2. INDEX
SR. NO. AIM PAGE NO. SIGNATURE
1. Write a programme to conduct
uninformed and informed
search.
1 – 12
2. Write a programme to conduct
game search.
13 – 17
3. Write a programme to
construct a Bayesian network
from given data.
18 – 23
4. Write a programme to infer
from the Bayesian network.
24 – 28
5. Write a programme to run
value and policy iteration in a
grid world.
29 – 33
6. Write a programme to do
reinforcement learning in a
grid world
34 - 40
3. EXPERIMENT N0. 1
AIM : Write a program to conduct uniformed and informed search.
THEORY :
Uninformed Search Algorithm
Uninformed search is a class of general-purpose search algorithms which
operates in brute force-way. Uninformed search algorithms do not have
additional information about state or search space other than how to
traverse the tree, so it is also called blind search.
Following are the various types of uninformed search algorithms:
1.Breadth-first Search
2.Depth-first Search
1. Breadth-first Search:
Breadth-first search is the most common search strategy for traversing a
tree or graph. This algorithm searches breadthwise in a tree or graph, so
it is called breadth-first search. BFS algorithm starts searching from the
root node of the tree and expands all successor node at the current level
before moving to nodes of next level. The breadth-first search algorithm
is an example of a general-graph search algorithm. Breadth-first search
implemented using FIFO queue data structure.
Code for BFS :
#include<bits/stdc++.h>
using namespace std;
4. // This class represents a directed graph using
// adjacency list representation
class Graph
{
int V; // No. of vertices
// Pointer to an array containing adjacency
// lists
vector<list<int>> adj;
public:
Graph(int V); // Constructor
// function to add an edge to graph
void addEdge(int v, int w);
// prints BFS traversal from a given source s
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj.resize(V);
}
5. void Graph::addEdge(int v, int w)
{
adj*v+.push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
vector<bool> visited;
visited.resize(V,false);
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
6. queue.pop_front();
// Get all adjacent vertices of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (auto adjecent: adj[s])
{
if (!visited[adjecent])
{
visited[adjecent] = true;
queue.push_back(adjecent);
}
}
}
}
// Driver program to test methods of graph class
int main()
{
// Create a graph given in the above diagram
Graph g(4);
7. g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2) n";
g.BFS(2);
return 0;
}
2. Depth-first Search
Depth-first search isa recursive algorithm for traversing a tree or graph
data structure. It is called the depth-first search because it starts from the
root node and follows each path to its greatest depth node before
moving to the next path. DFS uses a stack data structure for its
implementation. The process of the DFS algorithm is similar to the BFS
algorithm
8. EXPERIMENT NO. 1
AIM: Write a program to conduct uniformed and informed search
Output:
Following is Breadth First Traversal (starting from vertex 2)
2 0 3 1
9. Code for DFS:
#include <bits/stdc++.h>
using namespace std;
// Graph class represents a directed graph
// using adjacency list representation
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;
// function to add an edge to graph
void addEdge(int v, int w);
// DFS traversal of the vertices
// reachable from v
void DFS(int v);
};
void Graph::addEdge(int v, int w)
{
adj*v+.push_back(w); // Add w to v’s list.
}
10. void Graph::DFS(int v)
{
// Mark the current node as visited and
// print it
visited[v] = true;
cout << v << " ";
// Recurse for all the vertices adjacent
// to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}
// Driver code
int main()
{
// Create a graph given in the above diagram
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
11. g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Depth First Traversal"
" (starting from vertex 2) n";
g.DFS(2);
return 0;
}
Informed Search:
Informed Search algorithms have information on the goal state which
helps in more efficient searching. This information is obtained by a
function that estimates how close a state is to the goal state.
In the informed search main algorithm which is given below:
1.A* Search Algorithm
A* search is the most commonly known form of best-first search. It uses
heuristic function h(n), and cost to reach the node n from the start state
g(n). It has combined features of UCS and greedy best-first search, by
which it solve the problem efficiently. A* search algorithm finds the
shortest path through the search space using the heuristic function. This
12. search algorithm expands less search tree and provides optimal result
faster. A* algorithm is similar to UCS except that it uses g(n)+h(n) instead
of g(n).
Code for A* algorithm
#include <iostream>
#include "source/AStar.hpp"
int main()
{
AStar::Generator generator;
// Set 2d map size.
generator.setWorldSize({25, 25});
// You can use a few heuristics : manhattan, euclidean or octagonal.
generator.setHeuristic(AStar::Heuristic::euclidean);
generator.setDiagonalMovement(true);
std::cout << "Generate path ... n";
// This method returns vector of coordinates from target to source.
auto path = generator.findPath({0, 0}, {20, 20});
for(auto& coordinate : path) {
std::cout << coordinate.x << " " << coordinate.y << "n";
}
}
15. EXPERIMENT N0. 2
AIM :Write a program to conduct game search.
THEORY :Game playing was one of the first tasks undertaken in Artificial
Intelligence. Game theory has its history from 1950, almost from the days
when computers became programmable. The very first game that is been
tackled in AI is chess. Initiators in the field of game theory in AI were
Konard Zuse (the inventor of the first programmable computer and the
first programming language), Claude Shannon (the inventor of
information theory), Norbert Wiener (the creator of modern control
theory), and Alan Turing. Since then, there has been a steady progress in
the standard of play, to the point that machines have defeated human
champions (although not every time) in chess and backgammon, and are
competitive in many other games.
Types of Game
1. Perfect Information Game: In which player knows all the possible
moves of himself and opponent and their results.
E.g. Chess.2
2. Imperfect Information Game: In which player does not know all the
possible moves of the opponent.
E.g. Bridge since all the cards are not visible to player
Mini-Max Algorithm in Artificial Intelligence:
Mini-max algorithm is a recursive or backtracking algorithm which is used
in decision-making and game theory. It provides an optimal move for the
16. player assuming that opponent is also playing optimally. Mini-Max
algorithm uses recursion to search through the game-tree. Min-Max
algorithm is mostly used for game playing in AI. Such as Chess, Checkers,
tic-tac-toe, go, and various tow-players game. This Algorithm computes
the minimax decision for the current state .In this algorithm two players
play the game, one is called MAX and other is called MIN. Both the
players fight it as the opponent player gets the minimum benefit while
they get the maximum benefit. Both Players of the game are opponent of
each other, where MAX will select the maximized value and MIN will
select the minimized value. The minimax algorithm performs a depth-first
search algorithm for the exploration of the complete game tree. The
minimax algorithm proceeds all the way down to the terminal node of
the tree, then backtrack the tree as the recursion.
Code for minmax algorithm :
// A simple C++ program to find
// maximum score that
// maximizing player can get.
#include<bits/stdc++.h>
using namespace std;
// Returns the optimal value a maximizer can obtain.
// depth is current depth in game tree.
// nodeIndex is index of current node in scores[].
// isMax is true if current move is
// of maximizer, else false
// scores[] stores leaves of Game tree.
// h is maximum height of Game tree
int minimax(int depth, int nodeIndex, bool isMax,
int scores[], int h)
{
// Terminating condition. i.e
17. // leaf node is reached
if (depth == h)
return scores[nodeIndex];
// If current move is maximizer,
// find the maximum attainable
// value
if (isMax)
return max(minimax(depth+1, nodeIndex*2, false, scores, h),
minimax(depth+1, nodeIndex*2 + 1, false, scores, h));
// Else (If current move is Minimizer), find the minimum
// attainable value
else
return min(minimax(depth+1, nodeIndex*2, true, scores, h),
minimax(depth+1, nodeIndex*2 + 1, true, scores, h));
}
// A utility function to find Log n in base 2
int log2(int n)
{
return (n==1)? 0 : 1 + log2(n/2);
}
// Driver code
int main()
18. {
// The number of elements in scores must be
// a power of 2.
int scores[] = {3, 5, 2, 9, 12, 5, 23, 23};
int n = sizeof(scores)/sizeof(scores[0]);
int h = log2(n);
int res = minimax(0, 0, true, scores, h);
cout << "The optimal value is : " << res << endl;
return 0;
}
19. EXPERIMENT N0. 2
AIM : Write a program to conduct game search
Output:
The optimal value is: 12
20. EXPERIMENT N0. 3
AIM :Write a program to construct a Bayesian network from given data
THEORY:A Bayesian network is a directed acyclic graph in which each
edge corresponds to a conditional dependency, and each node
corresponds to a unique random variable. Bayesian network consists of
two major parts: a directed acyclic graph and a set of conditional
probability distributions
1. The directed acyclic graph is a set of random variables represented
by nodes.
2. The conditional probability distribution of a node (random variable)
is defined for every possible outcome of the preceding causal
node(s).
For illustration, consider the following example. Suppose we attempt to
turn on our computer, but the computer does not start
(observation/evidence). We would like to know which of the possible
causes of computer failure is more likely. In this simplified illustration, we
assume only two possible causes of this misfortune: electricity failure and
computer malfunction.
The corresponding directed acyclic graph is depicted in below figure
causes
evidence
Electricity failure Computer
malfunction
Computer failure
21. The goal is to calculate the posterior conditional probability distribution
of each of the possible unobserved causes given the observed evidence,
i.e. P [Cause | Evidence].
Data Set:
Title: Heart Disease Databases
The Cleveland database contains 76 attributes, but all published
experiments refer to using a
subset of 14 of them. In particular, the Cleveland database is the only one
that has been used
by ML researchers to this date. The "Heartdisease" field refers to the
presence of heart disease in the patient. It is integer valued from 0 (no
presence) to 4.
Database: 0 1 2 3 4 Total
Cleveland: 164 55 36 35 13 303
Attribute Information:
1. age: age in years
2. sex: sex (1 = male; 0 = female)
3. cp: chest pain type
-anginal pain
22. 4. trestbps: resting blood pressure (in mm Hg on admission to the
hospital)
5. chol: serum cholestoral in mg/dl
6. fbs: (fasting blood sugar > 120 mg/dl) (1 = true; 0 = false)
7. restecg: resting electrocardiographic results
-T wave abnormality (T wave inversions and/or ST
elevation
or depression of > 0.05 mV)
hypertrophy by
Estes'
criteria
8. thalach: maximum heart rate achieved
9. exang: exercise induced angina (1 = yes; 0 = no)
10. oldpeak = ST depression induced by exercise relative to rest
11.slope: the slope of the peak exercise ST segment
ping
12. ca = number of major vessels (0-3) colored by flourosopy
13. thal: 3 = normal; 6 = fixed defect; 7 = reversable defect
23. 14.Heartdisease: It is integer valued from 0 (no presence) to 4. Diagnosis
of heart disease (angiographic disease status)
Some instance from the dataset:
age sex cp trestbps chol fbs restecg thalach exang oldpeak slope ca thal Heart
disease
63 1 1 145 1 1 2 150 0 2.3 3 0 6 0
67 1 4 160 4 0 2 108 1 1.5 2 3 3 2
67 1 4 120 4 0 2 129 1 2.6 2 2 7 1
41 0 2 130 2 0 2 172 0 1.4 1 O 3 0
62 0 4 140 4 0 2 160 0 3.6 3 2 3 3
60 1 4 130 206 0 2 132 1 2.4 2 2 7 4
Code :
import numpy as np
import csv
import pandas as pd
from pgmpy.models import BayesianModel
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination
#read Cleveland Heart Disease data
heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)
#display the data
print('Few examples from the dataset are given below')
print(heartDisease.head())
#Model Bayesian Network
25. EXPERIMENT N0. 3
AIM : Write a program to construct a Bayesian network from given data
Output:
Few examples from the dataset are given below
Age sex cp trestbps ... slope ca thal heartdisease
0 63 1 1 145 … 3 0 6 0
1 67 1 4 160 … 2 3 3 2
2 67 1 4 120 … 2 2 7 1
3 37 1 3 130 … 3 0 3 0
4 41 0 2 130 … 1 0 3 0
26. EXPERIMENT N0. 4
AIM:Write a program to infer from the Bayesian network.
THEORY :An acyclic directed graph is used to create a Bayesian network,
which is a probability model. It’s factored by utilizing a single conditional
probability distribution for each variable in the model, whose distribution
is based on the parents in the graph. The simple principle of probability
underpins Bayesian models. So, first, let’s define conditional probability
and joint probability distribution.
Conditional Probability
Conditional probability is a measure of the likelihood of an event
occurring provided that another event has already occurred (through
assumption, supposition, statement, or evidence). If A is the event of
interest and B is known or considered to have occurred, the conditional
probability of A given B is generally stated as P(A|B) or, less frequently,
PB(A) if A is the event of interest and B is known or thought to have
occurred. This can also be expressed as a percentage of the likelihood of
B crossing with A:
Joint Probability
The chance of two (or more) events together is known as the joint
probability. The sum of the probabilities of two or more random variables
is the joint probability distribution. For example, the joint probability of
events A and B is expressed formally as:
The letter P is the first letter of the alphabet (A and B).
27. The upside-down capital “U” operator or, in some situations, a comma “,”
represents the “and” or conjunction.
P(A ^ B)
P(A, B)
By multiplying the chance of event A by the likelihood of event B, the
combined probability for occurrences A and B is calculated.
Posterior Probability
In Bayesian statistics, the conditional probability of a random occurrence
or an ambiguous assertion is the conditional probability given the
relevant data or background. “After taking into account the relevant
evidence pertinent to the specific subject under consideration,”
“posterior” means in this case. The probability distribution of an
unknown quantity interpreted as a random variable based on data from
an experiment or survey is known as the posterior probability
distribution.
Inferencing with Bayesian Network
In this demonstration, we’ll use Bayesian Networks to solve the well-
known Monty Hall Problem. Let me explain the Monty Hall problem to
those of you who are unfamiliar with it:
This problem entails a competition in which a contestant must choose
one of three doors, one of which conceals a price. The show’s host
(Monty) unlocks an empty door and asks the contestant if he wants to
swap to the other door after the contestant has chosen one. The decision
is whether to keep the current door or replace it with a new one. It is
preferable to enter by the other door because the price is more likely to
28. be higher. To come out from this ambiguity let’s model this with a
Bayesian network.
CODE :
from pgmpy.models import BayesianNetwork
from pgmpy.factors.discrete import TabularCPD
import networkx as nx
import pylab as plt
# Defining Bayesian Structure
model = BayesianNetwork([('Guest', 'Host'), ('Price', 'Host')])
# Defining the CPDs:
cpd_guest = TabularCPD('Guest', 3, [[0.33], [0.33], [0.33]])
cpd_price = TabularCPD('Price', 3, [[0.33], [0.33], [0.33]])
cpd_host = TabularCPD('Host', 3, [[0, 0, 0, 0, 0.5, 1, 0, 1, 0.5],
[0.5, 0, 1, 0, 0, 0, 1, 0, 0.5],
[0.5, 1, 0, 1, 0.5, 0, 0, 0, 0]],
evidence=['Guest', 'Price'], evidence_card=[3, 3])
# Associating the CPDs with the network structure.
model.add_cpds(cpd_guest, cpd_price, cpd_host)
model.check_model()
# Infering the posterior probability
from pgmpy.inference import VariableElimination
31. EXPERIMENT NO. 5
AIM:Write a program to run value and policy iteration in a grid world
THEORY :Value Iteration
With the tools we have explored until now, a new question arises: why
do we need to consider an initial policy at all? The idea of the value
iteration algorithm is that we can compute the value function without a
policy. Instead of letting the policy, π, dictate which actions are selected,
we will select those actions that maximize the expected reward:
CODE FOR VALUE ITERATION :
def valueIteration(self, gridWorld, gamma = 1):
self.resetPolicy() # ensure empty policy before calling evaluatePolicy
V_old = None
V_new = np.repeat(0, gridWorld.size())
convergedCellIndices = np.zeros(0)
while len(convergedCellIndices) != len(V_new):
V_old = V_new
32. V_new = self.evaluatePolicySweep(gridWorld, V_old, gamma,
convergedCellIndices)
convergedCellIndices = self.findConvergedCells(V_old, V_new)
greedyPolicy = findGreedyPolicy(V_new, gridWorld, self.gameLogic)
self.setPolicy(greedyPolicy)
self.setWidth(gridWorld.getWidth())
self.setHeight(gridWorld.getHeight())
return(V_new)
POLICY ITERATION :
A simple strategy for this is a greedy algorithm that iterates over all the
cells in the grid and then chooses the action that maximizes the expected
reward according to the value function.
This approach implicitly determines the action-value function, which is
defined as
Qπ(s,a)=∑s′Pass′*Rass′+γVπ(s′)+Qπ(s,a)=∑s′Pss′a*Rss′a+γVπ(s′)+
The improvePolicy function determines the value function of a policy (if
it’s not available yet) and then calls findGreedyPolicy to identify the
optimal action for every state:
def improvePolicy(policy, gridWorld, gamma = 1):
policy = copy.deepcopy(policy) # dont modify old policy
if len(policy.values) == 0:
# policy needs to be evaluated first
policy.evaluatePolicy(gridWorld)
greedyPolicy = findGreedyPolicy(policy.getValues(), gridWorld,
policy.gameLogic, gamma)
policy.setPolicy(greedyPolicy)
return policy
def findGreedyPolicy(values, gridWorld, gameLogic, gamma = 1):
# create a greedy policy based on the values param
33. stateGen = StateGenerator()
greedyPolicy = [Action(Actions.NONE)] * len(values)
for (i, cell) in enumerate(gridWorld.getCells()):
gridWorld.setActor(cell)
if not cell.canBeEntered():
continue
maxPair = (Actions.NONE, -np.inf)
for actionType in Actions:
if actionType == Actions.NONE:
continue
proposedCell = gridWorld.proposeMove(actionType)
if proposedCell is None:
# action is nonsensical in this state
continue
Q = 0.0 # action-value function
proposedStates = stateGen.generateState(gridWorld, actionType, cell)
for proposedState in proposedStates:
actorPos = proposedState.getIndex()
transitionProb = gameLogic.getTransitionProbability(cell, proposedState,
actionType, gridWorld)
reward = gameLogic.R(cell, proposedState, actionType)
expectedValue = transitionProb * (reward + gamma * values[actorPos])
Q += expectedValue
if Q > maxPair[1]:
maxPair = (actionType, Q)
gridWorld.unsetActor(cell) # reset state
greedyPolicy[i] = Action(maxPair[0])
return greedyPolicy
34. EXPERIMENT NO. 5
AIM :Write a program to run value and policy iteration in a grid world.
OUTPUT :
36. EXPERIMENT NO : 6
AIM :Write a program to do reinforcement learning in a grid world .
THEORY : Reinforcement Learning (RL) involves decision making
under uncertainty which tries to maximize return over successive
states.There are four main elements of a Reinforcement Learning system:
a policy, a reward signal, a value function. The policy is a mapping from
the states to actions or a probability distribution of actions. Every action
the agent takes results in a numerical reward. The agent’s sole purpose is
to maximize the reward in the long run.
Reinforcement Learning involves decision making under uncertainty
which tries to maximize return over successive states.There are four main
elements of a Reinforcement Learning system: a policy, a reward signal, a
value function. The policy is a mapping from the states to actions or a
probability distribution of actions. Every action the agent takes results in
a numerical reward. The agent’s sole purpose is to maximize the reward
in the long run. The reward indicates the immediate return, a value
function specifies the return in the long run. Value of a state is the
expected reward that an agent can accrue The agent/robot takes an
action in At in state St and moves to state S’t anf gets a reward Rt+1 as
shown
37. An agent will seek to maximize the overall return as it transition across states
The expected return can be expressed as
where is the expected return in time t and the discounted expected
return in time t+1
A policy is a mapping from states to probabilities of selecting each possible action. If the
agent is following policy at time t, then is the probability that = a if = s.
The value function of a state s under a policy , denoted , is the expected return when
starting in s and following thereafter
This can be written as
=
Similarly the action value function gives the expected return when taking an action ‘a’ in
state ‘s’
These are Bellman’s equation for the state value function
The Bellman equations give the equation for each of the state
The Bellman optimality equations give the optimal policy of choosing specific actions in
specific states to achieve the maximum reward and reach the goal efficiently. They are given
as
The Bellman equations cannot be used directly in goal directed problems and dynamic
programming is used instead where the value functions are computed iteratively
In the problem below the Maze has 2 end states as shown in the corner. There are four
possible actions in each state up, down, right and left. If an action in a state takes it out of
the grid then the agent remains in the same state. All actions have a reward of -1 while the
end states have a reward of 0
38. This is shown as
where the reward for any transition is Rt=−1Rt=−1 except the transition to the end states at
the corner which have a reward of 0. The policy is a uniform policy with all actions being
equi-probable with a probability of 1/4 or 0.25
1. Gridworld-1
In [1]:
import numpy as np
import random
In [2]:
gamma = 1 # discounting rate
gridSize = 4
rewardValue = -1
terminationStates = [[0,0], [gridSize-1, gridSize-1]]
actions = [[-1, 0], [1, 0], [0, 1], [0, -1]]
numIterations = 1000
The action value provides the next state for a given action in a state and the accrued reward
In [3]:
def actionValue(initialPosition,action):
if initialPosition in terminationStates:
finalPosition = initialPosition
reward=0
else:
#Compute final position
finalPosition = np.array(initialPosition) + np.array(action)
reward= rewardValue
# If the action moves the finalPosition out of the grid, stay in same cell
if -1 in finalPosition or gridSize in finalPosition:
finalPosition = initialPosition
reward= rewardValue
#print(finalPosition)
return finalPosition, reward
1a. Bellman Update
39. In [4]:
# Initialize valueMap and valueMap1
valueMap = np.zeros((gridSize, gridSize))
valueMap1 = np.zeros((gridSize, gridSize))
states = [[i, j] for i in range(gridSize) for j in range(gridSize)]
In [5]:
def policy_evaluation(numIterations,gamma,theta,valueMap):
for i in range(numIterations):
delta=0
for state in states:
weightedRewards=0
for action in actions:
finalPosition,reward = actionValue(state,action)
weightedRewards += 1/4* (reward + gamma *
valueMap[finalPosition[0],finalPosition][1])
valueMap1[state[0],state[1]]=weightedRewards
delta =max(delta,abs(weightedRewards-valueMap[state[0],state[1]]))
valueMap = np.copy(valueMap1)
if(delta < 0.01):
print(valueMap)
break
In [6]:
valueMap = np.zeros((gridSize, gridSize))
valueMap1 = np.zeros((gridSize, gridSize))
states = [[i, j] for i in range(gridSize) for j in range(gridSize)]
policy_evaluation(1000,1,0.001,valueMap)
[[ 0. -13.89528403 -19.84482978 -21.82635535]
[-13.89528403 -17.86330422 -19.84586777 -19.84482978]
[-19.84482978 -19.84586777 -17.86330422 -13.89528403]
[-21.82635535 -19.84482978 -13.89528403 0. ]]
In [7]:
valueMap = np.zeros((gridSize, gridSize))
valueMap1 = np.zeros((gridSize, gridSize))
states = [[i, j] for i in range(gridSize) for j in range(gridSize)]
pi = np.ones((gridSize,gridSize))/4
pi1 = np.chararray((gridSize, gridSize))
pi1[:] = 'a'
In [8]:
# Compute the value state function for the Grid
def policy_evaluate(states,actions,gamma,valueMap):
#print("iterations=",i)
for state in states:
weightedRewards=0
for action in actions:
finalPosition,reward = actionValue(state,action)
weightedRewards += 1/4* (reward + gamma * valueMap[finalPosition[0],finalPosition][1])
40. # Set the computed weighted rewards to valueMap1
valueMap1[state[0],state[1]]=weightedRewards
# Copy to original valueMap
valueMap = np.copy(valueMap1)
return(valueMap)
In [9]:
def argmax(q_values):
idx=np.argmax(q_values)
return(np.random.choice(np.where(a==a[idx])[0].tolist()))
# Compute the best action in each state
def greedify_policy(state,pi,pi1,gamma,valueMap):
q_values=np.zeros(len(actions))
for idx,action in enumerate(actions):
finalPosition,reward = actionValue(state,action)
q_values[idx] += 1/4* (reward + gamma * valueMap[finalPosition[0],finalPosition][1])
# Find the index of the action for which the q_value is
idx=q_values.argmax()
pi[state[0],state[1]]=idx
if(idx == 0):
pi1[state[0],state[1]]='u'
elif(idx == 1):
pi1[state[0],state[1]]='d'
elif(idx == 2):
pi1[state[0],state[1]]='r'
elif(idx == 3):
pi1[state[0],state[1]]='l'
In [10]:
def improve_policy(pi, pi1,gamma,valueMap):
policy_stable = True
for state in states:
old = pi[state].copy()
# Greedify policy for state
greedify_policy(state,pi,pi1,gamma,valueMap)
if not np.array_equal(pi[state], old):
policy_stable = False
print(pi)
print(pi1)
return pi, pi1, policy_stable
In [11]:
def policy_iteration(gamma, theta):
valueMap = np.zeros((gridSize, gridSize))
pi = np.ones((gridSize,gridSize))/4