\"Create an implementation of a binary tree using the recursive approach introduced in the
chapter. In this approach, each node is a binary tree. Thus a binary tree contains a reference to
the element stored at its root as well as references to its left and right subtrees. You may also
want to include a reference to its parent.\" p.741
You need to use the locally implemented binary tree. This means you need to have a \"jsjf\"
subfolder with at least these files: BinaryTreeADT.java, LinkedBinaryTree.java,
BinaryTreeNode.java, and the exceptions sub-subfolder.
Test/demonstrate your binary tree by doing the following:
Request file name from user,
Read an infix expression from file,
Build binary expression tree,
Display binary expression tree,
Evaluate binary expression tree,
Display result.
##############################################
Note a typical input file can be found here
##############################################
# Version 0.2, fully parenthesized.
# This is a comment
((9 + 4) * 5) + (4 - (6 + 3))
# Note first expression should evaluate to 60
((42 + ( 10 - 2 )) + ( 5 * 3 )) / 6
# Note second expression should evaluate to 65 / 6 or 10 (integer division)
##############################################
My program is below but the out put is incorrect
##############################################
StringTree.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;
import jsjf.BinaryTreeNode;
import jsjf.LinkedBinaryTree;
public class StringTree extends LinkedBinaryTree {
public StringTree(String rootStr, StringTree leftSubtree, StringTree rightSubtree) {
root = new BinaryTreeNode(rootStr, leftSubtree, rightSubtree);
} // StringTree
public StringTree(File f) {
Stack leftStack = new Stack(), rightStack = new Stack();
// stacks of left and right subtrees of nodes
Scanner scan;
// scanner for reading from the file
String nodeType,
nodeStr;
// string contained in the current node
boolean hasLeftChild, hasRightChild;
// true if the current node has a left or right child
StringTree leftSubtree, rightSubtree,
// left and right subtrees of the current node
subtree;
// subtree having the current node as its root
// Create a scanner for reading from the file.
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
root = null;
System.out.println(\"\ \"+\"The program has terminated......\");
System.exit(0);
return;
}
// Read the file and build a tree from the bottom up.
while (scan.hasNext()) {
// Input information about a tree node.
nodeType = scan.next();
hasLeftChild = (scan.next().equalsIgnoreCase(\"y\"));
hasRightChild = (scan.next().equalsIgnoreCase(\"y\"));
nodeStr = scan.next();
// Determine the left and right subtrees of the subtree
// having the node as its root.
if (hasLeftChild)
leftSubtree = leftStack.pop();
else
leftSubtree = null;
if (hasRightChild)
rightSubtree = rightStack.pop();
else
rightSubtree = null;
.
Add these three functions to the class binaryTreeType (provided).W.pdfindiaartz
Add these three functions to the class binaryTreeType (provided).
Write the definition of the function, nodeCount, that returns the number of nodes in the binary
tree.
Write the definition of the function, leavesCount, that takes as a parameter a pointer to the root
node of a binary tree and returns the number of leaves in a binary tree.
Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Print
the original tree and the resulting tree using a pre-order traversal.
Write a program to test your new functions. Use the data provided to build your binary search
tree (-999 is the sentinel): (C++)
Data: 65 55 22 44 61 19 90 10 78 52 -999
Already completed code is below:
//Header File Binary Search Tree
#ifndef H_binarySearchTree
#define H_binarySearchTree
#include \"binaryTree.h\"
#include
using namespace std;
template
class bSearchTreeType: public binaryTreeType
{
public:
bool search(const elemType& searchItem) const;
//Function to determine if searchItem is in the binary
//search tree.
//Postcondition: Returns true if searchItem is found in
// the binary search tree; otherwise,
// returns false.
void insert(const elemType& insertItem);
//Function to insert insertItem in the binary search tree.
//Postcondition: If there is no node in the binary search
// tree that has the same info as
// insertItem, a node with the info
// insertItem is created and inserted in the
// binary search tree.
void deleteNode(const elemType& deleteItem);
//Function to delete deleteItem from the binary search tree
//Postcondition: If a node with the same info as deleteItem
// is found, it is deleted from the binary
// search tree.
// If the binary tree is empty or deleteItem
// is not in the binary tree, an appropriate
// message is printed.
private:
void deleteFromTree(nodeType* &p);
//Function to delete the node to which p points is
//deleted from the binary search tree.
//Postcondition: The node to which p points is deleted
// from the binary search tree.
};
template
bool bSearchTreeType::search
(const elemType& searchItem) const
{
nodeType *current;
bool found = false;
if (this->root == NULL)
cout << \"Cannot search an empty tree.\" << endl;
else
{
current = this->root;
while (current != NULL && !found)
{
if (current->info == searchItem)
found = true;
else if (current->info > searchItem)
current = current->lLink;
else
current = current->rLink;
}//end while
}//end else
return found;
}//end search
template
void bSearchTreeType::insert
(const elemType& insertItem)
{
nodeType *current; //pointer to traverse the tree
nodeType *trailCurrent; //pointer behind current
nodeType *newNode; //pointer to create the node
newNode = new nodeType;
newNode->info = insertItem;
newNode->lLink = NULL;
newNode->rLink = NULL;
if (this->root == NULL)
this->root = newNode;
else
{
current = this->root;
while (current != NULL)
{
trailCurrent = current;
if (current->info == insertItem)
{
cout << \"The item to be inserted is already \";
cout << \"in the t.
Write a program in Java to implement the ADT Binary Tree part of who.docxrochellwa9f
Write a program in Java to implement the ADT Binary Tree part of whose definition is given below. You are also to write a driver program that demonstrates the correctness of your implementation by way of taking a series of commands from a text file and carrying them out. In each binary tree that you will deal with, the values are distinct (i.e. there are no duplicates).
Note: Code for binary tree that I discussed in class is available on Isidore. Feel free to use it but you will assume responsibility for the correctness.
The ADT Binary Tree
The only (private) data member you can use is root, as given below. However, feel free to use as many private member functions as you need.
/* Class BinaryTree */
public class BinaryTree> {
/* Class BinaryNode */
static private class BinaryNode> {
T
BinaryNode
BinaryNode
element; // data part
left; // left child
right; // right child
// Add appropriate constructors for BinaryNode
} // end of BinaryNode
private BinaryNode root; // root of the tree
private final int LCHILD = 1; // constant for left child
private final int RCHILD = 2; // constant for right child
// constructor for BinaryTree
public BinaryTree() {
root = null; // construct an empty tree
}
// Below are the methods that you must implement
//
// Create a tree with the given item as the root with its
// subtrees being empty.
// Post: Previous value of the tree is lost.
//
public void insertRoot (T item)
// If node containing parent exists, and if the specified // child is absent, create the specified child of parent // with item as data element and return true; otherwise
// return false.
//
// Pre: data items in the tree are distinct, i.e., no
duplicates.
// item, if it can be successfully inserted, is
different from
// each value in the tree.
// Post: if insertion were successful, item is the specified
child of
// parent.
// Parameters:
// item: data item to be inserted
// parent: data item of the potential parent // child == 1 => item is to be inserted as left
child of parent
// child == 2 => item is to be inserted as right
child of parent
// Return Value:
// true, if insertion succeeded, and false
otherwise.
public boolean insertItem (T item, T parent, int child)
// Print the tree contents in inorder to the stream
// associated with the printwriter output
public void printTree(PrintWriter output)
// Returns true if val1 exists, val2 exists, and they are
// siblings; otherwise, returns false
public boolean siblings (T val1, T val2)
// print to the given printwriter the frontier of the tree, // i.e., all the leaves in a "right to left reading of the // leaves” order; consecutive items are separated by a space public void printFrontier (PrintWriter output)
// delete subtree rooted at item, if item is present;
// otherwise, tree remains unchanged
public void deleteSubtree (T item)
// Post: if item is present, returns refer.
Please i need help on following program using C++ Language.Add the.pdfezzi552
Instructions write a c program to solve the following problem. Upload your source code file to
Canvas. The file name must be of the form hwloop your name.c Substitute your first and last
name for \"your name\" in the file name. Example: Student\'s name is Sparky Watts. The file
name is hwloop sparky watts.c Problem Statement create a program that calculates twelve
month\'s interest and principle loan balance. Your program will ask the user for the starting
principle balance, annual interest rate, and monthly payment amount. Your program will verify
the input is reasonable, as described in the Error checking section below. After obtaining
reasonable the program will process 12 months of payments. The will show the accrued interest
and updated loan balance after each month\'s payment. The total interest paid and total payment
amounts for the 12 month period will also be calculated and displayed. Your program output
should resemble the output below. AUsers williidialDesktoplhw04MbinlDebuglhw04.exe Enter
loan anount: 32000.00 Enter annual interest rate 7.99 Enter monthly payment 752.84
Solution
#include
#include
int main()
{
double loan_amount = 0;
printf(\"Enter loan amount :\");
if (scanf(\"%lf\", &loan_amount) != 1)
{
printf(\"Please enter loan amount correctly\ \");
return -1;
}
if (loan_amount < 500)
{
printf(\"Loan amount should be greater than 500\ \");
return 1;
}
if (loan_amount > 100000)
{
printf(\"Loan amount should be less than 100000\ \");
return -1;
}
printf(\"Enter annual interest rate: \");
double interest_rate;
if (scanf(\"%lf\", &interest_rate) != 1)
{
printf(\"Please enter interest rate correctly\ \");
return -1;
}
if (interest_rate < 0 || interest_rate > 8.99)
{
printf(\"Interest rate should be in range of 0 to 8.99\ \");
return -1;
}
double monthly_payments;
printf(\"Enter monthly payment: \");
if (scanf(\"%lf\", &monthly_payments) != 1)
{
printf(\"Please monthly payment correctly\ \");
return -1;
}
double first_month_interest = (loan_amount * interest_rate)/(12*100);
if (monthly_payments < first_month_interest)
{
printf(\"Monthly payment should be greater than %f\ \", first_month_interest);
return -1;
}
double total_interest = 0;
double total_paid = 0;
printf(\"\ \");
printf(\"Begin \\t\\t\\t\\tMonthly\\tEnd\ \");
printf(\"Loan\\t\\tAccured\\t\\tPayment\\tLoan\ \");
printf(\"Balance\\t\\tInterest\\tAmount\\tBalance\ \");
printf(\"\ \");
int i;
for(i = 0; i <= 12; i++)
{
printf(\"%0.2f\\t\", loan_amount);
double interest = (loan_amount*interest_rate)/(1200);
printf(\"%0.2f\\t\\t\", interest);
printf(\"%0.2f\\t\", monthly_payments);
loan_amount = loan_amount + interest;
if (loan_amount < monthly_payments)
{
total_paid -= loan_amount;
loan_amount = 0;
printf(\"%0.2f\ \", loan_amount);
break;
}
else
{
loan_amount -= monthly_payments;
total_paid += monthly_payments;
}
printf(\"%0.2f\ \", loan_amount);
total_interest += interest;
}
printf(\"\ \");
printf(\"Annual total\\t%.2f\\t\\t%.2f\ \", total_interest, total_paid);
return 0;
}.
Once you have all the structures working as intended- it is time to co.docxfarrahkur54
Once you have all the structures working as intended, it is time to compare the
performances of the 2. Use runBenchmark() to start.
a. First, generate an increasing number (N) of random integers (1000, 5000, 10000,
50000, 75000, 100000, 500000 or as far as your computing power will let you)
i. Time and print how long it takes to insert the random integers into an initially
empty BST. Do not print the tree.
You can get a random list using the java class Random, located in
java.util.Random. To test the speed of the insertion algorithm, you should use
the System.currentTimeMillis() method, which returns a long that contains the
current time (in milliseconds). Call System.currentTimeMillis() before and after
the algorithm runs and subtract the two times. (Instant.now() is an alternative
way of recording the time.)
ii. Time and print how long it takes to insert the same random integers into an
initially empty AVL tree. Do not print the tree.
iii. If T(N) is the time function, how does the growth of TBST(N) compare with the
growth of TAVL(N)?
Plot a simple graph to of time against N for the two types of BSTs to visualize
your results.
b. Second, generate a list of k random integers. k is also some large value.
i. Time how long it takes to search your various N-node BSTs for all k random
integers. It does not matter whether the search succeeds.
ii. Time how long it takes to search your N-node AVL trees for the same k random
integers.
iii. Compare the growth rates of these two search time-functions with a graph the
same way you did in part a.
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {
protected BinaryNode<AnyType> root;
public BinarySearchTree() {
root = null;
}
/**
* Insert into the tree; duplicates are ignored.
*
* @param x the item to insert.
* @param root
* @return
*/
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) {
// If the root is null, we've reached an empty leaf node, so we create a new node
// with the value x and return it
if (root == null) {
return new BinaryNode<>(x, null, null);
}
// Compare the value of x to the value stored in the root node
int compareResult = x.compareTo(root.element);
// If x is less than the value stored in the root node, we insert it into the left subtree
if (compareResult < 0) {
root.left = insert(x, root.left);
}
// If x is greater than the value stored in the root node, we insert it into the right subtree
else if (compareResult > 0) {
root.right = insert(x, root.right);
}
// If x is equal to the value stored in the root node, we ignore it since the tree does not allow duplicates
return root;
}
/**
* Counts the number of leaf nodes in this tree.
*
* @param t The root of the tree.
* @return
*/
private int countLeafNodes(BinaryNode<AnyType> root) {
// If the root is null, it means the tree is empty, so we return 0
if (root == null) {
return 0;
}
// If the root has no children, it means it is a leaf node, so we return 1
if (root.left == .
Please write in C++ and should be able to compile and debug.Thank yo.pdfajaycosmeticslg
Please write in C++ and should be able to compile and debug.Thank you
Create a class called BinaryTreeDeque. This binary tree implements all of the functionality of
the BinaryTree class, but instead of storing its values in a tree structure, the element values are
stored in a deque, using pointers to maintain the relationship between the binary tree and its node
values. Additionally: deque * getValues() - returns a copy of the deque the current array of
values (which should be in insertion order).
Solution
Following are steps to insert a new node in Complete Binary Tree.
1. If the tree is empty, initialize the root with new node.
2. Else, get the front node of the queue.
…….If the left child of this front node doesn’t exist, set the left child as the new node.
…….else if the right child of this front node doesn’t exist, set the right child as the new node.
3. If the front node has both the left child and right child, Dequeue() it.
4. Enqueue() the new node.
Code :-
-------------------------
binarytreedequeue.h
#ifndef BINARYTREEDEQUE_H
#define BINARYTREEDEQUE_H
// Program for linked implementation of complete binary tree
#include
#include
// For Queue Size
#define SIZE 50
// A tree node
struct node
{
int data;
struct node *right,*left;
};
// A queue node
struct Queue
{
int front, rear;
int size;
struct node* *array;
};
class BinaryTreeDeque
{
public:
BinaryTreeDeque();
struct node* newNode(int data);
struct Queue* createQueue(int size);
int isEmpty(struct Queue* queue);
int isFull(struct Queue* queue);
int hasOnlyOneItem(struct Queue* queue);
void Enqueue(struct node *root, struct Queue* queue);
struct node* Dequeue(struct Queue* queue);
struct node* getFront(struct Queue* queue);
int hasBothChild(struct node* temp);
void insert(struct node **root, int data, struct Queue* queue);
void display(struct Queue* queue);
node * getValues(struct Queue* queue);
};
#endif // BINARYTREEDEQUE_H
binarydequeue.cpp
---------------------------------------
#include \"binarytreedeque.h\"
BinaryTreeDeque::BinaryTreeDeque()
{
}
// A utility function to create a new tree node
struct node* BinaryTreeDeque::newNode(int data)
{
struct node* temp = (struct node*) malloc(sizeof( struct node ));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to create a new Queue
struct Queue* BinaryTreeDeque::createQueue(int size)
{
struct Queue* queue = (struct Queue*) malloc(sizeof( struct Queue ));
queue->front = queue->rear = -1;
queue->size = size;
queue->array = (struct node**) malloc(queue->size * sizeof( struct node* ));
int i;
for (i = 0; i < size; ++i)
queue->array[i] = NULL;
return queue;
}
// Standard Queue Functions
int BinaryTreeDeque::isEmpty(struct Queue* queue)
{
return queue->front == -1;
}
int BinaryTreeDeque::isFull(struct Queue* queue)
{ return queue->rear == queue->size - 1; }
int BinaryTreeDeque::hasOnlyOneItem(struct Queue* queue)
{ return queue->front == queue->rear; }
void BinaryTreeDeque::Enqueue(struct node *root, s.
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.
Add these three functions to the class binaryTreeType (provided).W.pdfindiaartz
Add these three functions to the class binaryTreeType (provided).
Write the definition of the function, nodeCount, that returns the number of nodes in the binary
tree.
Write the definition of the function, leavesCount, that takes as a parameter a pointer to the root
node of a binary tree and returns the number of leaves in a binary tree.
Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Print
the original tree and the resulting tree using a pre-order traversal.
Write a program to test your new functions. Use the data provided to build your binary search
tree (-999 is the sentinel): (C++)
Data: 65 55 22 44 61 19 90 10 78 52 -999
Already completed code is below:
//Header File Binary Search Tree
#ifndef H_binarySearchTree
#define H_binarySearchTree
#include \"binaryTree.h\"
#include
using namespace std;
template
class bSearchTreeType: public binaryTreeType
{
public:
bool search(const elemType& searchItem) const;
//Function to determine if searchItem is in the binary
//search tree.
//Postcondition: Returns true if searchItem is found in
// the binary search tree; otherwise,
// returns false.
void insert(const elemType& insertItem);
//Function to insert insertItem in the binary search tree.
//Postcondition: If there is no node in the binary search
// tree that has the same info as
// insertItem, a node with the info
// insertItem is created and inserted in the
// binary search tree.
void deleteNode(const elemType& deleteItem);
//Function to delete deleteItem from the binary search tree
//Postcondition: If a node with the same info as deleteItem
// is found, it is deleted from the binary
// search tree.
// If the binary tree is empty or deleteItem
// is not in the binary tree, an appropriate
// message is printed.
private:
void deleteFromTree(nodeType* &p);
//Function to delete the node to which p points is
//deleted from the binary search tree.
//Postcondition: The node to which p points is deleted
// from the binary search tree.
};
template
bool bSearchTreeType::search
(const elemType& searchItem) const
{
nodeType *current;
bool found = false;
if (this->root == NULL)
cout << \"Cannot search an empty tree.\" << endl;
else
{
current = this->root;
while (current != NULL && !found)
{
if (current->info == searchItem)
found = true;
else if (current->info > searchItem)
current = current->lLink;
else
current = current->rLink;
}//end while
}//end else
return found;
}//end search
template
void bSearchTreeType::insert
(const elemType& insertItem)
{
nodeType *current; //pointer to traverse the tree
nodeType *trailCurrent; //pointer behind current
nodeType *newNode; //pointer to create the node
newNode = new nodeType;
newNode->info = insertItem;
newNode->lLink = NULL;
newNode->rLink = NULL;
if (this->root == NULL)
this->root = newNode;
else
{
current = this->root;
while (current != NULL)
{
trailCurrent = current;
if (current->info == insertItem)
{
cout << \"The item to be inserted is already \";
cout << \"in the t.
Write a program in Java to implement the ADT Binary Tree part of who.docxrochellwa9f
Write a program in Java to implement the ADT Binary Tree part of whose definition is given below. You are also to write a driver program that demonstrates the correctness of your implementation by way of taking a series of commands from a text file and carrying them out. In each binary tree that you will deal with, the values are distinct (i.e. there are no duplicates).
Note: Code for binary tree that I discussed in class is available on Isidore. Feel free to use it but you will assume responsibility for the correctness.
The ADT Binary Tree
The only (private) data member you can use is root, as given below. However, feel free to use as many private member functions as you need.
/* Class BinaryTree */
public class BinaryTree> {
/* Class BinaryNode */
static private class BinaryNode> {
T
BinaryNode
BinaryNode
element; // data part
left; // left child
right; // right child
// Add appropriate constructors for BinaryNode
} // end of BinaryNode
private BinaryNode root; // root of the tree
private final int LCHILD = 1; // constant for left child
private final int RCHILD = 2; // constant for right child
// constructor for BinaryTree
public BinaryTree() {
root = null; // construct an empty tree
}
// Below are the methods that you must implement
//
// Create a tree with the given item as the root with its
// subtrees being empty.
// Post: Previous value of the tree is lost.
//
public void insertRoot (T item)
// If node containing parent exists, and if the specified // child is absent, create the specified child of parent // with item as data element and return true; otherwise
// return false.
//
// Pre: data items in the tree are distinct, i.e., no
duplicates.
// item, if it can be successfully inserted, is
different from
// each value in the tree.
// Post: if insertion were successful, item is the specified
child of
// parent.
// Parameters:
// item: data item to be inserted
// parent: data item of the potential parent // child == 1 => item is to be inserted as left
child of parent
// child == 2 => item is to be inserted as right
child of parent
// Return Value:
// true, if insertion succeeded, and false
otherwise.
public boolean insertItem (T item, T parent, int child)
// Print the tree contents in inorder to the stream
// associated with the printwriter output
public void printTree(PrintWriter output)
// Returns true if val1 exists, val2 exists, and they are
// siblings; otherwise, returns false
public boolean siblings (T val1, T val2)
// print to the given printwriter the frontier of the tree, // i.e., all the leaves in a "right to left reading of the // leaves” order; consecutive items are separated by a space public void printFrontier (PrintWriter output)
// delete subtree rooted at item, if item is present;
// otherwise, tree remains unchanged
public void deleteSubtree (T item)
// Post: if item is present, returns refer.
Please i need help on following program using C++ Language.Add the.pdfezzi552
Instructions write a c program to solve the following problem. Upload your source code file to
Canvas. The file name must be of the form hwloop your name.c Substitute your first and last
name for \"your name\" in the file name. Example: Student\'s name is Sparky Watts. The file
name is hwloop sparky watts.c Problem Statement create a program that calculates twelve
month\'s interest and principle loan balance. Your program will ask the user for the starting
principle balance, annual interest rate, and monthly payment amount. Your program will verify
the input is reasonable, as described in the Error checking section below. After obtaining
reasonable the program will process 12 months of payments. The will show the accrued interest
and updated loan balance after each month\'s payment. The total interest paid and total payment
amounts for the 12 month period will also be calculated and displayed. Your program output
should resemble the output below. AUsers williidialDesktoplhw04MbinlDebuglhw04.exe Enter
loan anount: 32000.00 Enter annual interest rate 7.99 Enter monthly payment 752.84
Solution
#include
#include
int main()
{
double loan_amount = 0;
printf(\"Enter loan amount :\");
if (scanf(\"%lf\", &loan_amount) != 1)
{
printf(\"Please enter loan amount correctly\ \");
return -1;
}
if (loan_amount < 500)
{
printf(\"Loan amount should be greater than 500\ \");
return 1;
}
if (loan_amount > 100000)
{
printf(\"Loan amount should be less than 100000\ \");
return -1;
}
printf(\"Enter annual interest rate: \");
double interest_rate;
if (scanf(\"%lf\", &interest_rate) != 1)
{
printf(\"Please enter interest rate correctly\ \");
return -1;
}
if (interest_rate < 0 || interest_rate > 8.99)
{
printf(\"Interest rate should be in range of 0 to 8.99\ \");
return -1;
}
double monthly_payments;
printf(\"Enter monthly payment: \");
if (scanf(\"%lf\", &monthly_payments) != 1)
{
printf(\"Please monthly payment correctly\ \");
return -1;
}
double first_month_interest = (loan_amount * interest_rate)/(12*100);
if (monthly_payments < first_month_interest)
{
printf(\"Monthly payment should be greater than %f\ \", first_month_interest);
return -1;
}
double total_interest = 0;
double total_paid = 0;
printf(\"\ \");
printf(\"Begin \\t\\t\\t\\tMonthly\\tEnd\ \");
printf(\"Loan\\t\\tAccured\\t\\tPayment\\tLoan\ \");
printf(\"Balance\\t\\tInterest\\tAmount\\tBalance\ \");
printf(\"\ \");
int i;
for(i = 0; i <= 12; i++)
{
printf(\"%0.2f\\t\", loan_amount);
double interest = (loan_amount*interest_rate)/(1200);
printf(\"%0.2f\\t\\t\", interest);
printf(\"%0.2f\\t\", monthly_payments);
loan_amount = loan_amount + interest;
if (loan_amount < monthly_payments)
{
total_paid -= loan_amount;
loan_amount = 0;
printf(\"%0.2f\ \", loan_amount);
break;
}
else
{
loan_amount -= monthly_payments;
total_paid += monthly_payments;
}
printf(\"%0.2f\ \", loan_amount);
total_interest += interest;
}
printf(\"\ \");
printf(\"Annual total\\t%.2f\\t\\t%.2f\ \", total_interest, total_paid);
return 0;
}.
Once you have all the structures working as intended- it is time to co.docxfarrahkur54
Once you have all the structures working as intended, it is time to compare the
performances of the 2. Use runBenchmark() to start.
a. First, generate an increasing number (N) of random integers (1000, 5000, 10000,
50000, 75000, 100000, 500000 or as far as your computing power will let you)
i. Time and print how long it takes to insert the random integers into an initially
empty BST. Do not print the tree.
You can get a random list using the java class Random, located in
java.util.Random. To test the speed of the insertion algorithm, you should use
the System.currentTimeMillis() method, which returns a long that contains the
current time (in milliseconds). Call System.currentTimeMillis() before and after
the algorithm runs and subtract the two times. (Instant.now() is an alternative
way of recording the time.)
ii. Time and print how long it takes to insert the same random integers into an
initially empty AVL tree. Do not print the tree.
iii. If T(N) is the time function, how does the growth of TBST(N) compare with the
growth of TAVL(N)?
Plot a simple graph to of time against N for the two types of BSTs to visualize
your results.
b. Second, generate a list of k random integers. k is also some large value.
i. Time how long it takes to search your various N-node BSTs for all k random
integers. It does not matter whether the search succeeds.
ii. Time how long it takes to search your N-node AVL trees for the same k random
integers.
iii. Compare the growth rates of these two search time-functions with a graph the
same way you did in part a.
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {
protected BinaryNode<AnyType> root;
public BinarySearchTree() {
root = null;
}
/**
* Insert into the tree; duplicates are ignored.
*
* @param x the item to insert.
* @param root
* @return
*/
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) {
// If the root is null, we've reached an empty leaf node, so we create a new node
// with the value x and return it
if (root == null) {
return new BinaryNode<>(x, null, null);
}
// Compare the value of x to the value stored in the root node
int compareResult = x.compareTo(root.element);
// If x is less than the value stored in the root node, we insert it into the left subtree
if (compareResult < 0) {
root.left = insert(x, root.left);
}
// If x is greater than the value stored in the root node, we insert it into the right subtree
else if (compareResult > 0) {
root.right = insert(x, root.right);
}
// If x is equal to the value stored in the root node, we ignore it since the tree does not allow duplicates
return root;
}
/**
* Counts the number of leaf nodes in this tree.
*
* @param t The root of the tree.
* @return
*/
private int countLeafNodes(BinaryNode<AnyType> root) {
// If the root is null, it means the tree is empty, so we return 0
if (root == null) {
return 0;
}
// If the root has no children, it means it is a leaf node, so we return 1
if (root.left == .
Please write in C++ and should be able to compile and debug.Thank yo.pdfajaycosmeticslg
Please write in C++ and should be able to compile and debug.Thank you
Create a class called BinaryTreeDeque. This binary tree implements all of the functionality of
the BinaryTree class, but instead of storing its values in a tree structure, the element values are
stored in a deque, using pointers to maintain the relationship between the binary tree and its node
values. Additionally: deque * getValues() - returns a copy of the deque the current array of
values (which should be in insertion order).
Solution
Following are steps to insert a new node in Complete Binary Tree.
1. If the tree is empty, initialize the root with new node.
2. Else, get the front node of the queue.
…….If the left child of this front node doesn’t exist, set the left child as the new node.
…….else if the right child of this front node doesn’t exist, set the right child as the new node.
3. If the front node has both the left child and right child, Dequeue() it.
4. Enqueue() the new node.
Code :-
-------------------------
binarytreedequeue.h
#ifndef BINARYTREEDEQUE_H
#define BINARYTREEDEQUE_H
// Program for linked implementation of complete binary tree
#include
#include
// For Queue Size
#define SIZE 50
// A tree node
struct node
{
int data;
struct node *right,*left;
};
// A queue node
struct Queue
{
int front, rear;
int size;
struct node* *array;
};
class BinaryTreeDeque
{
public:
BinaryTreeDeque();
struct node* newNode(int data);
struct Queue* createQueue(int size);
int isEmpty(struct Queue* queue);
int isFull(struct Queue* queue);
int hasOnlyOneItem(struct Queue* queue);
void Enqueue(struct node *root, struct Queue* queue);
struct node* Dequeue(struct Queue* queue);
struct node* getFront(struct Queue* queue);
int hasBothChild(struct node* temp);
void insert(struct node **root, int data, struct Queue* queue);
void display(struct Queue* queue);
node * getValues(struct Queue* queue);
};
#endif // BINARYTREEDEQUE_H
binarydequeue.cpp
---------------------------------------
#include \"binarytreedeque.h\"
BinaryTreeDeque::BinaryTreeDeque()
{
}
// A utility function to create a new tree node
struct node* BinaryTreeDeque::newNode(int data)
{
struct node* temp = (struct node*) malloc(sizeof( struct node ));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to create a new Queue
struct Queue* BinaryTreeDeque::createQueue(int size)
{
struct Queue* queue = (struct Queue*) malloc(sizeof( struct Queue ));
queue->front = queue->rear = -1;
queue->size = size;
queue->array = (struct node**) malloc(queue->size * sizeof( struct node* ));
int i;
for (i = 0; i < size; ++i)
queue->array[i] = NULL;
return queue;
}
// Standard Queue Functions
int BinaryTreeDeque::isEmpty(struct Queue* queue)
{
return queue->front == -1;
}
int BinaryTreeDeque::isFull(struct Queue* queue)
{ return queue->rear == queue->size - 1; }
int BinaryTreeDeque::hasOnlyOneItem(struct Queue* queue)
{ return queue->front == queue->rear; }
void BinaryTreeDeque::Enqueue(struct node *root, s.
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.
javaFix in the program belowhandle incomplete data for text fil.pdfbirajdar2
java
Fix in the program below:
handle incomplete data for text file and allow to search multiple items at once
and let it sort duplicate values
and most importantly let it use get and set methods on the Nodes
New Internal Requirements :
For this assignment, you should replace your Database class with another implementation which
uses instances of the Java Collections java.util.LinkedList class to replace your hand-crafted
LinkedList classes. Note the following:
• LinkedList is a generic type; you must instantiate it with concrete class types. Thus, your
Database object will contain several LinkedList objects; you will need to organize these lists into
another instance of LinkedList. (Consider creating a Year object to help with this.)
• You are still required to maintain your lists in sorted order. The pre-built LinkedList methods
do not directly support relative insertion into a linked list; you will need to find ways to
accomplish this with the tools available to you. (There are at least a couple of ways to do this.)
New function to add:
• A new command should be implemented which allows the user to edit a storm from the main
menu. If selected, the program should prompt the user for the year and storm name to be edited.
If a matching storm is found, the corresponding record should be displayed and the user
prompted for new information to be placed in the record. Users may not change the year or storm
name, but may change any of the other information. If no matching storm is found, no action
should be taken. The user should be informed of the outcome in any case.
this is what the txt file the program is reading from looks like:
2000/Alex/0110/0120/0
2001/Bill/0210/0220/0
2002/Chris/0310/0320/0
2003/Devon/0140/0420/0
2004/Eli/0510/0520/1
2005/Fred/0610/0620/2
2006/Gilbert/0710/0820/3
2007/Herbert/0910/0920/4
2008/Kim/1010/1020/5
#######################################Java
Program#######################################################################
###
/*****************************************************************************
***************/
/*This program takes a a file and gives infomation to the user using a LinkedList */
/*****************************************************************************
***************/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
//setting variables to string or int
public class Storm {
private int stormYear;
private int stormMag;
private String stormStart;
private String stormEnd;
private String stormName;
/**
* Constructor
* Storing all variables from text file
* @param stormName
* @param stormYear
* @param stormStart
* @param stormEnd
* @param stormMag
*/
public Storm(String stormName, int stormYear, String stormStart, String stormEnd, int
stormMag) {
this.stormName = stormName;
this.stormYear = stormYear;
this.stormStart = stormStart;
this.stormEnd = stormEnd;
this.stormMag = stormMag;
}
/*******************************.
C programming. Answer question only in C code Ninth Deletion with B.pdfinfo309708
C programming. Answer question only in C code Ninth: Deletion with Binary Search Tree (20
points) In the ninth part, you will extend the binary search tree in the eighth part to support the
deletion of a node. The deletion of a node is slightly trickier compared to the search and insert in
the eighth The deletion is straightforward if the node to be deleted has only one child. You make
the parent of the node to be deleted point to that child. In this scenario, special attention must be
paid only when the node to be deleted is the root Deleting a node with two children requires
some more work. In this case, you must find the minimum element in the right subtree of the
node to be deleted. Then you insert that node in the place where the node to be deleted was. This
process needs to be repeated to delete the minimum node that was just moved In either case, if
the node to be deleted is the root, you must update the pointer to the root to point to the new root
node Input format: This program takes a file name as argument from the command line. The file
is either blank or contains successive lines of input. Each line contains a character, \'i or \'d\'
followed by a tab and an integer. For each line that starts with \'i\', your program should insert
that number in the binary search tree if it is not already there. If the line starts with a \'s, your
program should search for that value. If the line starts with a \'d\', your program should delete
that value from the tree output format: For each line in the input file, your program should print
the status/result of the operation. For insert and search, the output is the same as in the Eighth
Part: For an insert operation, the program should print either \"inserted\" with a single space
followed by a number the height of the inserted mode in the tree, or \"duplicate\" if the value is
already present in the tree. The height of the root node is 1. For a search, the program should
either print \"present\" followed by the height of the node, or absent\" based on the outcome of
the search. For a delete, the program should print \"success or \"fail\" based on the whether the
value was present or not. Again, as in the Eight Part, your program should print \"error\" (and
nothing else) if the file does not exist or for input lines with improper structure Example
Execution: Lets assume we have a file filel.txt with the following contents: i 5 i 3 i 4 i 1 i 6 i 2 s
1 d 3 s 2 Executing the program in the following fashion should produce the output shown
below:
Solution
// C program to demonstrate delete operation in binary search tree
#include
#include
struct node
{
int key;
struct node *left, *right;
};
// A utility function to create a new BST node
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
.
Need Help with this Java Assignment. Program should be done in JAVA .pdfarchiesgallery
Need Help with this Java Assignment. Program should be done in JAVA please
Complete required scripts based on eclipse and troubleshoot the scripts until the tasks are done.
1. Implement a binary search tree (write the code for it), for a height of 2 or higher. Please show
the output if you can Thank you in advance!
Solution
I have compiled this code and checked for errors, worked fine.
Also after the code I have pasted the Output transcript to show what User Inputs I gave and what
all outputs I got.
// Java Program to Implement Binary Tree
import java.util.Scanner;
/* Define Class BinaryTreeNode */
class BinaryTreeNode
{
BinaryTreeNode left, right;
int data;
/* Constructor */
public BinaryTreeNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BinaryTreeNode(int n)
{
left = null;
right = null;
data = n;
}
/* Function to set left node */
public void setLeft(BinaryTreeNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BinaryTreeNode n)
{
right = n;
}
/* Function to get left node */
public BinaryTreeNode getLeft()
{
return left;
}
/* Function to get right node */
public BinaryTreeNode getRight()
{
return right;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}
/* Define anothe Class Operations to perform required operationns on Binary Tree*/
class Operations
{
private BinaryTreeNode root;
/* Constructor */
public Operations()
{
root = null;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return root == null;
}
/* Functions to insert data */
public void insert(int data)
{
root = insert(root, data);
}
/* Function to insert data recursively */
private BinaryTreeNode insert(BinaryTreeNode node, int data)
{
if (node == null)
node = new BinaryTreeNode(data);
else
{
if (node.getRight() == null)
node.right = insert(node.right, data);
else
node.left = insert(node.left, data);
}
return node;
}
/* Function to count number of nodes */
public int countNodes()
{
return countNodes(root);
}
/* Function to count number of nodes recursively */
private int countNodes(BinaryTreeNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
/* Function to search for an element */
public boolean search(int val)
{
return search(root, val);
}
/* Function to search for an element recursively */
private boolean search(BinaryTreeNode r, int val)
{
if (r.getData() == val)
return true;
if (r.getLeft() != null)
if (search(r.getLeft(), val))
return true;
if (r.getRight() != null)
if (search(r.getRight(), val))
return true;
return false;
}
/* Function for inorder traversal */
public void inorder()
{
inorder(root);
}
private void inorder(BinaryTreeNode r)
{
if (r != null)
{
inorder(r.getLeft());
System.out.print(r.getData() +\" \");
inorder(r.getRight());
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(root);
}
priva.
C programming. Answer question only in C code In the eighth part, yo.pdfmohammedfootwear
C programming. Answer question only in C code In the eighth part, you have to implement a
binary search tree. The tree must satisfy the binary search tree property: the key in each node
must be greater than all keys stored in the left sub-tree, and smaller than all keys in right sub-
tree. You have to dynamically allocate space for each node and free the space for the nodes at the
end of the program. This program takes a file name as an argument from the command line. The
file is either blank or contains successive lines of input. Each line starts with a character, either
\'i\' or \'s\' followed by a tab and then an integer. For each line that starts with V, your program
should insert that number in the binary search tree if it is not already there. If it is already
present, you will print \"duplicate\" and not change the tree. If the line starts with a \'s\' your
program should search for the value. Output format: For each fine in the input file, your
program should print the status/result of the operation. For an insert operation, the program
should print either \"inserted\" with a single space followed by a number, the height of the
inserted node in the tree, or \"duplicate\" if the value is already present in the tree. The height of
the root node is 1. For a search, the program should either print \"present\", followed by the
height of the node, or \"absent\" based on the outcome of the search. Your program should print
\"error\" (and nothing else) if the file does not exist or for input lines with improper structure.
Example Execution: Let\'s assume we have a file.txt with the following contents: 5 3 4 1 6 s
Executing the program in the following fashion should produce the output shown below:
$./eighth file1.txt inserted 1 inserted 2 inserted 3 inserted 3 inserted 2 present 3.
Solution
Above program only inserts data / nodes to the binary tree. To print the tree, we need to know
how to traverse a Binary Search Tree
C Program to implement Binary Search Tree Traversal
Preorder traversal sequence : F, B, A, D, C, E, G, I, H
(root, left, right)
Inorder traversal sequence : A, B, C, D, E, F, G, H, I
(left, root, right)
Postorder traversal sequence: A, C, E, D, B, H, I, G, F
(left, right, root)
Program :
# include
# include
# include
typedef struct BST {
int data;
struct BST *lchild, *rchild;
} node;
void insert(node *, node *);
void inorder(node *);
void preorder(node *);
void postorder(node *);
node *search(node *, int, node **);
void main() {
int choice;
char ans = \'N\';
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
root = NULL;
clrscr();
printf(\"\ Program For Binary Search Tree \");
do {
printf(\"\ 1.Create\");
printf(\"\ 2.Search\");
printf(\"\ 3.Recursive Traversals\");
printf(\"\ 4.Exit\");
printf(\"\ Enter your choice :\");
scanf(\"%d\", &choice);
switch (choice) {
case 1:
do {
new_node = get_node();
printf(\"\ Enter The Element \");
scanf(\"%d\", &new_node->data);
if (root == NULL) /* Tree is not Created */
root =.
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfaioils
please navigate to cs112 webpage and go to assignments --> Trees. This will give you the
directions for the assignment. Please do the last 2 methods in huffman.java called encode() and
decode()
Code is provided below:
HuffmanCoding.java
package huffman;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
/**
* This class contains methods which, when used together, perform the
* entire Huffman Coding encoding and decoding process
*
* @author Ishaan Ivaturi
* @author Prince Rawal
*/
public class HuffmanCoding {
private String fileName;
private ArrayList sortedCharFreqList;
private TreeNode huffmanRoot;
private String[] encodings;
/**
* Constructor used by the driver, sets filename
* DO NOT EDIT
* @param f The file we want to encode
*/
public HuffmanCoding(String f) {
fileName = f;
}
/**
* Reads from filename character by character, and sets sortedCharFreqList
* to a new ArrayList of CharFreq objects with frequency > 0, sorted by frequency
*/
public void makeSortedList() {
StdIn.setFile(fileName);
/* Your code goes here */
}
/**
* Uses sortedCharFreqList to build a huffman coding tree, and stores its root
* in huffmanRoot
*/
public void makeTree() {
/* Your code goes here */
}
/**
* Uses huffmanRoot to create a string array of size 128, where each
* index in the array contains that ASCII character's bitstring encoding. Characters not
* present in the huffman coding tree should have their spots in the array left null.
* Set encodings to this array.
*/
public void makeEncodings() {
/* Your code goes here */
}
/**
* Using encodings and filename, this method makes use of the writeBitString method
* to write the final encoding of 1's and 0's to the encoded file.
*
* @param encodedFile The file name into which the text file is to be encoded
*/
public void encode(String encodedFile) {
StdIn.setFile(fileName);
/* Your code goes here */
}
/**
* Writes a given string of 1's and 0's to the given file byte by byte
* and NOT as characters of 1 and 0 which take up 8 bits each
* DO NOT EDIT
*
* @param filename The file to write to (doesn't need to exist yet)
* @param bitString The string of 1's and 0's to write to the file in bits
*/
public static void writeBitString(String filename, String bitString) {
byte[] bytes = new byte[bitString.length() / 8 + 1];
int bytesIndex = 0, byteIndex = 0, currentByte = 0;
// Pad the string with initial zeroes and then a one in order to bring
// its length to a multiple of 8. When reading, the 1 signifies the
// end of padding.
int padding = 8 - (bitString.length() % 8);
String pad = "";
for (int i = 0; i < padding-1; i++) pad = pad + "0";
pad = pad + "1";
bitString = pad + bitString;
// For every bit, add it to the right spot in the corresponding byte,
// and store bytes in the array when finished
for (char c : bitString.toCharArray()) {
if (c != '1' && c != '0') {
System.out.println("Invalid characters in bitstring");
return;
}
if (c .
Refactoring, Agile Entwicklung, Continuous Integration – all diese für nachhaltigen Erfolg wichtigen Vorgehensweisen setzen Erfahrung mit Unit Testing voraus. Abseits von den üblichen "Bowling"-Beispielen möchten wir gerne einen Crashkurs inkl. Best Practices für das erfolgreiche Unit Testing durchführen. Anhand eines Beispielprojekts auf Basis des Zend Frameworks werden wir nach der Installation von PHPUnit auf allen Notebooks gemeinsam eine kleine Applikation aufbauen, die durchgehend Test-driven entwickelt wird.
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like \"+-+7*935*82*625\"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException(\"Underflow\");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println(\"Invalid Expression\");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= \'0\' && ch <= \'9\';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == \'+\' || ch == \'-\' || ch == \'*\' || ch == \'/\';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - \'0\';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public dou.
Thisi s a program of a binary tree which is extended from its super class Simple Tree. It uses all the functionalities from its super class. A binary tree consists of two leaves mainly left child nodes and right child nodes.
You’ve seen Kris’ open source libraries, but how does he tackle coding out an application? Walk through green fields with a Symfony expert as he takes his latest “next big thing” idea from the first line of code to a functional prototype. Learn design patterns and principles to guide your way in organizing your own code and take home some practical examples to kickstart your next project.
Running Head: Discussion Board 1
Discussion Board 3
Discussion Board
Student’s Name
Institution Affiliation
My topics for this discussion will lean on the immigration and the plight of immigrants. This is a subject that will bring a good platform to form an informative as well as persuasive speech. I will specifically address the value of policy making in the management of immigration trends that are increasing in the USA as well as western countries (Zatz, & Rodriguez, 2015). The topic will be “Do illegal immigrants deserve a hearing in the countries they seek asylum or they should just be deported impartially?” I think this is a contentious issue in the world today.
There are many policies that have been established by various international organizations such as UN in regard to Immigration. The underlying issues in this matter still remain dormant and unresolved. The fundamental question of concern is addressing the parties that should be concerned with this matter. I will be addressing the international community as my audience, particularly the UN, countries. The speech will also include recommendations that will be suggested for handling of the matter. It will also give a discourse of the current situation in different parts of the world such as USA and Europe. This will paint a picture of the dire need of the situation and the dangers that immigrants are facing every day. It will also address the plight of illegal immigrants who I will argue that they deserve humanly just and fair treatment whenever they are met by the hand of the law. The speech is intended to bring an evaluation of the essence of humanity in considering one another and building bridges that alleviate instead of perpetuating human suffering in the world.
References
Zatz, M. S., & Rodriguez, N. (2015). Dreams and nightmares: Immigration policy, youth, and families. University of California Press.
ASS12/assg-12.cppASS12/assg-12.cpp/**
*
* @description Assignment 12 Binary Search Trees
*/
#include<cassert>
#include<iostream>
#include"BinaryTree.hpp"
usingnamespace std;
/** main
* The main entry point for this program. Execution of this program
* will begin with this main function.
*
* @param argc The command line argument count which is the number of
* command line arguments provided by user when they started
* the program.
* @param argv The command line arguments, an array of character
* arrays.
*
* @returns An int value indicating program exit status. Usually 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc,char** argv)
{
// -----------------------------------------------------------------------
...
Write a C program that reads the words the user types at the command.pdfSANDEEPARIHANT
Write a C program that reads the words the user types at the command prompt (using the \'int
argc, char * argv[] and store each unique letter in a Binary Search Tree. When a duplicate is
encountered do not store the letter again and instead keep track of the count in the tree. Once the
Binary Search tree has been created print out the tree both inorder and reverse order. Also print
the highest and lowest alphabetically letter in the tree if any.
Solution
# include
# include
# include
typedef struct BST {
int data;
struct BST *lchild, *rchild;
} node;
void insert(node *, node *);
void preorder(node *);
findMinimum(struct node* root)
findMaximum(struct node* root)
void reverseLevelOrder(struct node* root)
void main(int argc,char argv) {
char argv = \'N\';
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
root = NULL;
clrscr();
printf(\"\ Program For Binary Search Tree \");
do {
printf(\"\ 1.Create\");
printf(\"\ 2.Search\");
printf(\"\ 3.Recursive Traversals\");
printf(\"\ 4.Exit\");
printf(\"\ Enter your choice :\");
scanf(\"%d\", &argc);
switch (argc) {
case 1:
do {
new_node = get_node();
printf(\"\ Enter The Element \");
scanf(\"%d\", &new_node->data);
if (root == NULL) /* Tree is not Created */
root = new_node;
else
insert(root, new_node);
printf(\"\ Want To enter More Elements?(y/n)\");
argv= getch();
} while (argv == \'y\');
break;
case 2:
if (root == NULL)
printf(\"Tree Is Not Created\");
else {
printf(\"\ The Preorder display : \");
preorder(root);
}
break;
}
} while (argv != 4);
}
/*
Get new Node
*/
node *get_node() {
node *temp;
temp = (node *) malloc(sizeof(node));
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
/*
This function is for creating a binary search tree
*/
void insert(node *root, node *new_node) {
if (new_node->data < root->data) {
if (root->lchild == NULL)
root->lchild = new_node;
return newNode(key);
else
insert(root->lchild, new_node);
}
if (new_node->data > root->data) {
if (root->rchild == NULL)
root->rchild = new_node;
return newNode(key);
else
insert(root->rchild, new_node);
}
}
if (key == node->key)
{
(node->count)++;
return node;
}
/*
This function displays the tree in preorder fashion
*/
void preorder(node *temp) {
if (temp != NULL) {
printf(\"%d\", temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}
// Returns maximum value in a given Binary Tree
int findMaximum(struct node* root)
{
// Base case
if (root == NULL)
return INT_MAXIMUM;
// Return maximum of 3 values:
// 1) Root\'s data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMaximum (root->lchild);
int rres = findMaximum (root->rchild);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
// Returns minimum value in a given Binary Tree
int findMinimum(struct node* root)
{
// Base case
if (root == NULL)
return INT_MINIMUM;
// Return minimum of 3 values:
// 1) Root\'s data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMinimum(r.
A ISCSI SAN consists of Select one or more A. HBA B. LUN C. Fibr.pdffederaleyecare
A ISCSI SAN consists of Select one or more: A. HBA B. LUN C. Fibre Channel switch D.
Storage system E. Storage processor(SP)
Solution
iSCSi SAN is consist of the storage system for the purpose of storage that uses the RAID level.
This uses the fibre channel and consist of switch in that fibre channel.
Logical unit number which is essential for representing the logical device which is a part of
physical ISCSI device..
Which of the following statements about tRNA molecules is TRUEMul.pdffederaleyecare
Which of the following statements about tRNA molecules is TRUE?
Multiple Choice
Bases in the tRNA loops do not pair with any other bases
tRNA assumes a double helical shape
Every base in a tRNA molecule pairs with another base in the same tRNA strand, leading to its
higher levels of structure
All of these are TRUE
The amino acid is attached to the central loop region of the tRNA molecule
Solution
The amino acid is attached to the acceptor stem of tRNA..
More Related Content
Similar to Create an implementation of a binary tree using the recursive appr.pdf
javaFix in the program belowhandle incomplete data for text fil.pdfbirajdar2
java
Fix in the program below:
handle incomplete data for text file and allow to search multiple items at once
and let it sort duplicate values
and most importantly let it use get and set methods on the Nodes
New Internal Requirements :
For this assignment, you should replace your Database class with another implementation which
uses instances of the Java Collections java.util.LinkedList class to replace your hand-crafted
LinkedList classes. Note the following:
• LinkedList is a generic type; you must instantiate it with concrete class types. Thus, your
Database object will contain several LinkedList objects; you will need to organize these lists into
another instance of LinkedList. (Consider creating a Year object to help with this.)
• You are still required to maintain your lists in sorted order. The pre-built LinkedList methods
do not directly support relative insertion into a linked list; you will need to find ways to
accomplish this with the tools available to you. (There are at least a couple of ways to do this.)
New function to add:
• A new command should be implemented which allows the user to edit a storm from the main
menu. If selected, the program should prompt the user for the year and storm name to be edited.
If a matching storm is found, the corresponding record should be displayed and the user
prompted for new information to be placed in the record. Users may not change the year or storm
name, but may change any of the other information. If no matching storm is found, no action
should be taken. The user should be informed of the outcome in any case.
this is what the txt file the program is reading from looks like:
2000/Alex/0110/0120/0
2001/Bill/0210/0220/0
2002/Chris/0310/0320/0
2003/Devon/0140/0420/0
2004/Eli/0510/0520/1
2005/Fred/0610/0620/2
2006/Gilbert/0710/0820/3
2007/Herbert/0910/0920/4
2008/Kim/1010/1020/5
#######################################Java
Program#######################################################################
###
/*****************************************************************************
***************/
/*This program takes a a file and gives infomation to the user using a LinkedList */
/*****************************************************************************
***************/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
//setting variables to string or int
public class Storm {
private int stormYear;
private int stormMag;
private String stormStart;
private String stormEnd;
private String stormName;
/**
* Constructor
* Storing all variables from text file
* @param stormName
* @param stormYear
* @param stormStart
* @param stormEnd
* @param stormMag
*/
public Storm(String stormName, int stormYear, String stormStart, String stormEnd, int
stormMag) {
this.stormName = stormName;
this.stormYear = stormYear;
this.stormStart = stormStart;
this.stormEnd = stormEnd;
this.stormMag = stormMag;
}
/*******************************.
C programming. Answer question only in C code Ninth Deletion with B.pdfinfo309708
C programming. Answer question only in C code Ninth: Deletion with Binary Search Tree (20
points) In the ninth part, you will extend the binary search tree in the eighth part to support the
deletion of a node. The deletion of a node is slightly trickier compared to the search and insert in
the eighth The deletion is straightforward if the node to be deleted has only one child. You make
the parent of the node to be deleted point to that child. In this scenario, special attention must be
paid only when the node to be deleted is the root Deleting a node with two children requires
some more work. In this case, you must find the minimum element in the right subtree of the
node to be deleted. Then you insert that node in the place where the node to be deleted was. This
process needs to be repeated to delete the minimum node that was just moved In either case, if
the node to be deleted is the root, you must update the pointer to the root to point to the new root
node Input format: This program takes a file name as argument from the command line. The file
is either blank or contains successive lines of input. Each line contains a character, \'i or \'d\'
followed by a tab and an integer. For each line that starts with \'i\', your program should insert
that number in the binary search tree if it is not already there. If the line starts with a \'s, your
program should search for that value. If the line starts with a \'d\', your program should delete
that value from the tree output format: For each line in the input file, your program should print
the status/result of the operation. For insert and search, the output is the same as in the Eighth
Part: For an insert operation, the program should print either \"inserted\" with a single space
followed by a number the height of the inserted mode in the tree, or \"duplicate\" if the value is
already present in the tree. The height of the root node is 1. For a search, the program should
either print \"present\" followed by the height of the node, or absent\" based on the outcome of
the search. For a delete, the program should print \"success or \"fail\" based on the whether the
value was present or not. Again, as in the Eight Part, your program should print \"error\" (and
nothing else) if the file does not exist or for input lines with improper structure Example
Execution: Lets assume we have a file filel.txt with the following contents: i 5 i 3 i 4 i 1 i 6 i 2 s
1 d 3 s 2 Executing the program in the following fashion should produce the output shown
below:
Solution
// C program to demonstrate delete operation in binary search tree
#include
#include
struct node
{
int key;
struct node *left, *right;
};
// A utility function to create a new BST node
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
.
Need Help with this Java Assignment. Program should be done in JAVA .pdfarchiesgallery
Need Help with this Java Assignment. Program should be done in JAVA please
Complete required scripts based on eclipse and troubleshoot the scripts until the tasks are done.
1. Implement a binary search tree (write the code for it), for a height of 2 or higher. Please show
the output if you can Thank you in advance!
Solution
I have compiled this code and checked for errors, worked fine.
Also after the code I have pasted the Output transcript to show what User Inputs I gave and what
all outputs I got.
// Java Program to Implement Binary Tree
import java.util.Scanner;
/* Define Class BinaryTreeNode */
class BinaryTreeNode
{
BinaryTreeNode left, right;
int data;
/* Constructor */
public BinaryTreeNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BinaryTreeNode(int n)
{
left = null;
right = null;
data = n;
}
/* Function to set left node */
public void setLeft(BinaryTreeNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BinaryTreeNode n)
{
right = n;
}
/* Function to get left node */
public BinaryTreeNode getLeft()
{
return left;
}
/* Function to get right node */
public BinaryTreeNode getRight()
{
return right;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}
/* Define anothe Class Operations to perform required operationns on Binary Tree*/
class Operations
{
private BinaryTreeNode root;
/* Constructor */
public Operations()
{
root = null;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return root == null;
}
/* Functions to insert data */
public void insert(int data)
{
root = insert(root, data);
}
/* Function to insert data recursively */
private BinaryTreeNode insert(BinaryTreeNode node, int data)
{
if (node == null)
node = new BinaryTreeNode(data);
else
{
if (node.getRight() == null)
node.right = insert(node.right, data);
else
node.left = insert(node.left, data);
}
return node;
}
/* Function to count number of nodes */
public int countNodes()
{
return countNodes(root);
}
/* Function to count number of nodes recursively */
private int countNodes(BinaryTreeNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
/* Function to search for an element */
public boolean search(int val)
{
return search(root, val);
}
/* Function to search for an element recursively */
private boolean search(BinaryTreeNode r, int val)
{
if (r.getData() == val)
return true;
if (r.getLeft() != null)
if (search(r.getLeft(), val))
return true;
if (r.getRight() != null)
if (search(r.getRight(), val))
return true;
return false;
}
/* Function for inorder traversal */
public void inorder()
{
inorder(root);
}
private void inorder(BinaryTreeNode r)
{
if (r != null)
{
inorder(r.getLeft());
System.out.print(r.getData() +\" \");
inorder(r.getRight());
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(root);
}
priva.
C programming. Answer question only in C code In the eighth part, yo.pdfmohammedfootwear
C programming. Answer question only in C code In the eighth part, you have to implement a
binary search tree. The tree must satisfy the binary search tree property: the key in each node
must be greater than all keys stored in the left sub-tree, and smaller than all keys in right sub-
tree. You have to dynamically allocate space for each node and free the space for the nodes at the
end of the program. This program takes a file name as an argument from the command line. The
file is either blank or contains successive lines of input. Each line starts with a character, either
\'i\' or \'s\' followed by a tab and then an integer. For each line that starts with V, your program
should insert that number in the binary search tree if it is not already there. If it is already
present, you will print \"duplicate\" and not change the tree. If the line starts with a \'s\' your
program should search for the value. Output format: For each fine in the input file, your
program should print the status/result of the operation. For an insert operation, the program
should print either \"inserted\" with a single space followed by a number, the height of the
inserted node in the tree, or \"duplicate\" if the value is already present in the tree. The height of
the root node is 1. For a search, the program should either print \"present\", followed by the
height of the node, or \"absent\" based on the outcome of the search. Your program should print
\"error\" (and nothing else) if the file does not exist or for input lines with improper structure.
Example Execution: Let\'s assume we have a file.txt with the following contents: 5 3 4 1 6 s
Executing the program in the following fashion should produce the output shown below:
$./eighth file1.txt inserted 1 inserted 2 inserted 3 inserted 3 inserted 2 present 3.
Solution
Above program only inserts data / nodes to the binary tree. To print the tree, we need to know
how to traverse a Binary Search Tree
C Program to implement Binary Search Tree Traversal
Preorder traversal sequence : F, B, A, D, C, E, G, I, H
(root, left, right)
Inorder traversal sequence : A, B, C, D, E, F, G, H, I
(left, root, right)
Postorder traversal sequence: A, C, E, D, B, H, I, G, F
(left, right, root)
Program :
# include
# include
# include
typedef struct BST {
int data;
struct BST *lchild, *rchild;
} node;
void insert(node *, node *);
void inorder(node *);
void preorder(node *);
void postorder(node *);
node *search(node *, int, node **);
void main() {
int choice;
char ans = \'N\';
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
root = NULL;
clrscr();
printf(\"\ Program For Binary Search Tree \");
do {
printf(\"\ 1.Create\");
printf(\"\ 2.Search\");
printf(\"\ 3.Recursive Traversals\");
printf(\"\ 4.Exit\");
printf(\"\ Enter your choice :\");
scanf(\"%d\", &choice);
switch (choice) {
case 1:
do {
new_node = get_node();
printf(\"\ Enter The Element \");
scanf(\"%d\", &new_node->data);
if (root == NULL) /* Tree is not Created */
root =.
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfaioils
please navigate to cs112 webpage and go to assignments --> Trees. This will give you the
directions for the assignment. Please do the last 2 methods in huffman.java called encode() and
decode()
Code is provided below:
HuffmanCoding.java
package huffman;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
/**
* This class contains methods which, when used together, perform the
* entire Huffman Coding encoding and decoding process
*
* @author Ishaan Ivaturi
* @author Prince Rawal
*/
public class HuffmanCoding {
private String fileName;
private ArrayList sortedCharFreqList;
private TreeNode huffmanRoot;
private String[] encodings;
/**
* Constructor used by the driver, sets filename
* DO NOT EDIT
* @param f The file we want to encode
*/
public HuffmanCoding(String f) {
fileName = f;
}
/**
* Reads from filename character by character, and sets sortedCharFreqList
* to a new ArrayList of CharFreq objects with frequency > 0, sorted by frequency
*/
public void makeSortedList() {
StdIn.setFile(fileName);
/* Your code goes here */
}
/**
* Uses sortedCharFreqList to build a huffman coding tree, and stores its root
* in huffmanRoot
*/
public void makeTree() {
/* Your code goes here */
}
/**
* Uses huffmanRoot to create a string array of size 128, where each
* index in the array contains that ASCII character's bitstring encoding. Characters not
* present in the huffman coding tree should have their spots in the array left null.
* Set encodings to this array.
*/
public void makeEncodings() {
/* Your code goes here */
}
/**
* Using encodings and filename, this method makes use of the writeBitString method
* to write the final encoding of 1's and 0's to the encoded file.
*
* @param encodedFile The file name into which the text file is to be encoded
*/
public void encode(String encodedFile) {
StdIn.setFile(fileName);
/* Your code goes here */
}
/**
* Writes a given string of 1's and 0's to the given file byte by byte
* and NOT as characters of 1 and 0 which take up 8 bits each
* DO NOT EDIT
*
* @param filename The file to write to (doesn't need to exist yet)
* @param bitString The string of 1's and 0's to write to the file in bits
*/
public static void writeBitString(String filename, String bitString) {
byte[] bytes = new byte[bitString.length() / 8 + 1];
int bytesIndex = 0, byteIndex = 0, currentByte = 0;
// Pad the string with initial zeroes and then a one in order to bring
// its length to a multiple of 8. When reading, the 1 signifies the
// end of padding.
int padding = 8 - (bitString.length() % 8);
String pad = "";
for (int i = 0; i < padding-1; i++) pad = pad + "0";
pad = pad + "1";
bitString = pad + bitString;
// For every bit, add it to the right spot in the corresponding byte,
// and store bytes in the array when finished
for (char c : bitString.toCharArray()) {
if (c != '1' && c != '0') {
System.out.println("Invalid characters in bitstring");
return;
}
if (c .
Refactoring, Agile Entwicklung, Continuous Integration – all diese für nachhaltigen Erfolg wichtigen Vorgehensweisen setzen Erfahrung mit Unit Testing voraus. Abseits von den üblichen "Bowling"-Beispielen möchten wir gerne einen Crashkurs inkl. Best Practices für das erfolgreiche Unit Testing durchführen. Anhand eines Beispielprojekts auf Basis des Zend Frameworks werden wir nach der Installation von PHPUnit auf allen Notebooks gemeinsam eine kleine Applikation aufbauen, die durchgehend Test-driven entwickelt wird.
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like \"+-+7*935*82*625\"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException(\"Underflow\");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println(\"Invalid Expression\");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= \'0\' && ch <= \'9\';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == \'+\' || ch == \'-\' || ch == \'*\' || ch == \'/\';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - \'0\';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public dou.
Thisi s a program of a binary tree which is extended from its super class Simple Tree. It uses all the functionalities from its super class. A binary tree consists of two leaves mainly left child nodes and right child nodes.
You’ve seen Kris’ open source libraries, but how does he tackle coding out an application? Walk through green fields with a Symfony expert as he takes his latest “next big thing” idea from the first line of code to a functional prototype. Learn design patterns and principles to guide your way in organizing your own code and take home some practical examples to kickstart your next project.
Running Head: Discussion Board 1
Discussion Board 3
Discussion Board
Student’s Name
Institution Affiliation
My topics for this discussion will lean on the immigration and the plight of immigrants. This is a subject that will bring a good platform to form an informative as well as persuasive speech. I will specifically address the value of policy making in the management of immigration trends that are increasing in the USA as well as western countries (Zatz, & Rodriguez, 2015). The topic will be “Do illegal immigrants deserve a hearing in the countries they seek asylum or they should just be deported impartially?” I think this is a contentious issue in the world today.
There are many policies that have been established by various international organizations such as UN in regard to Immigration. The underlying issues in this matter still remain dormant and unresolved. The fundamental question of concern is addressing the parties that should be concerned with this matter. I will be addressing the international community as my audience, particularly the UN, countries. The speech will also include recommendations that will be suggested for handling of the matter. It will also give a discourse of the current situation in different parts of the world such as USA and Europe. This will paint a picture of the dire need of the situation and the dangers that immigrants are facing every day. It will also address the plight of illegal immigrants who I will argue that they deserve humanly just and fair treatment whenever they are met by the hand of the law. The speech is intended to bring an evaluation of the essence of humanity in considering one another and building bridges that alleviate instead of perpetuating human suffering in the world.
References
Zatz, M. S., & Rodriguez, N. (2015). Dreams and nightmares: Immigration policy, youth, and families. University of California Press.
ASS12/assg-12.cppASS12/assg-12.cpp/**
*
* @description Assignment 12 Binary Search Trees
*/
#include<cassert>
#include<iostream>
#include"BinaryTree.hpp"
usingnamespace std;
/** main
* The main entry point for this program. Execution of this program
* will begin with this main function.
*
* @param argc The command line argument count which is the number of
* command line arguments provided by user when they started
* the program.
* @param argv The command line arguments, an array of character
* arrays.
*
* @returns An int value indicating program exit status. Usually 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc,char** argv)
{
// -----------------------------------------------------------------------
...
Write a C program that reads the words the user types at the command.pdfSANDEEPARIHANT
Write a C program that reads the words the user types at the command prompt (using the \'int
argc, char * argv[] and store each unique letter in a Binary Search Tree. When a duplicate is
encountered do not store the letter again and instead keep track of the count in the tree. Once the
Binary Search tree has been created print out the tree both inorder and reverse order. Also print
the highest and lowest alphabetically letter in the tree if any.
Solution
# include
# include
# include
typedef struct BST {
int data;
struct BST *lchild, *rchild;
} node;
void insert(node *, node *);
void preorder(node *);
findMinimum(struct node* root)
findMaximum(struct node* root)
void reverseLevelOrder(struct node* root)
void main(int argc,char argv) {
char argv = \'N\';
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
root = NULL;
clrscr();
printf(\"\ Program For Binary Search Tree \");
do {
printf(\"\ 1.Create\");
printf(\"\ 2.Search\");
printf(\"\ 3.Recursive Traversals\");
printf(\"\ 4.Exit\");
printf(\"\ Enter your choice :\");
scanf(\"%d\", &argc);
switch (argc) {
case 1:
do {
new_node = get_node();
printf(\"\ Enter The Element \");
scanf(\"%d\", &new_node->data);
if (root == NULL) /* Tree is not Created */
root = new_node;
else
insert(root, new_node);
printf(\"\ Want To enter More Elements?(y/n)\");
argv= getch();
} while (argv == \'y\');
break;
case 2:
if (root == NULL)
printf(\"Tree Is Not Created\");
else {
printf(\"\ The Preorder display : \");
preorder(root);
}
break;
}
} while (argv != 4);
}
/*
Get new Node
*/
node *get_node() {
node *temp;
temp = (node *) malloc(sizeof(node));
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
/*
This function is for creating a binary search tree
*/
void insert(node *root, node *new_node) {
if (new_node->data < root->data) {
if (root->lchild == NULL)
root->lchild = new_node;
return newNode(key);
else
insert(root->lchild, new_node);
}
if (new_node->data > root->data) {
if (root->rchild == NULL)
root->rchild = new_node;
return newNode(key);
else
insert(root->rchild, new_node);
}
}
if (key == node->key)
{
(node->count)++;
return node;
}
/*
This function displays the tree in preorder fashion
*/
void preorder(node *temp) {
if (temp != NULL) {
printf(\"%d\", temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}
// Returns maximum value in a given Binary Tree
int findMaximum(struct node* root)
{
// Base case
if (root == NULL)
return INT_MAXIMUM;
// Return maximum of 3 values:
// 1) Root\'s data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMaximum (root->lchild);
int rres = findMaximum (root->rchild);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
// Returns minimum value in a given Binary Tree
int findMinimum(struct node* root)
{
// Base case
if (root == NULL)
return INT_MINIMUM;
// Return minimum of 3 values:
// 1) Root\'s data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMinimum(r.
Similar to Create an implementation of a binary tree using the recursive appr.pdf (20)
A ISCSI SAN consists of Select one or more A. HBA B. LUN C. Fibr.pdffederaleyecare
A ISCSI SAN consists of Select one or more: A. HBA B. LUN C. Fibre Channel switch D.
Storage system E. Storage processor(SP)
Solution
iSCSi SAN is consist of the storage system for the purpose of storage that uses the RAID level.
This uses the fibre channel and consist of switch in that fibre channel.
Logical unit number which is essential for representing the logical device which is a part of
physical ISCSI device..
Which of the following statements about tRNA molecules is TRUEMul.pdffederaleyecare
Which of the following statements about tRNA molecules is TRUE?
Multiple Choice
Bases in the tRNA loops do not pair with any other bases
tRNA assumes a double helical shape
Every base in a tRNA molecule pairs with another base in the same tRNA strand, leading to its
higher levels of structure
All of these are TRUE
The amino acid is attached to the central loop region of the tRNA molecule
Solution
The amino acid is attached to the acceptor stem of tRNA..
Write a C program to simulate the description below using semaphores.pdffederaleyecare
Write a C program to simulate the description below using semaphores to synchronize the
processes/threads.
A group of fraternity brother and sorority sisters is having a party and drinking from a large
communal keg that can hold N servings of soda. When a partier wants to drink, he or she fills a
cup from keg, unless it is empty. If the keg is empty, the partier wakes up the pledge and then
waits until the pledge has returned with a new keg.
Solution
#include
#include
#include
#include
#include
#include
#include
#define MAX 10
//Keg which holds no of servings
int N = MAX;
int brothers,sisters,i=0;
int Bservings,Sservings;
void pledge(int signo);
int main()
{
int pidb,pids;
signal( SIGUSR1, pledge ); //instal signal handler
//for semaphore declaration
int sem_id,j; /* semid of semaphore set */
key_t key = 1234; /* key to pass to semget() */
int nsems = 1; /* nsems to pass to semget() */
//for semaphore operation
struct sembuf sop;
sem_id=semget(key,nsems,IPC_CREAT|0666);
printf(\"No of brothers = \");
scanf(\"%d\",&brothers);
printf(\"No of sisters = \");
scanf(\"%d\",&sisters);
//create no of brothers
while(brothers)
{
pidb = fork();
if( pidb > 0 )
{
printf(\"Parent process\ \");
sop.sem_num = 0;
sop.sem_op = -1;
sop.sem_flg = 0;
if (semop(sem_id, &sop, 1))
{
perror(\"Could not increment semaphore\");
exit(5);
}
kill(getpid(),SIGUSR1);
for(j=0; j=0 && Bservings<= N)
{
++Bservings;
N-=Bservings;
printf(\"N = %d\ \",N);
printf(\"Servings = %d\ \",Bservings);
printf(\"Brother%d has taken %d servings\ \",i,Bservings);
}
else
{
printf(\"Brorhes else\ \");
kill(getpid(),SIGUSR1);
sop.sem_num = 0;
sop.sem_op = -1;
sop.sem_flg = 0;
if (semop(sem_id, &sop, 1))
{
perror(\"Could not increment semaphore\");
exit(5);
}
}
}
--brothers;
}
//create no of brothers
i = 0;
while(sisters)
{
pids = fork();
if( pidb > 0 )
{
printf(\"Parent process\ \");
for(j=0; j=0 && Sservings<= N)
{
++Sservings;
N-=Sservings;
printf(\"N = %d\ \",N);
printf(\"Servings = %d\ \",Sservings);
printf(\"Brother%d has taken %d servings\ \",i,Sservings);
}
else
{
printf(\"sisters else\ \");
kill(getpid(),SIGUSR1);
sop.sem_num = 0;
sop.sem_op = -1;
sop.sem_flg = 0;
if (semop(sem_id, &sop, 1))
{
perror(\"Could not increment semaphore\");
exit(5);
}
}
}
--sisters;
}
}
//if empty execute pledge
void pledge(int signo)
{
//for semaphore operation
struct sembuf sop;
int sem_id; /* semid of semaphore set */
key_t key = 1234; /* key to pass to semget() */
int nsems = 1; /* nsems to pass to semget() */
sem_id=semget(key,nsems,0666);
if (signo == SIGUSR1)
printf(\"received SIGUSR1\ \");
else if (signo == SIGKILL)
printf(\"received SIGKILL\ \");
else if (signo == SIGSTOP)
printf(\"received SIGSTOP\ \");
//set keg to new value
N = MAX;
sop.sem_num = 0;
sop.sem_op = 1;
sop.sem_flg = 0;
if (semop(sem_id, &sop, 1))
{
perror(\"Could not increment semaphore\");
exit(5);
}
printf(\"Exiting pledge after setting keg to MAX value\");
}.
When analyzing any particular primary source, historians must consid.pdffederaleyecare
When analyzing any particular primary source, historians must consider all of the following
except:
Select one:
a. the perspectives not included in the source.
b. the source creator\'s bias and what the creator had to gain or lose by creating the source.
c. contrasting or corroborating evidence that will refute/support that source.
d. the historical context of the time at which the source was created.
e. the arguments presented by Wikipedia about that source.
Solution.
What is Linux SecuritySolutionLinux Security is a module in.pdffederaleyecare
What is Linux Security?
Solution
Linux Security is a module in a Linux Operationg System which gives Protection from security
attacks and misuse of Operating Sysytem.It ensure Protection from the Enemy who\'s Bad
Intention is to leak ,steal,change data or Hack your system. There are different types of security
threat as follow:
Reading data - Typically associated with espionage or theft, computer systems often contain
information that needs to be kept confidential or secure. This could vary from emails discussing
the price of a bid for a project to personal information or bank details. The disclosure of this
information could severely damage the company or have legal implications
Changing data - Potentially even more serious is that an attack could gain sufficient access to be
able to update data. This could be for sabotage, as a means of discrediting the organisation or
leaving a calling card. One of the biggest risks is that data could be modified and not noticed.
The cases that tend to get a high profile in this area are where attackers replace web pages with
their own modified versions.
Denial of service - Denial of Service (DoS) attacks are where the attacker disables, or makes
unusable the services provided by the system
Access to computer - Whilst for some systems you may allow other users onto your system
sometimes these user accounts could come under attack. The computer may not contain any
confidential material and the user may not be able to write to any data however they could still
use your system to cause damage. If someone manages to attack a computer that borders between
a secure and insecure network then they could use your machine as a method of traversing
between the two networks.
Linux OS has Security Policy which ensure that you have covered all of the principles
Authorisation, Authenticity, Privacy / Confidentiality, Integrity, Non-repudiation and
Availability as they apply to your system. Also consider how this is going to be implemented by
the users and system administrators. If a security process is hard to implement or restricts
someone from doing their job then you may find that the process gets ignored or is not complied
with.
Linux security Policy Requriments according to Data Protection Act 1998 and ISO 7984-2
International Standards Organisation Security Standard are:
Authorisation - Only allow those that need access to the data
Authenticity - Verifying they are who they say they are
Privacy / Confidentiality - Ensure personal information is not being compromised
Integrity - Ensuring that the data has not been tampered with
Non-repudiation - Confirmation that data is received. The ability to prove it in court
Availability - Ensure that the system can perform it’s required function.
What is the runtime complexity of Adams famous string splitter cod.pdffederaleyecare
What is the runtime complexity of Adam\'s famous string splitter code? Hint: Make sure to look
into the source code for string.find() in the C++ std library. I’ve included that code (downloaded
from GNU). static vector ring text string delimiter vector ring pieces int location text, (delimiter);
inte start 0; //while we find something interesting while location string DRos)f build substring
string piece text substr (start location start); (piece start location 1 //find again location ext find
deli miter start); string piece text substr (start location start); pieseswRush bask (piece return
pieces;
Solution
Assumption is we have text length as N and we have N-1 delimeters in that text.
text.find() -->Takes O(n) time in the worst case to find the delimeter.
vectorpieces; -->O(1)
int location = text.find();delimeter-->At max O(n)
while(location!=string.pos()){ . -> Runs N times
string piece = text.substr(start,location-start); -->At max takes O(N) [Copying that many
characters]*N times for while loop
start = location+1; -->O(1)
location = text.find(delimeter,start);-->At Max O(N) * N times for while loop
So While loop will run N time as we have N-1 delmieters and each time finding substr() and
find() on an average will take O(n). So overall time complexity is O(N2)
}
Thanks, let me know if there is any concern..
What does personalized learning mean to you What does personal.pdffederaleyecare
What does personalized learning mean to you?
What does personalized learning mean to you?
Solution
Personalized learning is an approach to general education.
Kids learn in different ways and at different paces. Personalized learning is a teaching model
based on that premise. Each student gets a “learning plan” based on how he learns, what he
knows, and what his skills and interests are.
With personalized learning, students are an integral part of the learning process. They work with
their teachers to set both short-term and long-term goals, and they take ownership of their own
learning..
What do patients in healthcare expect from their insurance company.pdffederaleyecare
What do patients in healthcare expect from their insurance company?
Solution
Health insurance is insurance against the risk of incurring medical expenses among individuals.
Depending on the type of health insurance coverage, either the insured pays costs out-of-pocket
and is then reimbursed, or the insurer makes payments directly to the provider.
The patients expect from their insurance companies to cover at least following services:-.
Use Table A to find the number z such that the proportion of observa.pdffederaleyecare
Use Table A to find the number z such that the proportion of observations that are less than z in a
standard Normal distribution is 0.26.
z (±0.01) =
Find the number z such that 34% of all observations from a standard Normal distribution are
greater than z.
z (±0.01) =
Solution
1. Z=0.64
2. Z=0.41
I looked in the table Z.
Two of the main political systems are democracy and totalitarianism..pdffederaleyecare
Two of the main political systems are democracy and totalitarianism. Define in your own words.
Solution
Democracy can be defined as a freedom of the people in a nation to opt for whatever they want.
The citizens of the country have the right to all the resources of the country. The majority of the
country decides the direction and the fate of the country. In a democracy, the leaders and
government are selected by the election process and it can also be removed if the public opposes
the government in power.
Opposite of the democracy is authoritarian and the totalitarian type of governance. In these types
of governance style, the leadership of the country remains with a single individual or a group
leading the entire country. These can be seen as a dictatorship.
In case of a totalitarian regime, the individual who holds the power or the dictator has the
influence of his charisma over the people. The citizens are attracted by his prophetic leadership
which makes these citizens perform and follow the wishes and orders of the dictator. Examples:-
Joseph Stalin of USSR, Benito Mussolini of Italy, and Adolf Hitler of Germany. There is a sense
of connection between the citizens and the dictators and this is how the dictator is able to rule the
country. A sense of ideology is mutually shared by the citizens and the totalitarian.
The procedure of transferring journal entries to the ledger accounts .pdffederaleyecare
The procedure of transferring journal entries to the ledger accounts is called journalizing.
analyzing. reporting. posting.
Solution
Answer is Posting.
Explanation:
The process of recording the debit and credit aspect of each journal entry in the respective ledger
accounts is known as Posting of entries to ledger accounts..
The ProblemUsing C programming language write a program that simul.pdffederaleyecare
The Problem
Using C programming language write a program that simulates the Tiny Machine Architecture.
Your code must implement the basic instruction set that the Tiny Machine Architecture adheres
to (LOAD[1], ADD[2], STORE[3], SUB[4], IN[5], OUT[6], END[7], JMP[8], SKIPZ[9]). Each
piece of the architecture must be accurately represented in your code (Instruction Register,
Program Counter, Memory Address Register, Data Memory, Memory Data Register, and
Accumulator). Data Memory will be represented by a 0-9 array. Your Program Counter will
begin at 10.
For the sake of simplicity Program Memory and Data Memory may be implemented as separate
arrays.
Hint: Implementing a struct for your Instructions and an array of these structs as your Program
Memory greatly simplifies this program.
Example:
typedef struct {
int opCode, deviceOrAddress;
} Instruction;
Instruction programMemory[MAXPROGRAMSIZE];
Input Specifications
Your simulator must run from the command line with a single input file as a parameter to main.
This file will contain a sequence of instructions for your simulator to assemble (store in
“program memory”) and then run via the fetch/execute cycle.
Example:
5 5 //IN 5
6 7 //OUT 7
3 0 //STORE 0
5 5 //IN 5
6 7 //OUT 7
3 1 //STORE 1
1 0 //LOAD 0
4 1 //SUB 1
3 0 //STORE 0
6 7 //OUT 7
1 1 //LOAD 1
6 7 //OUT 7
7 0 //END
Output Specifications
Your simulator should provide output according to the input file. Along with this output your
program should provide status messages identifying details on the workings of your simulator.
Output text does not have to reflect my example word-for-word, but please provide detail on the
program as it runs in a readable format that does not conflict with the actual output of your
simulator. After each instruction print the current state of the Program Counter, Accumulator,
and Data Memory. The INPUT instruction is the only one that should prompt an interaction from
the user.
Example:
Assembling Program…
Program Assembled.
Run.
PC = 10 | A = NULL | MEM = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
/* input value */
X
PC = 11 | A = X | MEM = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
/* outputting accumulator to screen */
X
PC = 12 | A = X | MEM = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
/* storing accumulator to memory location 0 */
PC = 13 | A = X | MEM = [X, 0, 0, 0, 0, 0, 0, 0, 0, 0]
… etc
Program complete.
Grading
Your simulator will be graded on the above criteria. Your program should compile and run from
the command line with one input file parameter. Please note that your program will not just be
graded on whether or not it runs successfully; accurate simulation and a thorough demonstration
of your understanding on the workings of this architecture will constitute a large portion of this
grade. As that is the case it is in your best interest to comment your program in a concise and
readable way. However, if your program does not run or compile the maximum points possible
will be 50 (up to 25 may be recovered by debugging and demonstrating a.
5. Joe and Sam are using Public Key encryption. Joe’s public and pri.pdffederaleyecare
5. Joe and Sam are using Public Key encryption. Joe’s public and private keys are named Joe-
Pub and Joe-Priv. Sam’s public and private keys are named Sam-Pub and Sam-Priv. a) (5 points)
Assume Sam is sending encrypted data to Joe. What key (out of the 4 keys listed above) does
Sam use to encrypt the data? What key does Joe use to decrypt the data? b) (5 points) Now
assume Sam is putting digital signatures on his messages to Joe to prove his identity. He does
this by encrypting the HMAC hash code at the end of the message. What key does Sam use to
encrypt this HMAC code? What key does Joe use to decrypt the encrypted HMAC code that he
receives?
Solution
Suppose A(sender) wants to send some data to B(receiver) using public-private key encryption.
Then A(sender) has to encrypt the data using public key of B(receiver). When B(receiver) will
get the data, he will decrypt it using his own private key.
So answer to first question (a) is that:
Sam will be using Joe-Pub to encrypt the data to be sent to Joe. And Joe will use Joe-Priv to
decrypt the data.
For question(b), the case is similar to question(a).
Sam will be using Joe-Pub key to encrypt the HMAC and Joe will be using Joe-Priv to decryp
the HMAC of Sam..
QUESTION 7 When using the indirect method to prepare the statement of.pdffederaleyecare
QUESTION 7 When using the indirect method to prepare the statement of cash flows,
depreciation expense should be presented as a(n): O addition to net income. o cash flow from
financing activities cash flow from investing activities. O deduction from net income. O
investing and financing activity not affecting cash.
Solution
A. addition to net income.
Depreciation is added back in cash flow statement because it is a non-cash item, which had
reduced the net income, and thus should be added back..
Q.1. Define noncontrolling (minority) interest. List three methods th.pdffederaleyecare
Q.1. Define noncontrolling (minority) interest. List three methods that might be used for
reporting the noncontrolling interest in a consolidated
Solution
Non Controlling Interest also known as Minority Interest is that portion of the subsidiary\'s
equity capital which is not held or own or controlled by the parent company. Parent company
here means who has a controlling interest of 50% or more in the subsidiary and who consolidates
their financial statements with its own.
Three methods to report NCI are:.
Picking a fruit-flavored or primary colored bean. overlapping event .pdffederaleyecare
Picking a fruit-flavored or primary colored bean. overlapping event mutually exclusive event
compound event dependent Picking a red or green or fruit-flavored bean, dependent
compound event mutually exclusive event overlapping event
Solution
13. picking a fruit flavoured or primary cloured bean is a compound event
compound event is a event with two or more favourable outcomes.
Part F - Viral Evolution and LysogenyOne hypothesis regarding the .pdffederaleyecare
Part F - Viral Evolution and Lysogeny
One hypothesis regarding the origin of viruses suggests that early viruses may have had
primarily latent life cycles and that they served a function by helping to transfer genes from one
cell to another. This hypothesis suggests that perhaps the lytic life cycle evolved later to allow
the viruses to more rapidly spread from one cell to another. How could the researchers studying
the archaeal RNA viruses determine whether those viruses have lytic or latent life cycles?
Choose all of the correct answers.
1. They could examine the genomes that they have assembled to determine whether genes
associated with lysogeny were present.
3. There is no way to determine the life cycle of the archaeal RNA viruses without observing the
viruses causing infection
4.They could examine the genomes of the archaeal RNA viruses to look for evidence of
uncoating genes.
1. They could examine the genomes that they have assembled to determine whether genes
associated with lysogeny were present.2. They could consider the life cycles of more well-known
archaeal viruses, which are rarely lysogenic, and compare the new viruses with known lysogenic
archaeal viruses.
3. There is no way to determine the life cycle of the archaeal RNA viruses without observing the
viruses causing infection
4.They could examine the genomes of the archaeal RNA viruses to look for evidence of
uncoating genes.
Solution
Answer : 2
Molecular mechanisms underlying the various stages of the viral life cycle remain poorly
understood in Archaea. (Quentin et al., 2014). Cell surface , environmental adaptibility, nature of
cell wall of archaea has great influence on the viral entry.
Hence, the approach of comparing the new virus with well known lysogenic archaea virus is
considered better..
Match the following Data vs Information Reliability as it adds value .pdffederaleyecare
Match the following Data vs Information Reliability as it adds value to information The IPO
model A Takes raw input and turns it into something meaningful vthile still allowing an
opportunity for adjustment of results. B. True C. Responding to different cultural needs/desires. \'
A critical component of a CBS A CBIS used to perform and record business related exchanges.
Are the Internet and the WWW the same thing? TPS A strategy for attaining competitive
advantage Financial evaluation is an important part of evaluation IS E False F. r: Providing
choices; varety; or higher quality The difference between raw facts and those that are organized
and processed in a way that adds value. projects H Is responsible for equipment, personnel,
finance, accounting and value or IS. Establishes trust; can be dependent on its source; can be a A
global challenge for information systems victim of poor data collection An organized collection
of facts and information-usually maintained in two or more related files.
Solution
Data vs information:- G:_ The difference between raw facts and those that are organized and
processed in a way that adds value
Reliability as it adds value to information:- I:- Establish trust; can dependent on its siurce; can be
a victim of poor data collection
The IPO model:- A:- Takes raw input and turns into something meaningful while still allowing
and opportunity for adjustment of results.
A critical component of CBIS:- J:- an organized collection of facts and information0usually
maintained iin two or more related files
Are the internet and www the same thing :- E:- FALSE
TPS:- D:- A CBIS used to perform and record business related exchanges
A strategy for attaining competitive advantage:- F:- Providing choices; variety or higher quality
Financial evaluation is an importance part of evaluation IS projects:- B:- True
CIO:- H:- is responsible for equipment, personnel, finance, accounting and value or IS
A global challenge for information systems:- C:- responding to different cultural needs/desires.
Many organizations invest substantial resources in creating their ow.pdffederaleyecare
Many organizations invest substantial resources in creating their own project methodologies,
which are sets of templates, process maps, and procedures that show the normal flow of a project
from start to finish. Other organizations have no formal project management methods, and it is
difficult for project managers and team members to be certain about what phase the project is in.
If informal project management can get the job done, why do we need fancy methods and
processes and terminology? Have you ever been involved in a project that didn’t follow the
standard cycle of initiating, planning, executing, and closing? Is it ethical to under plan or over
plan a project? Why or why not?
Solution
Q1) Informal project management doesn\'t have a detailed project plan outlining the phases,
resources and budget. It is followed by small companies where the project scale is low. The
phases begin and end in a flow rather than being preplanned. Though informal project
management can get the job done for small scale projects with not much budget involved and
relatively lesser sense of urgency for completion, for a project to be successful in all aspects, a
formal project management methodology needs to be in place. Below are the reasons -
1. Though project exceeds the cost expected and gets delayed to a small extent, it is difficult to
quantify and estimate in informal project management methodology and hence the firm doesn\'t
even know the loss being incurred.
2. Allocating, monitoring and controlling resources becomes difficult in informal methods.
3. Lack of accountability results in not owning any issues that might occur in the project.
Q2) Example of a project that is informal -
Quality circles formed by a group of employees from various departments or functions to
improve overall quality of the product and eliminate deviations from the process.
The project starts with identifying quality issue and random inputs pour in from all the functional
departments that are collected by a moderator who keeps scheduling recurring meetings to
ensure the rootcause of the issue is identified and the alternatives are prepared. The solution then
is identified by testing all the three alternatives at a pilot scale and the best alternative is
implemented.
Q3) Underplanning or overplanning a project is never known in advance and is known while
project is in progress. Individuals never wilfully over or under plan for the project; sometimes it
might happen to over plan if the project manager wants to keep a buffer of time, resources and
budget. Underplanning is purely a deviation from the project and as far as ethics is concerned, it
is not something which is expected though it doesn\'t wilfully happen..
Lets compare and contrast the national cultures of Egypt and Brazi.pdffederaleyecare
Let\'s compare and contrast the national cultures of Egypt and Brazil. Identify the main
differences and similarities between the two countries using project GLOBE (each 9 dimension
and give an example)
Solution
Answer:
As per PROJECT GLOBE, there are only 6 dimensions of culturally endorsed implicit leadership
and they are as follows,
And 9 nos are the cultural competencies..
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Create an implementation of a binary tree using the recursive appr.pdf
1. "Create an implementation of a binary tree using the recursive approach introduced in the
chapter. In this approach, each node is a binary tree. Thus a binary tree contains a reference to
the element stored at its root as well as references to its left and right subtrees. You may also
want to include a reference to its parent." p.741
You need to use the locally implemented binary tree. This means you need to have a "jsjf"
subfolder with at least these files: BinaryTreeADT.java, LinkedBinaryTree.java,
BinaryTreeNode.java, and the exceptions sub-subfolder.
Test/demonstrate your binary tree by doing the following:
Request file name from user,
Read an infix expression from file,
Build binary expression tree,
Display binary expression tree,
Evaluate binary expression tree,
Display result.
##############################################
Note a typical input file can be found here
##############################################
# Version 0.2, fully parenthesized.
# This is a comment
((9 + 4) * 5) + (4 - (6 + 3))
# Note first expression should evaluate to 60
((42 + ( 10 - 2 )) + ( 5 * 3 )) / 6
# Note second expression should evaluate to 65 / 6 or 10 (integer division)
##############################################
My program is below but the out put is incorrect
##############################################
StringTree.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;
import jsjf.BinaryTreeNode;
import jsjf.LinkedBinaryTree;
2. public class StringTree extends LinkedBinaryTree {
public StringTree(String rootStr, StringTree leftSubtree, StringTree rightSubtree) {
root = new BinaryTreeNode(rootStr, leftSubtree, rightSubtree);
} // StringTree
public StringTree(File f) {
Stack leftStack = new Stack(), rightStack = new Stack();
// stacks of left and right subtrees of nodes
Scanner scan;
// scanner for reading from the file
String nodeType,
nodeStr;
// string contained in the current node
boolean hasLeftChild, hasRightChild;
// true if the current node has a left or right child
StringTree leftSubtree, rightSubtree,
// left and right subtrees of the current node
subtree;
// subtree having the current node as its root
// Create a scanner for reading from the file.
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
root = null;
System.out.println(" "+"The program has terminated......");
System.exit(0);
return;
}
// Read the file and build a tree from the bottom up.
while (scan.hasNext()) {
// Input information about a tree node.
nodeType = scan.next();
hasLeftChild = (scan.next().equalsIgnoreCase("y"));
hasRightChild = (scan.next().equalsIgnoreCase("y"));
3. nodeStr = scan.next();
// Determine the left and right subtrees of the subtree
// having the node as its root.
if (hasLeftChild)
leftSubtree = leftStack.pop();
else
leftSubtree = null;
if (hasRightChild)
rightSubtree = rightStack.pop();
else
rightSubtree = null;
// Create the subtree having the node as its root.
subtree = new StringTree(nodeStr, leftSubtree, rightSubtree);
// Push the subtree onto the appropriate stack or finish
// construction of the whole tree.
if (nodeType.equalsIgnoreCase("L"))
leftStack.push(subtree);
else if (nodeType.equalsIgnoreCase("R"))
rightStack.push(subtree);
else {
root = subtree.root;
break;
}
} // while
} // StringTree
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// scanner to read keyboard input
String name;
// name of a tree description file
File f;
// the corresponding file object
StringTree tree;
// tree constructed from the file
// Input a tree description file name and create a
// corresponding file object.
4. System.out.print("Enter a tree description file name: ");
name = scan.nextLine();
scan.close();
f = new File(name);
// Create a tree as described by the file.
tree = new StringTree(f);
// Display the tree.
System.out.print(tree.toString());
// Find and display the tree's height.
System.out.println("The tree's height is: " + tree.getHeight());
// List the nodes in the order visited in a post-order
// traversal.
Iterator post = tree.iteratorPostOrder();
System.out.print("Traversed in PostOrder: ");
while (post.hasNext()) {
System.out.print(post.next() + " ");
}
//Printing terminating message
System.out.println(" "+" "+"The program has terminated......");
} // main
} // class StringTree
// ***************************************************************
LinkedBinaryTree.java
package jsjf;
import java.util.*;
import jsjf.exceptions.*;
public class LinkedBinaryTree implements BinaryTreeADT, Iterable {
protected BinaryTreeNode root;
protected int modCount = 0;
public LinkedBinaryTree() {
root = null;
} // LinkedBinaryTree
public LinkedBinaryTree(T element) {
5. root = new BinaryTreeNode(element);
} // LinkedBinaryTree
public LinkedBinaryTree(T element, LinkedBinaryTree left, LinkedBinaryTree right) {
root = new BinaryTreeNode(element);
root.setLeft(left.root);
root.setRight(right.root);
} // LinkedBinaryTree
public T getRootElement() throws EmptyCollectionException {
if (root == null) {
throw new EmptyCollectionException("There is no element at root! There must be a
root element to"
+ "create a tree.");
} else {
return root.getElement();
}
} // getRootElement
protected BinaryTreeNode getRootNode() throws EmptyCollectionException {
if(root == null){
throw new EmptyCollectionException("There is no node at root! There must be a root
node to"
+ "create a tree.");
} else{
return root;
}
} // getRootNode
public LinkedBinaryTree getLeft() {
BinaryTreeNode leftChild;
LinkedBinaryTree leftSubtree;
if (root == null)
return null;
leftChild = root.getLeft();
if (leftChild == null)
return null;
leftSubtree = new LinkedBinaryTree();
leftSubtree.root = leftChild;
6. return leftSubtree;
} // getLeft
public LinkedBinaryTree getRight() {
BinaryTreeNode rightChild;
LinkedBinaryTree rightSubtree;
if (root == null)
return null;
rightChild = root.getRight();
if (rightChild == null)
return null;
rightSubtree = new LinkedBinaryTree();
rightSubtree.root = rightChild;
return rightSubtree;
} // getRight
public boolean isEmpty() {
return (root == null);
} // isEmpty
public int size() {
return 0;
} // size
public int getHeight() {
if (this.isEmpty()) {
System.out.println(" "+"Check file for formatting errors.....");
System.out.println(" "+"The program has terminated......");
System.exit(0);
return 0;
} else {
BinaryTreeNode node = root;
return height(node);
}
} // getHeight
private int height(BinaryTreeNode node) {
if (node == null){
return -1;
}
7. int leftSub = height(node.left);
int rightSub = height(node.right);
if (leftSub > rightSub){
return leftSub + 1;
}
else{
return rightSub + 1;
}
} // height
public boolean contains(T targetElement) {
return false;
} // contains
public T find(T targetElement) throws ElementNotFoundException {
BinaryTreeNode current = findNode(targetElement, root);
if (current == null)
throw new ElementNotFoundException("LinkedBinaryTree");
return (current.getElement());
} // find
private BinaryTreeNode findNode(T targetElement, BinaryTreeNode next) {
if (next == null)
return null;
if (next.getElement().equals(targetElement))
return next;
BinaryTreeNode temp = findNode(targetElement, next.getLeft());
if (temp == null)
temp = findNode(targetElement, next.getRight());
return temp;
} // findNode
public String toString() {
return toString(root, 0);
} // toString
// Recursive helper method for the toString method.
private String toString(BinaryTreeNode node, int indent) {
String result = "";
BinaryTreeNode leftChild, rightChild;
8. if (node == null)
return "";
rightChild = node.getRight();
if (rightChild != null)
result += toString(rightChild, indent + 1);
for (int k = 1; k <= indent; k++)
result += " ";
result += node.getElement() + " ";
leftChild = node.getLeft();
if (leftChild != null)
result += toString(leftChild, indent + 1);
return result;
} // toString
public Iterator iterator() {
return iteratorInOrder();
} // iterator
public Iterator iteratorInOrder() {
ArrayUnorderedList tempList = new ArrayUnorderedList();
inOrder(root, tempList);
return new TreeIterator(tempList.iterator());
} // iteratorInOrder
protected void inOrder(BinaryTreeNode node, ArrayUnorderedList tempList) {
if (node != null) {
inOrder(node.getLeft(), tempList);
tempList.addToRear(node.getElement());
inOrder(node.getRight(), tempList);
}
} // inOrder
public Iterator iteratorPreOrder() {
return null;
} // iteratorPreOrder
protected void preOrder(BinaryTreeNode node, ArrayUnorderedList tempList) {
// To be completed as a Programming Project
} // preOrder
9. public Iterator iteratorPostOrder() {
ArrayUnorderedList tempList = new ArrayUnorderedList();
postOrder(root, tempList);
return new TreeIterator(tempList.iterator());
} // iteratorPostOrder
protected void postOrder(BinaryTreeNode node, ArrayUnorderedList tempList) {
if (node != null) {
postOrder(node.getLeft(), tempList);
postOrder(node.getRight(), tempList);
tempList.addToRear(node.getElement());
}
} // postOrder
public Iterator iteratorLevelOrder() {
ArrayUnorderedList> nodes = new ArrayUnorderedList>();
ArrayUnorderedList tempList = new ArrayUnorderedList();
BinaryTreeNode current;
nodes.addToRear(root);
while (!nodes.isEmpty()) {
current = nodes.removeFirst();
if (current != null) {
tempList.addToRear(current.getElement());
if (current.getLeft() != null)
nodes.addToRear(current.getLeft());
if (current.getRight() != null)
nodes.addToRear(current.getRight());
} else
tempList.addToRear(null);
}
return new TreeIterator(tempList.iterator());
} // iteratorLevelOrder
private class TreeIterator implements Iterator {
private int expectedModCount;
private Iterator iter;
10. public TreeIterator(Iterator iter) {
this.iter = iter;
expectedModCount = modCount;
} // TreeIterator
public boolean hasNext() throws ConcurrentModificationException {
if (!(modCount == expectedModCount))
throw new ConcurrentModificationException();
return (iter.hasNext());
} // hasNext
public T next() throws NoSuchElementException {
if (hasNext())
return (iter.next());
else
throw new NoSuchElementException();
} // next
public void remove() {
throw new UnsupportedOperationException();
} // remove
} // class TreeIterator
} // class LinkedBinaryTree
// ***************************************************************
BinaryTreeADT.java
package jsjf;
import java.util.Iterator;
public interface BinaryTreeADT
{
public T getRootElement();
public boolean isEmpty();
public int size();
public boolean contains(T targetElement);
public T find(T targetElement);
public String toString();
public Iterator iterator();
public Iterator iteratorInOrder();
11. public Iterator iteratorPreOrder();
public Iterator iteratorPostOrder();
public Iterator iteratorLevelOrder();
}
BinaryTreeNode.java
package jsjf;
public class BinaryTreeNode
{
protected T element;
protected BinaryTreeNode left, right;
public BinaryTreeNode(T obj)
{
element = obj;
left = null;
right = null;
}
public BinaryTreeNode(T obj, LinkedBinaryTree left, LinkedBinaryTree right)
{
element = obj;
if (left == null)
this.left = null;
else
this.left = left.getRootNode();
if (right == null)
this.right = null;
else
this.right = right.getRootNode();
}
public int numChildren()
{
int children = 0;
if (left != null)
children = 1 + left.numChildren();
if (right != null)
12. children = children + 1 + right.numChildren();
return children;
}
public T getElement()
{
return element;
}
public BinaryTreeNode getRight()
{
return right;
}
public void setRight(BinaryTreeNode node)
{
right = node;
}
public BinaryTreeNode getLeft()
{
return left;
}
public void setLeft(BinaryTreeNode node)
{
left = node;
}
}
EmptyCollectionException.java
package jsjf.exceptions;
public class EmptyCollectionException extends RuntimeException
{
private static final long serialVersionUID = 1L;
public EmptyCollectionException (String collection)
{
13. super ("The " + collection + " is empty.");
}
}
ElementNotFoundException.java
package jsjf.exceptions;
public class ElementNotFoundException extends RuntimeException
{
private static final long serialVersionUID = 1L;
public ElementNotFoundException (String collection)
{
super ("The target element is not in this " + collection);
}
}
ArrayUnorderedList.java
package jsjf;
import jsjf.exceptions.*;
public class ArrayUnorderedList extends ArrayList
implements UnorderedListADT
{
public ArrayUnorderedList()
{
super();
}
public ArrayUnorderedList(int initialCapacity)
{
super(initialCapacity);
}
public void addToFront(T element)
{
if (size() == list.length)
expandCapacity();
// shift elements up one
for (int scan=rear; scan > 0; scan--)
list[scan] = list[scan-1];
14. list[0] = element;
rear++;
modCount++;
}
public void addToRear(T element)
{
if (size() == list.length)
expandCapacity();
list[rear] = element;
rear++;
modCount++;
}
public void addAfter(T element, T target)
{
if (size() == list.length)
expandCapacity();
int scan = 0;
// find the insertion point
while (scan < rear && !target.equals(list[scan]))
scan++;
if (scan == rear)
throw new ElementNotFoundException("UnorderedList");
scan++;
// shift elements up one
for (int shift=rear; shift > scan; shift--)
list[shift] = list[shift-1];
// insert element
list[scan] = element;
rear++;
modCount++;
}
}
15. UnorderedListADT.java
package jsjf;
public interface UnorderedListADT extends ListADT
{
public void addToFront(T element);
public void addToRear(T element);
public void addAfter(T element, T target);
}
ListADT.java
package jsjf;
import java.util.Iterator;
public interface ListADT extends Iterable
{
public T removeFirst();
public T removeLast();
public T remove(T element);
public T first();
public T last();
public boolean contains(T target);
public boolean isEmpty();
public int size();
public Iterator iterator();
public String toString();
}
ArrayList.java
package jsjf;
import jsjf.exceptions.*;
import java.util.*;
public abstract class ArrayList implements ListADT, Iterable
{
private final static int DEFAULT_CAPACITY = 100;
private final static int NOT_FOUND = -1;
protected int rear;
protected T[] list;
16. protected int modCount;
public ArrayList()
{
this(DEFAULT_CAPACITY);
}
// Added.
@SuppressWarnings("unchecked")
public ArrayList(int initialCapacity)
{
rear = 0;
list = (T[])(new Object[initialCapacity]);
modCount = 0;
}
protected void expandCapacity()
{
list = Arrays.copyOf(list, list.length*2);
}
public T removeLast() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("ArrayList");
T result;
rear--;
result = list[rear];
list[rear] = null;
modCount++;
return result;
}
public T removeFirst() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("ArrayList");
T result = list[0];
17. rear--;
/** shift the elements */
for (int scan=0; scan < rear; scan++)
list[scan] = list[scan+1];
list[rear] = null;
modCount++;
return result;
}
public T remove(T element)
{
T result;
int index = find(element);
if (index == NOT_FOUND)
throw new ElementNotFoundException("ArrayList");
result = list[index];
rear--;
// shift the appropriate elements
for (int scan=index; scan < rear; scan++)
list[scan] = list[scan+1];
list[rear] = null;
modCount++;
return result;
}
public T first() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("ArrayList");
return list[0];
}
public T last() throws EmptyCollectionException
{
18. if (isEmpty())
throw new EmptyCollectionException("ArrayList");
return list[rear-1];
}
public boolean contains(T target)
{
return (find(target) != NOT_FOUND);
}
private int find(T target)
{
int scan = 0;
int result = NOT_FOUND;
if (!isEmpty())
while (result == NOT_FOUND && scan < rear)
if (target.equals(list[scan]))
result = scan;
else
scan++;
return result;
}
public boolean isEmpty()
{
return (rear == 0);
}
public int size()
{
return rear;
}
public String toString()
{
String result = "";
for (int scan=0; scan < rear; scan++)
result = result + list[scan] + " ";
return result;
19. }
public Iterator iterator()
{
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator
{
int iteratorModCount;
int current;
public ArrayListIterator()
{
iteratorModCount = modCount;
current = 0;
}
public boolean hasNext() throws ConcurrentModificationException
{
if (iteratorModCount != modCount)
throw new ConcurrentModificationException();
return (current < rear);
}
public T next() throws ConcurrentModificationException
{
if (!hasNext())
throw new NoSuchElementException();
current++;
return list[current - 1];
}
public void remove() throws UnsupportedOperationException
21. int main()
{
int choice, num;
BST bst;
node *temp;
while (1)
{
cout<<"-----------------"<>choice;
switch(choice)
{
case 1:
temp = new node;
cout<<"Enter the number to be inserted : ";
cin>>temp->info;
bst.insert(root, temp);
case 2:
if (root == NULL)
{
cout<<"Tree is empty, nothing to delete"<>num;
bst.del(num);
break;
case 3:
cout<<"Inorder Traversal of BST:"<info)
{
*loc = root;
*par = NULL;
return;
}
if (item < root->info)
ptr = root->left;
else
ptr = root->right;
ptrsave = root;
while (ptr != NULL)
{
if (item == ptr->info)