For the code below complete the preOrder() method so that it performs a preOrder traversal of
the tree. For each node it traverses, it should call sb.append() to add a \"[\" the results of
traversing the subtree rooted at that node, and then a \"]\". You should add a space before the
results of the left and right child traversals, but only if the node exists.
code:
Solution
In preorder Nodes visited are in the order of
code:
package edu.buffalo.cse116;
import java.util.AbstractSet;
import java.util.Iterator;
public class BinarySearchTree> extends AbstractSet {
protected Entry root;
protected int size;
/**
* Initializes this BinarySearchTree object to be empty, to contain only
* elements of type E, to be ordered by the Comparable interface, and to
* contain no duplicate elements.
*/
public BinarySearchTree() {
root = null;
size = 0;
}
/**
* Initializes this BinarySearchTree object to contain a shallow copy of a
* specified BinarySearchTree object. The worstTime(n) is O(n), where n is the
* number of elements in the specified BinarySearchTree object.
*
* @param otherTree - the specified BinarySearchTree object that this
* BinarySearchTree object will be assigned a shallow copy of.
*/
public BinarySearchTree(BinarySearchTree otherTree) {
root = copy(otherTree.root, null);
size = otherTree.size;
}
/* Method to complete is here! */
public void preOrder(Entry ent, StringBuilder sb) {
preorder(root)
protected Entry copy(Entry p, Entry parent) {
if (p != null) {
Entry q = new Entry(p.element, parent);
q.left = copy(p.left, q);
q.right = copy(p.right, q);
return q;
}
return null;
} // method copy
@SuppressWarnings(\"unchecked\")
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BinarySearchTree)) {
return false;
}
return equals(root, ((BinarySearchTree) obj).root);
}
public boolean equals(Entry p, Entry q) {
if ((p == null) || (q == null)) {
return p == q;
}
if (!p.element.equals(q.element)) {
return false;
}
if (equals(p.left, q.left) && equals(p.right, q.right)) {
return true;
}
return false;
}
/**
* Returns the size of this BinarySearchTree object.
*
* @return the size of this BinarySearchTree object.
*/
@Override
public int size() {
return size;
}
/**
* Iterator method will be implemented for a future
*
* @return an iterator positioned at the smallest element in this
* BinarySearchTree object.
*/
@Override
public Iterator iterator() {
throw new UnsupportedOperationException(\"Not implemented yet!\");
}
/**
* Determines if there is at least one element in this BinarySearchTree object
* that equals a specified element. The worstTime(n) is O(n) and
* averageTime(n) is O(log n).
*
* @param obj - the element sought in this BinarySearchTree object.
* @return true - if there is an element in this BinarySearchTree object that
* equals obj; otherwise, return false.
* @throws ClassCastException - if obj cannot be compared to the elements in
* this BinarySearchTree object.
* @throws NullPointerException - if obj is null.
*/
@Override
public .
There is BinarySearchTree class. When removing a node from a BST, we.pdfDhanrajsolanki2091
There is BinarySearchTree class. When removing a node from a BST, we can replace it with
either its predecessor or its successor. Complete the predecessor() method
so that it returns the node that comes immediately before e. Hint: the work needed to find the
predecessor is a mirror image of what is required to find a node\'s
successor, so use successor() as a resource.
BinarySearchTree class:
Solution
import java.util.AbstractSet;
import java.util.Iterator;
public class BinarySearchTree> extends AbstractSet {
protected BTNode root;
protected int size;
/**
* Initializes this BinarySearchTree object to be empty, to contain only
* elements of type E, to be ordered by the Comparable interface, and to
* contain no duplicate elements.
*/
public BinarySearchTree() {
root = null;
size = 0;
}
/**
* Initializes this BinarySearchTree object to contain a shallow copy of a
* specified BinarySearchTree object. The worstTime(n) is O(n), where n is the
* number of elements in the specified BinarySearchTree object.
*
* @param otherTree - the specified BinarySearchTree object that this
* BinarySearchTree object will be assigned a shallow copy of.
*/
public BinarySearchTree(BinarySearchTree otherTree) {
root = copy(otherTree.root, null);
size = otherTree.size;
}
protected BTNode copy(BTNode p, BTNode parent) {
if (p != null) {
BTNode q = new BTNode(p.element, parent);
q.left = copy(p.left, q);
q.right = copy(p.right, q);
return q;
}
return null;
} // method copy
/**
* Finds the predecessor of a specified BTNode object in this BinarySearchTree. The
worstTime(n) is O(n) and
* averageTime(n) is constant.
*
* @param e - the BTNode object whose successor is to be found.
* @return the successor of e, if e has a successor; otherwise, return null.
*/
protected BTNode predecessor(BTNode e) {
if (e == null) {
return null;
} else if (e.left != null) {
// successor is leftmost BTNode in right subtree of e
BTNode p = e.left;
while (p.right != null) {
p = p.right;
}
return p;
} // e has a right child
else {
// go up the tree to the right as far as possible, then go up
// to the left.
BTNode p = e.parent;
BTNode ch = e;
while ((p != null) && (ch == p.left)) {
ch = p;
p = p.parent;
} // while
return p;
} // e has no left child
// method successor
}
@SuppressWarnings(\"unchecked\")
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BinarySearchTree)) {
return false;
}
return equals(root, ((BinarySearchTree) obj).root);
} // method 1-parameter equals
public boolean equals(BTNode p, BTNode q) {
if ((p == null) || (q == null)) {
return p == q;
}
if (!p.element.equals(q.element)) {
return false;
}
if (equals(p.left, q.left) && equals(p.right, q.right)) {
return true;
}
return false;
}
/**
* Returns the size of this BinarySearchTree object.
*
* @return the size of this BinarySearchTree object.
*/
@Override
public int size() {
return size;
}
/**
* Iterator method will be implemented for a future
*
* @return an iterator positioned at the smallest element in this
* Bina.
The LinkedList1 class implements a Linked list. class.pdfmalavshah9013
/**
The LinkedList1 class implements a Linked list.
*/
class LinkedList1
{
/**
The Node class stores a list element
and a reference to the next node.
*/
private class Node
{
String value;
Node next;
/**
Constructor.
@param val The element to store in the node.
@param n The reference to the successor node.
*/
Node(String val, Node n)
{
value = val;
next = n;
}
/**
Constructor.
@param val The element to store in the node.
*/
Node(String val)
{
// Call the other (sister) constructor.
this(val, null);
}
}
private Node first; // list head
private Node last; // last element in list
/**
Constructor.
*/
public LinkedList1()
{
first = null;
last = null;
}
/**
The isEmpty method checks to see
if the list is empty.
@return true if list is empty,
false otherwise.
*/
public boolean isEmpty()
{
return first == null;
}
/**
The size method returns the length of the list.
@return The number of elements in the list.
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
/**
The add method adds an element to
the end of the list.
@param e The value to add to the
end of the list.
*/
public void add(String e)
{
if (isEmpty())
{
first = new Node(e);
last = first;
}
else
{
// Add to end of existing list
last.next = new Node(e);
last = last.next;
}
}
/**
The add method adds an element at a position.
@param e The element to add to the list.
@param index The position at which to add
the element.
@exception IndexOutOfBoundsException When
index is out of bounds.
*/
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
first = new Node(e, first);
if (last == null)
last = first;
return;
}
// Set a reference pred to point to the node that
// will be the predecessor of the new node
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
// Splice in a node containing the new element
pred.next = new Node(e, pred.next);
// Is there a new last element ?
if (pred.next.next == null)
last = pred.next;
}
/**
The toString method computes the string
representation of the list.
@return The string form of the list.
*/
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + \"\ \");
p = p.next;
}
return strBuilder.toString();
}
/**
The remove method removes the element at an index.
@param index The index of the element to remove.
@return The element removed.
@exception IndexOutOfBoundsException When index is
out of bounds.
*/
public String remove(int index)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
String element; // The element to return
if (index == 0)
{
// Removal of first item in the list
element.
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfarrowmobile
Here is the editable code:
Solution
import java.util.NoSuchElementException;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public void addFirst(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
/**
* adds element at the end of the linked list
* @param element
*/
public void addLast(E element) {
Node tmp = new Node(element, null, tail);
if(tail != null) {tail.next = tmp;}
tail = tmp;
if(head == null) { head = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
public void iterateForward(){
System.out.println(\"iterating forward..\");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}
/**
* this method walks backward through the linked list
*/
public void iterateBackward(){
System.out.println(\"iterating backword..\");
Node tmp = tail;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.prev;
}
}
public E removeFirst() {
if (size == 0) throw new NoSuchElementException();
Node tmp = head;
head = head.next;
head.prev = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
public E removeLast() {
if (size == 0) throw new NoSuchElementException();
Node tmp = tail;
tail = tail.prev;
tail.next = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
public static void main(String a[]){
DoublyLinkedListImpl dll = new DoublyLinkedListImpl();
dll.addFirst(10);
dll.addFirst(34);
dll.addLast(56);
dll.addLast(364);
dll.iterateForward();
dll.removeFirst();
dll.removeLast();
dll.iterateBackward();
}
}
import java.util.Scanner;
/* Class Node */
class Node
{
protected int data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = 0;
}
/* Constructor */
public Node(int d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n)
{
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p)
{
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext()
{
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev()
{
return prev;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}
/* Class linkedList */
class linkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public linkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isE.
Java Foundations StackADT-java --- - Defines the interface to a stack.docxVictorXUQGloverl
Java Foundations
StackADT.java
/**
* Defines the interface to a stack collection.
*
* @author Java Foundations
* @version 4.0
*/
public interface StackADT<T> {
/**
* Adds the specified element to the top of this stack.
*
* @param element element to be pushed onto the stack
*/
public void push(T element);
/**
* Removes and returns the top element from this stack.
*
* @return the element removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T pop();
/**
* Returns the top element of this stack without removing it from the stack.
*
* @return the element on top of the stack. It is not removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if the stack is empty, false if the stack is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size();
}
QueueADT.java
/**
* QueueADT defines the interface to a queue collection.
*
* @author Java Foundation
* @version 4.0
*/
public interface QueueADT<T> {
/**
* Adds one element to the rear of this queue.
*
* @param element the element to be added to the rear of the queue
*/
public void enqueue(T element);
/**
* Removes and returns the element at the front of this queue.
*
* @return the element at the front of the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T dequeue();
/**
* Returns without removing the element at the front of this queue.
*
* @return the first element in the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T first();
/**
* Returns true if this queue contains no elements.
*
* @return true if the queue is empty, false if the queue is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this queue.
*
* @return the number of elements in the queue
*/
public int size();
}
LinkedDeque.java
public class LinkedDeque<T> implements QueueADT<T>, StackADT<T>, DequeADT<T> {
// inner class for a double linked list node
private class DNode<T> {
private T element;
private DNode<T> prev, next;
}
// data fields for the LinkedDeque class
private DNode<T> front, rear;
private int size;
// deque interface methods
@Override
public void addFirst(T element) {
// create a new node and set it up
DNode<T> newNode = new DNode<T>();
newNode.element = element; // from param to new node obj
newNode.prev = newNode.next = null;
if(this.isEmpty()) {
// we are making the only node in the deque
this.rear = this.front = newNode;
} else {
// there already exists a new node
// so, put the new node before the front node
newNode.next = this.front;
this.front.prev = newNode;
this.front = newNode;
}
this.size++;
}
@Override
public T removeFirst() {
T grabbedElt = this.getFirst(); // checks for empty for us
if.
import java.util.Iterator; import java.util.NoSuchElementException; /** * An implementation
of MyList with a linked list (a longer exercise would be to * implement the List interface as is
done in the class java.util.LinkedList: * the source of the LinkedList class is available from Sun.
Check it out). */ public class MyLinkedList implements MyList { // A private class to
represent a Node in the linked list private class Node { public E item;
public Node next; // a convenient constructor public Node(E o) {
this.item = o; this.next = null; } } // The start of the linked
list private Node head; // The last Node in the linked list private Node tail;
// Number of elements in the list private int size; /** * Creates an empty list (this
constructor is not necessary) */ public MyLinkedList() { } /** *
Returns the number of elements in this list. */ public int size() { return size;
} /** * Returns true if this list contains no elements. */ public boolean
isEmpty() { return size == 0; } /** * Appends the specified element to
the end of this list */ public boolean add(E o) { Node n = new Node(o);
// If this is the first element in the list if (head == null) { head = n;
} else { // If the list is not empty, use tail tail.next = n;
} // update tail tail = n; // update size size++;
return true; } /** * Empties this List */ public void clear() {
// update head, tail and size head = tail = null; size = 0; } /**
* Returns the element at the specified position in this list. */ public E get(int index) {
if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find it
Node n = head; for (int i = 0; i < index; i++) { n = n.next; }
return n.item; } /** * Returns the index of the specified element (-1 if
there is no match) */ public int indexOf(Object o) { // If o is null
int index = 0; Node p = head; if (o == null) // look for a null element in the
list { while (p != null) { if (p.item == null) {
return index; } index++;
p = p.next; } } else // o is an object (use equals) {
while (p != null) { if (o.equals(p.item)) { return
index; } index++; p = p.next;
} } // if we get here, o is not in the list return -1; }
/** * Returns true if this list contains the specified element. */ public boolean
contains(Object o) { // easy with indexOf return indexOf(o) != -1; }
/** * Removes the element in the List at position index */ public boolean
remove(int index) { if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find the
corresponding node Node prev = null, p = head; for (int i = 0; i < index; i++)
{ prev = p; p = p.next; } // Remove it
// Special case for the first node if (p == head) { head = head.next;
} else { prev.next = p.next; } // If the last node has been
removed, update tail if (p == tail) { tail = prev; } //
update size size--; return true; } /** * Removes the element
in the List at position index */ public boolean remove(Object o) { // easy
with indexOf and remove int index = i.
Note- Can someone help me with the private E get(int index- int curren (1).docxVictorzH8Bondx
Note: Can someone help me with the private E get(int index, int currentIndex, Node n)method. The code is not running. Also I need help with the public void add(int index, E element) method too. Please use the parameters provided with the code to solve. package edu.ust.cisc; import java.util.Iterator; import java.util.NoSuchElementException; public class CiscSortedLinkedList > implements CiscList { /** * A reference to this list's dummy node. Its next reference should refer to the node containing the first element * in this list, or it should refer to itself if the list is empty. The next reference within the node containing * the last element in this list should refer to dummy, thus creating a cyclic list. */ private Node dummy; /** * Number of elements in the list. */ private int size; /** * Constructs an empty CiscSortedLinkedList instance with a non-null dummy node whose next reference refers to * itself. */ public CiscSortedLinkedList() { dummy = new Node<>(null, null); dummy.next = dummy; } /** * Returns the number of elements in this list. * * @return the number of elements in this list */ @Override public int size() { return size; } /** * Returns {@code true} if this list contains no elements. * * @return {@code true} if this list contains no elements */ @Override public boolean isEmpty() { return size==0; } /** * Returns {@code true} if this list contains the specified element (compared using the {@code equals} method). * This implementation should stop searching as soon as it is able to determine that the specified element is not * present. * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element * @throws NullPointerException if the specified element is null */ @Override public boolean contains(Object o) { if(o==null){ throw new NullPointerException(); } return containsHelper(o,dummy.next); } private boolean containsHelper(Object o, Node node){ if(node== dummy){ return false; } else if(o.equals(node.data)){ return true; } else{ return containsHelper(o,node.next); } } /** * Returns an iterator over the elements in this list in proper sequence. * * @return an iterator over the elements in this list in proper sequence */ @Override public Iterator iterator() { //return new Iterator (){ //private Node curr = dummy.next; //private Node prev = dummy; //private boolean canRemove = false; return null; } /** * Returns an array containing all of the elements in this list in proper sequence (from first to last element). *
The returned array will be "safe" in that no references to it are maintained by this list. (In other words, * this method must allocate a new array even if this list is backed by an array). The caller is thus free to modify * the returned array. * * @return an array containing all of the elements in this list in proper sequence */ @Override public Object[] toArray() { Object[] arr = new Object[size]; int i = 0; for(Node current = dummy;current!=null;cur.
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 == .
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdframbagra74
5. Design and implement a method contains 2 for BinarySearchTree, functionall equivalent to
the contains method, that does not use recursion.
show the driver code and do this in java
this is the binarysearchtree
import java.util.*; // Iterator, Comparator
public class BinarySearchTree implements BSTInterface
{
protected BSTNode root; // reference to the root of this BST
protected Comparator comp; // used for all comparisons
protected boolean found; // used by remove
public BinarySearchTree()
// Precondition: T implements Comparable
// Creates an empty BST object - uses the natural order of elements.
{
root = null;
comp = new Comparator()
{
public int compare(T element1, T element2)
{
return ((Comparable)element1).compareTo(element2);
}
};
}
public BinarySearchTree(Comparator comp)
// Creates an empty BST object - uses Comparator comp for order
// of elements.
{
root = null;
this.comp = comp;
}
public boolean isFull()
// Returns false; this link-based BST is never full.
{
return false;
}
public boolean isEmpty()
// Returns true if this BST is empty; otherwise, returns false.
{
return (root == null);
}
public T min()
// If this BST is empty, returns null;
// otherwise returns the smallest element of the tree.
{
if (isEmpty())
return null;
else
{
BSTNode node = root;
while (node.getLeft() != null)
node = node.getLeft();
return node.getInfo();
}
}
public T max()
// If this BST is empty, returns null;
// otherwise returns the largest element of the tree.
{
if (isEmpty())
return null;
else
{
BSTNode node = root;
while (node.getRight() != null)
node = node.getRight();
return node.getInfo();
}
}
private int recSize(BSTNode node)
// Returns the number of elements in subtree rooted at node.
{
if (node == null)
return 0;
else
return 1 + recSize(node.getLeft()) + recSize(node.getRight());
}
public int size()
// Returns the number of elements in this BST.
{
return recSize(root);
}
public int size2()
// Returns the number of elements in this BST.
{
int count = 0;
if (root != null)
{
LinkedStack> nodeStack = new LinkedStack>();
BSTNode currNode;
nodeStack.push(root);
while (!nodeStack.isEmpty())
{
currNode = nodeStack.top();
nodeStack.pop();
count++;
if (currNode.getLeft() != null)
nodeStack.push(currNode.getLeft());
if (currNode.getRight() != null)
nodeStack.push(currNode.getRight());
}
}
return count;
}
private boolean recContains(T target, BSTNode node)
// Returns true if the subtree rooted at node contains info i such that
// comp.compare(target, i) == 0; otherwise, returns false.
{
if (node == null)
return false; // target is not found
else if (comp.compare(target, node.getInfo()) < 0)
return recContains(target, node.getLeft()); // Search left subtree
else if (comp.compare(target, node.getInfo()) > 0)
return recContains(target, node.getRight()); // Search right subtree
else
return true; // target is found
}
public boolean contains (T target)
// Returns true if this BST contains a node with info i such that
// comp.compare(target, i) == 0; otherwise, re.
There is BinarySearchTree class. When removing a node from a BST, we.pdfDhanrajsolanki2091
There is BinarySearchTree class. When removing a node from a BST, we can replace it with
either its predecessor or its successor. Complete the predecessor() method
so that it returns the node that comes immediately before e. Hint: the work needed to find the
predecessor is a mirror image of what is required to find a node\'s
successor, so use successor() as a resource.
BinarySearchTree class:
Solution
import java.util.AbstractSet;
import java.util.Iterator;
public class BinarySearchTree> extends AbstractSet {
protected BTNode root;
protected int size;
/**
* Initializes this BinarySearchTree object to be empty, to contain only
* elements of type E, to be ordered by the Comparable interface, and to
* contain no duplicate elements.
*/
public BinarySearchTree() {
root = null;
size = 0;
}
/**
* Initializes this BinarySearchTree object to contain a shallow copy of a
* specified BinarySearchTree object. The worstTime(n) is O(n), where n is the
* number of elements in the specified BinarySearchTree object.
*
* @param otherTree - the specified BinarySearchTree object that this
* BinarySearchTree object will be assigned a shallow copy of.
*/
public BinarySearchTree(BinarySearchTree otherTree) {
root = copy(otherTree.root, null);
size = otherTree.size;
}
protected BTNode copy(BTNode p, BTNode parent) {
if (p != null) {
BTNode q = new BTNode(p.element, parent);
q.left = copy(p.left, q);
q.right = copy(p.right, q);
return q;
}
return null;
} // method copy
/**
* Finds the predecessor of a specified BTNode object in this BinarySearchTree. The
worstTime(n) is O(n) and
* averageTime(n) is constant.
*
* @param e - the BTNode object whose successor is to be found.
* @return the successor of e, if e has a successor; otherwise, return null.
*/
protected BTNode predecessor(BTNode e) {
if (e == null) {
return null;
} else if (e.left != null) {
// successor is leftmost BTNode in right subtree of e
BTNode p = e.left;
while (p.right != null) {
p = p.right;
}
return p;
} // e has a right child
else {
// go up the tree to the right as far as possible, then go up
// to the left.
BTNode p = e.parent;
BTNode ch = e;
while ((p != null) && (ch == p.left)) {
ch = p;
p = p.parent;
} // while
return p;
} // e has no left child
// method successor
}
@SuppressWarnings(\"unchecked\")
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BinarySearchTree)) {
return false;
}
return equals(root, ((BinarySearchTree) obj).root);
} // method 1-parameter equals
public boolean equals(BTNode p, BTNode q) {
if ((p == null) || (q == null)) {
return p == q;
}
if (!p.element.equals(q.element)) {
return false;
}
if (equals(p.left, q.left) && equals(p.right, q.right)) {
return true;
}
return false;
}
/**
* Returns the size of this BinarySearchTree object.
*
* @return the size of this BinarySearchTree object.
*/
@Override
public int size() {
return size;
}
/**
* Iterator method will be implemented for a future
*
* @return an iterator positioned at the smallest element in this
* Bina.
The LinkedList1 class implements a Linked list. class.pdfmalavshah9013
/**
The LinkedList1 class implements a Linked list.
*/
class LinkedList1
{
/**
The Node class stores a list element
and a reference to the next node.
*/
private class Node
{
String value;
Node next;
/**
Constructor.
@param val The element to store in the node.
@param n The reference to the successor node.
*/
Node(String val, Node n)
{
value = val;
next = n;
}
/**
Constructor.
@param val The element to store in the node.
*/
Node(String val)
{
// Call the other (sister) constructor.
this(val, null);
}
}
private Node first; // list head
private Node last; // last element in list
/**
Constructor.
*/
public LinkedList1()
{
first = null;
last = null;
}
/**
The isEmpty method checks to see
if the list is empty.
@return true if list is empty,
false otherwise.
*/
public boolean isEmpty()
{
return first == null;
}
/**
The size method returns the length of the list.
@return The number of elements in the list.
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
/**
The add method adds an element to
the end of the list.
@param e The value to add to the
end of the list.
*/
public void add(String e)
{
if (isEmpty())
{
first = new Node(e);
last = first;
}
else
{
// Add to end of existing list
last.next = new Node(e);
last = last.next;
}
}
/**
The add method adds an element at a position.
@param e The element to add to the list.
@param index The position at which to add
the element.
@exception IndexOutOfBoundsException When
index is out of bounds.
*/
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
first = new Node(e, first);
if (last == null)
last = first;
return;
}
// Set a reference pred to point to the node that
// will be the predecessor of the new node
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
// Splice in a node containing the new element
pred.next = new Node(e, pred.next);
// Is there a new last element ?
if (pred.next.next == null)
last = pred.next;
}
/**
The toString method computes the string
representation of the list.
@return The string form of the list.
*/
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + \"\ \");
p = p.next;
}
return strBuilder.toString();
}
/**
The remove method removes the element at an index.
@param index The index of the element to remove.
@return The element removed.
@exception IndexOutOfBoundsException When index is
out of bounds.
*/
public String remove(int index)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
String element; // The element to return
if (index == 0)
{
// Removal of first item in the list
element.
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfarrowmobile
Here is the editable code:
Solution
import java.util.NoSuchElementException;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public void addFirst(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
/**
* adds element at the end of the linked list
* @param element
*/
public void addLast(E element) {
Node tmp = new Node(element, null, tail);
if(tail != null) {tail.next = tmp;}
tail = tmp;
if(head == null) { head = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
public void iterateForward(){
System.out.println(\"iterating forward..\");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}
/**
* this method walks backward through the linked list
*/
public void iterateBackward(){
System.out.println(\"iterating backword..\");
Node tmp = tail;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.prev;
}
}
public E removeFirst() {
if (size == 0) throw new NoSuchElementException();
Node tmp = head;
head = head.next;
head.prev = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
public E removeLast() {
if (size == 0) throw new NoSuchElementException();
Node tmp = tail;
tail = tail.prev;
tail.next = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
public static void main(String a[]){
DoublyLinkedListImpl dll = new DoublyLinkedListImpl();
dll.addFirst(10);
dll.addFirst(34);
dll.addLast(56);
dll.addLast(364);
dll.iterateForward();
dll.removeFirst();
dll.removeLast();
dll.iterateBackward();
}
}
import java.util.Scanner;
/* Class Node */
class Node
{
protected int data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = 0;
}
/* Constructor */
public Node(int d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n)
{
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p)
{
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext()
{
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev()
{
return prev;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}
/* Class linkedList */
class linkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public linkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isE.
Java Foundations StackADT-java --- - Defines the interface to a stack.docxVictorXUQGloverl
Java Foundations
StackADT.java
/**
* Defines the interface to a stack collection.
*
* @author Java Foundations
* @version 4.0
*/
public interface StackADT<T> {
/**
* Adds the specified element to the top of this stack.
*
* @param element element to be pushed onto the stack
*/
public void push(T element);
/**
* Removes and returns the top element from this stack.
*
* @return the element removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T pop();
/**
* Returns the top element of this stack without removing it from the stack.
*
* @return the element on top of the stack. It is not removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if the stack is empty, false if the stack is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size();
}
QueueADT.java
/**
* QueueADT defines the interface to a queue collection.
*
* @author Java Foundation
* @version 4.0
*/
public interface QueueADT<T> {
/**
* Adds one element to the rear of this queue.
*
* @param element the element to be added to the rear of the queue
*/
public void enqueue(T element);
/**
* Removes and returns the element at the front of this queue.
*
* @return the element at the front of the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T dequeue();
/**
* Returns without removing the element at the front of this queue.
*
* @return the first element in the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T first();
/**
* Returns true if this queue contains no elements.
*
* @return true if the queue is empty, false if the queue is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this queue.
*
* @return the number of elements in the queue
*/
public int size();
}
LinkedDeque.java
public class LinkedDeque<T> implements QueueADT<T>, StackADT<T>, DequeADT<T> {
// inner class for a double linked list node
private class DNode<T> {
private T element;
private DNode<T> prev, next;
}
// data fields for the LinkedDeque class
private DNode<T> front, rear;
private int size;
// deque interface methods
@Override
public void addFirst(T element) {
// create a new node and set it up
DNode<T> newNode = new DNode<T>();
newNode.element = element; // from param to new node obj
newNode.prev = newNode.next = null;
if(this.isEmpty()) {
// we are making the only node in the deque
this.rear = this.front = newNode;
} else {
// there already exists a new node
// so, put the new node before the front node
newNode.next = this.front;
this.front.prev = newNode;
this.front = newNode;
}
this.size++;
}
@Override
public T removeFirst() {
T grabbedElt = this.getFirst(); // checks for empty for us
if.
import java.util.Iterator; import java.util.NoSuchElementException; /** * An implementation
of MyList with a linked list (a longer exercise would be to * implement the List interface as is
done in the class java.util.LinkedList: * the source of the LinkedList class is available from Sun.
Check it out). */ public class MyLinkedList implements MyList { // A private class to
represent a Node in the linked list private class Node { public E item;
public Node next; // a convenient constructor public Node(E o) {
this.item = o; this.next = null; } } // The start of the linked
list private Node head; // The last Node in the linked list private Node tail;
// Number of elements in the list private int size; /** * Creates an empty list (this
constructor is not necessary) */ public MyLinkedList() { } /** *
Returns the number of elements in this list. */ public int size() { return size;
} /** * Returns true if this list contains no elements. */ public boolean
isEmpty() { return size == 0; } /** * Appends the specified element to
the end of this list */ public boolean add(E o) { Node n = new Node(o);
// If this is the first element in the list if (head == null) { head = n;
} else { // If the list is not empty, use tail tail.next = n;
} // update tail tail = n; // update size size++;
return true; } /** * Empties this List */ public void clear() {
// update head, tail and size head = tail = null; size = 0; } /**
* Returns the element at the specified position in this list. */ public E get(int index) {
if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find it
Node n = head; for (int i = 0; i < index; i++) { n = n.next; }
return n.item; } /** * Returns the index of the specified element (-1 if
there is no match) */ public int indexOf(Object o) { // If o is null
int index = 0; Node p = head; if (o == null) // look for a null element in the
list { while (p != null) { if (p.item == null) {
return index; } index++;
p = p.next; } } else // o is an object (use equals) {
while (p != null) { if (o.equals(p.item)) { return
index; } index++; p = p.next;
} } // if we get here, o is not in the list return -1; }
/** * Returns true if this list contains the specified element. */ public boolean
contains(Object o) { // easy with indexOf return indexOf(o) != -1; }
/** * Removes the element in the List at position index */ public boolean
remove(int index) { if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find the
corresponding node Node prev = null, p = head; for (int i = 0; i < index; i++)
{ prev = p; p = p.next; } // Remove it
// Special case for the first node if (p == head) { head = head.next;
} else { prev.next = p.next; } // If the last node has been
removed, update tail if (p == tail) { tail = prev; } //
update size size--; return true; } /** * Removes the element
in the List at position index */ public boolean remove(Object o) { // easy
with indexOf and remove int index = i.
Note- Can someone help me with the private E get(int index- int curren (1).docxVictorzH8Bondx
Note: Can someone help me with the private E get(int index, int currentIndex, Node n)method. The code is not running. Also I need help with the public void add(int index, E element) method too. Please use the parameters provided with the code to solve. package edu.ust.cisc; import java.util.Iterator; import java.util.NoSuchElementException; public class CiscSortedLinkedList > implements CiscList { /** * A reference to this list's dummy node. Its next reference should refer to the node containing the first element * in this list, or it should refer to itself if the list is empty. The next reference within the node containing * the last element in this list should refer to dummy, thus creating a cyclic list. */ private Node dummy; /** * Number of elements in the list. */ private int size; /** * Constructs an empty CiscSortedLinkedList instance with a non-null dummy node whose next reference refers to * itself. */ public CiscSortedLinkedList() { dummy = new Node<>(null, null); dummy.next = dummy; } /** * Returns the number of elements in this list. * * @return the number of elements in this list */ @Override public int size() { return size; } /** * Returns {@code true} if this list contains no elements. * * @return {@code true} if this list contains no elements */ @Override public boolean isEmpty() { return size==0; } /** * Returns {@code true} if this list contains the specified element (compared using the {@code equals} method). * This implementation should stop searching as soon as it is able to determine that the specified element is not * present. * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element * @throws NullPointerException if the specified element is null */ @Override public boolean contains(Object o) { if(o==null){ throw new NullPointerException(); } return containsHelper(o,dummy.next); } private boolean containsHelper(Object o, Node node){ if(node== dummy){ return false; } else if(o.equals(node.data)){ return true; } else{ return containsHelper(o,node.next); } } /** * Returns an iterator over the elements in this list in proper sequence. * * @return an iterator over the elements in this list in proper sequence */ @Override public Iterator iterator() { //return new Iterator (){ //private Node curr = dummy.next; //private Node prev = dummy; //private boolean canRemove = false; return null; } /** * Returns an array containing all of the elements in this list in proper sequence (from first to last element). *
The returned array will be "safe" in that no references to it are maintained by this list. (In other words, * this method must allocate a new array even if this list is backed by an array). The caller is thus free to modify * the returned array. * * @return an array containing all of the elements in this list in proper sequence */ @Override public Object[] toArray() { Object[] arr = new Object[size]; int i = 0; for(Node current = dummy;current!=null;cur.
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 == .
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdframbagra74
5. Design and implement a method contains 2 for BinarySearchTree, functionall equivalent to
the contains method, that does not use recursion.
show the driver code and do this in java
this is the binarysearchtree
import java.util.*; // Iterator, Comparator
public class BinarySearchTree implements BSTInterface
{
protected BSTNode root; // reference to the root of this BST
protected Comparator comp; // used for all comparisons
protected boolean found; // used by remove
public BinarySearchTree()
// Precondition: T implements Comparable
// Creates an empty BST object - uses the natural order of elements.
{
root = null;
comp = new Comparator()
{
public int compare(T element1, T element2)
{
return ((Comparable)element1).compareTo(element2);
}
};
}
public BinarySearchTree(Comparator comp)
// Creates an empty BST object - uses Comparator comp for order
// of elements.
{
root = null;
this.comp = comp;
}
public boolean isFull()
// Returns false; this link-based BST is never full.
{
return false;
}
public boolean isEmpty()
// Returns true if this BST is empty; otherwise, returns false.
{
return (root == null);
}
public T min()
// If this BST is empty, returns null;
// otherwise returns the smallest element of the tree.
{
if (isEmpty())
return null;
else
{
BSTNode node = root;
while (node.getLeft() != null)
node = node.getLeft();
return node.getInfo();
}
}
public T max()
// If this BST is empty, returns null;
// otherwise returns the largest element of the tree.
{
if (isEmpty())
return null;
else
{
BSTNode node = root;
while (node.getRight() != null)
node = node.getRight();
return node.getInfo();
}
}
private int recSize(BSTNode node)
// Returns the number of elements in subtree rooted at node.
{
if (node == null)
return 0;
else
return 1 + recSize(node.getLeft()) + recSize(node.getRight());
}
public int size()
// Returns the number of elements in this BST.
{
return recSize(root);
}
public int size2()
// Returns the number of elements in this BST.
{
int count = 0;
if (root != null)
{
LinkedStack> nodeStack = new LinkedStack>();
BSTNode currNode;
nodeStack.push(root);
while (!nodeStack.isEmpty())
{
currNode = nodeStack.top();
nodeStack.pop();
count++;
if (currNode.getLeft() != null)
nodeStack.push(currNode.getLeft());
if (currNode.getRight() != null)
nodeStack.push(currNode.getRight());
}
}
return count;
}
private boolean recContains(T target, BSTNode node)
// Returns true if the subtree rooted at node contains info i such that
// comp.compare(target, i) == 0; otherwise, returns false.
{
if (node == null)
return false; // target is not found
else if (comp.compare(target, node.getInfo()) < 0)
return recContains(target, node.getLeft()); // Search left subtree
else if (comp.compare(target, node.getInfo()) > 0)
return recContains(target, node.getRight()); // Search right subtree
else
return true; // target is found
}
public boolean contains (T target)
// Returns true if this BST contains a node with info i such that
// comp.compare(target, i) == 0; otherwise, re.
Note- Can someone help me with the Public boolean add(E value) method.pdfStewart29UReesa
Note: Can someone help me with the Public boolean add(E value) method and Private void
add(E value,Node n) method. I have everything but it is not working. Also need help with the
remove methods. Both public and private methods for remove. package edu.ust.cisc; import
java.util.Iterator; import java.util.NoSuchElementException; public class CiscSortedLinkedList
> implements CiscList { /** * A reference to this list's dummy node. Its next reference should
refer to the node containing the first element * in this list, or it should refer to itself if the list is
empty. The next reference within the node containing * the last element in this list should refer to
dummy, thus creating a cyclic list. */ private Node dummy; /** * Number of elements in the list.
*/ private int size; /** * Constructs an empty CiscSortedLinkedList instance with a non-null
dummy node whose next reference refers to * itself. */ public CiscSortedLinkedList() { dummy
= new Node<>(null, null); dummy.next = dummy; } /** * Returns the number of elements in
this list. * * @return the number of elements in this list */ @Override public int size() { return
size; } /** * Returns {@code true} if this list contains no elements. * * @return {@code true} if
this list contains no elements */ @Override public boolean isEmpty() { return size==0; } /** *
Returns {@code true} if this list contains the specified element (compared using the {@code
equals} method). * This implementation should stop searching as soon as it is able to determine
that the specified element is not * present. * @param o element whose presence in this list is to
be tested * @return {@code true} if this list contains the specified element * @throws
NullPointerException if the specified element is null */ @Override public boolean
contains(Object o) { if(o==null){ throw new NullPointerException(); } return
containsHelper(o,dummy.next); } private boolean containsHelper(Object o, Node node){
if(node== dummy){ return false; } else if(o.equals(node.data)){ return true; } else{ return
containsHelper(o,node.next); } } /** * Returns an iterator over the elements in this list in proper
sequence. * * @return an iterator over the elements in this list in proper sequence */ @Override
public Iterator iterator() { //return new Iterator (){ //private Node curr = dummy.next; //private
Node prev = dummy; //private boolean canRemove = false; return new CiscLinkedListIterator();
} /** * Returns an array containing all of the elements in this list in proper sequence (from first
to last element). * *
The returned array will be "safe" in that no references to it are maintained by this list. (In other
words, * this method must allocate a new array even if this list is backed by an array). The caller
is thus free to modify * the returned array. * * @return an array containing all of the elements in
this list in proper sequence */ @Override public Object[] toArray() { Object[] arr = new
Object[size]; int i = 0; for(Node current = dummy;curren.
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxGavinUJtMathist
JAVA
Demonstrate the use of your APL in a PartB_Driver class by doing the following. Create a static method called removeConsecutiveDuplicates that removes any consecutive duplicate strings from an array positional list of Strings and returns the number of strings left after the removal. After calling the method, the positional list parameter should contain the same sequence of strings as before but with any consecutive duplicates removed. Illustrate your method using the following sets of strings and display the content of the list after executing the method.
NOTE: You MUST use a combination/variation of ALL the add and set methods (AddFirst, AddLast, AddBefore, AddAfter, and set) in creating one of the following original lists.
- harry ron tom tom tom hermione
- harry harry tom ron mary harry
- tom ron harry hermione mary
- mary mary tom james hermione hermione james harry harry harry
You MUST NOT use any other auxiliary data structure e.g., arrays in your implementation ofremoveConsecutiveDuplicates.
Sample Output (for last set of Strings)
Original positional list:
[0] mary [1] mary [2] tom [3] james [4] hermione [5] hermione [6] james [7] harry [8] harry [9] harry
APL.java
public class ArrayPositionalList<E> implements PositionalList<E> {
private static class ArrPos<E> implements Position<E> {
private int index;
private E element;
public ArrPos(E e, int i) {
index = i;
element = e;
}
public E getElement() throws IllegalStateException {
if (index == -1) {
throw new IllegalStateException("Position no longer valid");
}
return element;
}
public void setElement(E e) {
element = e;
}
public int getIndex() {
return index;
}
public void setIndex(int i) {
index = i;
}
}
public static final int CAPACITY = 16;
private ArrPos<E>[] data;
private int size = 0;
public ArrayPositionalList() {
this(CAPACITY);
}
public ArrayPositionalList(int capacity) {
data = (ArrPos<E>[]) new ArrPos[capacity];
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public Position first() {
if (!isEmpty())
return data[0];
return null;
}
@Override
public Position last() {
if (!isEmpty())
return data[size - 1];
return null;
}
@Override
public Position before(Position p) throws IllegalArgumentException {
if (p.getIndex() > 0 && p.getIndex() < size) {
return data[p.getIndex() - 1];
}
if (p.getIndex() == 0)
return null;
throw new IllegalArgumentException();
}
@Override
public Position after(Position p) throws IllegalArgumentException {
if (p.getIndex() >= 0 && p.getIndex() < size - 1) {
return data[p.getIndex() + 1];
}
if (p.getIndex() == size - 1)
return null;
throw new IllegalArgumentException();
}
@Override
public Position addFirst(E e) {
if (size < data.length) {
for (int i = size - 1; i >= 0; i--) {
data[i + 1] = data[i];
data[i + 1].setIndex(data[i + 1].getIndex() + 1);
}
data[0] = new ArrPos<E>(e, 0);
size++;
return data[0];
}
return null;
}
@Override
public Position addLast(E e) {
if (size < data.length) {
da.
4. The size of instructions can be fixed or variable. What are advant.pdfmumnesh
4. The size of instructions can be fixed or variable. What are advantage and disadvantage of
fixed compared to variable? point) eft 2 20 0 C-4131-28 Add suction 131-26 nvaction 125-2 PC
egister daiess mancion 120-16 date 1 regnter 2 nstructien 31-00 eg stcrs Read U ALLu dela tlata
dvts 02 rstend In the above figure (single-cycle implementation), current instruction is SW S1,
4(S2) (SW: Store Word; current addrss for this instruction is 100 in decimal; S1 and $2 are
initially 8). For redundancy, you should write \"X\" instead of 0 or . You should write the reason
for cach question as well. 5. What is the value of RegDst? (1 point) 6. What is the value of
RegWrite? (I point) 7. What is the value after sign-extension? 1 point) 8. What is the value of
MemRead? (1 point) 9. What is the value of MemtoReg? (1 point) In the above figure, current
instruction is ADDI $1. S2, #-1(which is minus l) (ADDI is ADD Immediate; current address for
this instruction s 100 in decimal and S2 are initially1). For redundancy, you should write “X\',
instead of 0 or 1 . You should write the reason for each question as well. 10. What is the value
(immediate value) of instruction [15-0)? Write the value in 6-bit binary (1 point) 11. What is the
value after sign extension? Write the value in 32-bit binary. (I point) 12. What is the value of
Reg Write? (1 point) 13. What is the value of MemtoReg? (1 point) 2/4
Solution
import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import
java.util.NoSuchElementException; /** * Implementation of an abstract set using an array-
based binary tree. This is * used to help teach binary tree\'s and will have more details explained
in * future lectures. * * @author William J. Collins * @author Matthew Hertz * @param
Data type (which must be Comparable) of the elements in this tree. */ public class
ArrayBinaryTree> extends AbstractSet { /** Entry in the data store where the root node can be
found. */ private static final int ROOT = 0; /** Array used to store the nodes which consist of
this binary tree. */ protected Node[] store; /** Number of elements within the tree. */
protected int size; /** * Initializes this ArrayBinaryTree object to be empty. This creates the
array * in which items will be stored. */ @SuppressWarnings(\"unchecked\") public
ArrayBinaryTree() { store = new Node[63]; size = 0; } /** * Initializes this
ArrayBinaryTree object to contain a shallow copy of a * specified ArrayBinaryTree object.
The worstTime(n) is O(n), where n is the * number of elements in the specified
ArrayBinaryTree object. * * @param otherTree The tree which will be copied to create our
new tree, */ @SuppressWarnings(\"unchecked\") public ArrayBinaryTree(ArrayBinaryTree
otherTree) { store = (Node[]) Arrays.copyOf(otherTree.store, otherTree.store.length); size =
otherTree.size; } public int countLeaves() { } /** * Returns the size of this
ArrayBinaryTree object. * * @return the size of this ArrayBinaryTree object. */
@Overrid.
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = \"I am part of a lost generation#and I refuse to believe that#\";
sb.append(set1);
String set2 = \"I can change the world#I realize this may be a shock but#\";
sb.append(set2);
String set3 = \"\'Happiness comes from within\'#is a lie, and#\";
sb.append(set3);
String set4 = \"\'Money will make me happy\'#So in 30 years I will tell my children#\";
sb.append(set4);
String set5 = \"they are not the most important thing in my life#\";
sb.append(set5);
String set6 = \"My employer will know that#I have my priorities straight because#\";
sb.append(set6);
String set7 = \"work#is more important than#family#I tell you this#\";
sb.append(set7);
String set8 = \"Once upon a time#Families stayed together#\";
sb.append(set8);
String set9 = \"but this will not be true in my era#\";
sb.append(set9);
String set10 = \"This is a quick fix society#Experts tell me#\";
sb.append(set10);
String set11 = \"30 years from now, I will be celebrating the 10th anniversary of my
divorce#\";
sb.append(set11);
String set12 = \"I do not concede that#I will live in a country of my own making#\";
sb.append(set12);
String set13 = \"In the future#Environmental destruction will be the norm#\";
sb.append(set13);
String set14 = \"No longer can it be said that#My peers and I care about this earth#\";
sb.append(set14);
String set15 = \"It will be evident that#My generation is apathetic and lethargic#\";
sb.append(set15);
String set16 = \"It is foolish to presume that#There is hope#\";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split(\"#\");
System.out.println(\"========== Original Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println(\"========== Reverse Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: \'#\':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyS.
Given below is the completed implementation of MyLinkedList class. O.pdfinfo430661
Given below is the completed implementation of MyLinkedList class. Other classes are not
modified and remain same as in question - MyList, MyAbstractList, TestMyLinkedList.
The output of TestMyLinkedList is shown below. Please don\'t forget to rate the answer if it
helped. Thank you very much.
Since the MyList is not completely pasted in the question ... giving the complete class file below
MyList.java
public interface MyList> extends java.lang.Iterable
{
// Add a new element at the end of this list
public void add (E e);
// Add a new element at specified index in this list
public void add (int index, E e);
// Return true if this list contains the element
public boolean contains (E e);
// Return the element at the specified index
public E get (int index);
// Return the index of the first matching element
// Return -1 if no match.
public int indexOf (E e);
// Return the index of the last matching element
// Return -1 if no match.
public int lastIndexOf (E e);
E remove(int index);
void clear();
E set(int index, E e);
}
MyLinkedList.java
public class MyLinkedList> extends MyAbstractList
implements Comparable>
{
private Node head, tail; // head and tail pointers
// Create a default list
public MyLinkedList()
{
}
public int size()
{
return size;
}
// Need this for implementing Comparable
public int compareTo (MyLinkedList e)
{
return(size() - e.size());
}
// Create a list from an array of objects
public MyLinkedList (E[] objects)
{
super(objects); // Passes the array up to abstract parent
}
// Return the head element in the list
public E getFirst()
{
if (size == 0)
{
return null;
}
else
{
return head.element;
}
}
// Return the last element in the list
public E getLast()
{
if (size == 0)
{
return null;
}
else
{
return tail.element;
}
}
// Add an element to the beginning of the list
public void addFirst (E e)
{
// Create a new node for element e
Node newNode = new Node(e);
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // new node is only node
{
tail = head;
}
}
// Add an element to the end of the list
public void addLast (E e)
{
// Create a new node for element e
Node newNode = new Node(e);
if (tail == null)
{
head = tail = newNode; // new node is only node
}
else
{
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
// Remove the head node and
// return the object from the removed node
public E removeFirst()
{
if (size == 0)
{
return null;
}
else
{
Node temp = head;
head = head.next;
size--;
if (head == null)
{
tail = null;
}
return temp.element;
}
}
// Remove the last node and return the object from it
public E removeLast()
{
if (size == 0)
{
return null;
}
else if (size == 1)
{
Node temp = head;
head = tail = null;
size = 0;
return temp.element;
}
else
{
Node current = head;
for (int i = 0; i < size - 2; i++)
{
current = current.next;
}
Node temp = tail;
tai.
Please complete all the code as per instructions in Java programming.docxcgraciela1
Please complete all the code as per instructions in Java programming import org.w3c.dom.Node; import javax.xml.crypto.NodeSetData; import java.awt.*; import java.util.Iterator; import java.util.NoSuchElementException; /** * This class implements an acyclic (non-cyclic), doubly-linked list. * @param */ public class CiscDoublyLinkedList implements CiscList { /** * A reference to the first node in the list (or null if list is empty). */ private Node head; /** * A reference to the last node int the list (or null if list is empty). */ private Node tail; /** * Number of elements in the list. */ private int size; /** * Returns the number of elements in this list. * * * @return the number of elements in this list */ @Override public int size() { return size; } /** * Returns {@code true} if this list contains no elements. * * * @return {@code true} if this list contains no elements */ @Override public boolean isEmpty() { if (size == 0){ return true; } return false; } /** * Returns {@code true} if this list contains the specified element (compared using the {@code equals} method). * * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element * @throws NullPointerException if the specified element is null */ @Override public boolean contains(Object o) { if(o == null) { throw new NullPointerException(); } Node node = head; while(node != null) { if(node.data.equals(o)){ return true; } node = node.next; } return false; } /** * Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not * contain the element (compared using the {@code equals} method). * * * @param o element to search for * @return the index of the first occurrence of the specified element in this list, or -1 if this list does not * contain the element * @throws NullPointerException if the specified element is null */ @Override public int indexOf(Object o) { if (o == null){ throw new NullPointerException(); } for(int i =0; i = size){ throw new IndexOutOfBoundsException(); } return null; } /** * Appends the specified element to the end of this list. * * *
Lists may place the specified element at arbitrary locations if desired. In particular, an ordered list will * insert the specified element at its sorted location. List classes should clearly specify in their documentation * how elements will be added to the list if different from the default behavior (end of this list). * * @param e element to be appended to this list * @return {@code true} * @throws NullPointerException if the specified element is null */ @Override public boolean add(E e) { if(e == null){ throw new NullPointerException(); } return false; } /** * Replaces the element at the specified position in this list with the specified element. * * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position *.
I need help implementing a Stack with this java programming assignme.pdfsauravmanwanicp
I need help implementing a Stack with this java programming assignment:
Given a doubly linked list (code provided below) implement a Stack. You must use the doubly
link list class and utilize it as an object in your implementation of the stack.
A Stack is a Last in First Out (LiFO) structure which translates to the processes of outputting the
last element which was inputted in the collection. The Stack is based on the process of putting
things on top of one another and taking the item on top (think of a stack of papers).
Operations to implement:
push (E): Add an element to the start of the sequence
pop: Remove an element from the start of the sequence
Peek: Return the first element of the sequence without removing it
atIndex(x): Return the element at the given index (x) Or throw an exception if it is out of bound
(if you can control the user input then do that instead)
Size: Return the size of the Stack
isEmpty: Boolean, returns true if the Stack is empty
Empty: Empty the Stack
Code Part 1:
public class DoublyLinkedList{
private DNode head;
private DNode tail;
private int size;
public DoublyLinkedList(){ // construct an empty list
this.tail = new DNode (null, null, this.head);
this.head = new DNode (null, this.tail, null);
this.size = 0;
}
public DoublyLinkedList(DNode next){ // constructs a list
// out of a single node
this.tail = new DNode (null, null, next);
this.head = new DNode (null, next, null);
next.changeNext(this.tail);
next.changePrev(this.head);
this.size = 1;
}
public DoublyLinkedList(Object [] objectArray){ // construct a list out of
// an array
this.tail = new DNode (null, null, this.head);
this.head = new DNode (null, this.tail, null);
DNode temp = this.head;
for (Object e : objectArray)
{
//Anonomus function
new DNode (e, temp.getNext(),temp).insertBetweenNodes(temp, temp.getNext());
temp = temp.getNext();
this.size += 1;
}
}
public void addToFrontofList(Object toAdd){ // Appends the begining
// of the list
DNode temp = new DNode (toAdd, this.head.getNext(), this.head);
this.head.getNext().changePrev(temp);
this.head.changeNext(temp);
this.size += 1;
}
public void addToendofList (Object toAdd) // appends the end of the list
// with a node
{
DNode temp = new DNode (toAdd, this.tail, this.tail.getPrev());
this.tail.getPrev().changeNext(temp);
this.tail.changePrev(temp);
this.size += 1;
}
public void insertAfterNode(DNode current, Object input)// Inserts a new
// a new node after
// current node
{
current.insertAfterNode(input);
this.size += 1;
}
public int getSize() // returns the size of the list
{
return this.size;
}
public String toString()
{
String result = \"\";
for (DNode temp = this.head.getNext();
temp.hasNext(); temp = temp.getNext())
{
result += temp.getValue();
result += \" -> \";
}
result += \"End of list\";
return result;
}
}
and code part2:
public class DNode{
private Object e; // place holder for the type of object the
//collection is storing
private DNode next; // reference to the next node in the sequence
// of.
Can you please debug this Thank you in advance! This program is sup.pdfFashionBoutiquedelhi
Can you please debug this? Thank you in advance! This program is supposed to use stacks and
find the paths of an airplane. It should tell you whether or not the plane goes from the requested
city to the requested destination. requestFile.txt contains the requests, flightFile.txt contains the
flights and cityFile.txt contains the city\'s that the airline serves.
My errors: my output is simply \"Hpair does not serve Los Angeles.\" Thats it and it stops.
It should look something like (these are not real values of the file just an example):
\"Request is to fly from cityA to CityB.
Hpair flight from cityA to CityB.
Request is to fly from cityC to cityD.
Sorry, HPAir does not serve City D
Request is to fly from cityE to CityF
Sorry, HPAir does not fly from cityE to CityF\"
**It said to use ispath.cpp but I got confused on how to implement it completely.\"
isPath.cpp
//***I did not include ispath.cpp in my program. Parts of it are in the map.h portion.
main.cpp
#include
#include
#include \"Map.h\"
using namespace std;
int main()
{
Map aMap;
aMap.readFlights();
aMap.verifyRequestedFile();
}
StackInterface.h
#ifndef StackInterface_h
#define StackInterface_h
template
class StackInterface
{
/** Checks if the stack is empty.
@return True if the stack is empty or false if the stack is not.*/
virtual bool isEmpty() const = 0;
/** Adds a new item to the stack
@post newEntry is at the top of the stack
@param newEntry is the object to be added to the stack
@return True if successfully added, otherwise false. */
virtual bool push(const ItemType& newEntry) = 0;
/** Removes item from stack
@post The top item in the stack is removed
@return True if the item was removed, false if it was not. */
virtual bool pop() = 0;
/** Returns the top item in the stack
@pre The stack is not empty
@post The top item in the stack is returned
@return The top of the stack */
virtual ItemType peek() const = 0;
};
#endif /* StackInterface_h */
Node.h
#ifndef node_h
#define node_h
template
class Node {
public:
Node();
Node (const ItemType &anItem);
Node(const ItemType &anItem, Node * nextNodePtr);
void setItem(const ItemType &anItem);
void setNext(Node * nextNodePtr);
ItemType getItem() const;
Node* getNext() const;
private:
ItemType item;
Node* next;
};
template
Node::Node():next(nullptr){}
template
Node::Node(const ItemType &anItem):item(anItem), next(nullptr){}
template
Node::Node(const ItemType &anItem, Node * nextNodePtr):item(anItem), next(nextNodePtr)
{
}
template
void Node::setItem(const ItemType &anItem){
item = anItem;
}
template
void Node::setNext(Node * nextNodePtr) {
next = nextNodePtr;
}
template
ItemType Node::getItem() const {
return item;
}
template
Node* Node::getNext()const{
return next;
}
#endif /* node_h */
LinkedStack.h
#include
#ifndef LinkedStack_h
#define LinkedStack_h
#include \"Node.h\"
#include \"StackInterface.h\"
template
class LinkedStack:public StackInterface{
public:
LinkedStack();
LinkedStack(const LinkedStack &aStack); //space matter?***********
virt.
Please review my code (java)Someone helped me with it but i cannot.pdffathimafancyjeweller
Please make it to clear 12-95. The basketball passed through the hoop even though it barely
cleared the hands of the player B who attempted to block it. Neglecting the size of the ball,
determine the magnitude vn of its initial velocity and the height h of the ball when it passes over
player B 10 ft 5 ft Prob. 12-95
Solution
Consider the motion along horizontal direction
Vox = initial velocity in horizontal direction = Va Cos30
X = horizontal distance = 25 + 3 = 28 ft
t = time taken
t = X / Vox = 28/(Va Cos30) eq-1
consider the motion in vertical direction
Y = vertical displacement = 10 - 7 = 3 ft
a = acceleration = - 32.2
Voy = initial velocity = Va Sin30
t = time taken
using the equation
Y = Voy t + (0.5) a t2
3 = (Va Sin30) (28/(Va Cos30)) + (0.5) (- 32.2) (28/(Va Cos30))2
Va = 35.8 m/s
t\' = time taken to reach B = 25 / (Va Cos30) = 25 / (35.8 Cos30) = 0.81 sec
h = 7 + Voy t\' + (0.5) a t\'2
h = 7 + (35.8 Sin30) (0.81) + (0.5) (- 32.2) (0.81)2
h = 10.94 ft.
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
Required to augment the author's Binary Search Tree (BST) code to support these new operations. Method names below are merely suggestions. (The author’s class is attached separately in the file called “authordoc”. I just built a simple test tree in the author’s main method which can be used to test the various operations. )
1. AnyType nthElement(int n) -- returns the n-th element (starting from 1) of the in-order traversal of the BST.
2. int rank( AnyType x ) -- returns the "rank" of x. The rank of an element is its position (starting with 1) in an in-order traversal.
3. AnyType median( ) -- returns the median (middle) element in the BST. If the BST contains an even number of elements, returns the smaller of the two medians.
4. boolean isPerfect( ) -- returns true if the BST is a perfect binary tree.
5. boolean isComplete( ) -- returns true if the BST is a complete binary tree.
6. String toString( int nrLevels ) -- generates the level-order output described in the sample output below.
Most of these operations could easily be implemented by performing an in-order traversal inside the BST and perhaps placing the results in an ArrayList. However, such a method is extremely inefficient. Instead, we are going to achieve faster performance by "augmenting" the BST nodes. You will add a new private integer data member ("tree size") to the BinaryNode which stores the size of the tree rooted at that node (including the root). You must develop your own algorithms for these operations, but obviously you will use the new tree size data member to guide your search. Think before you code and think recursively!
These items cover those topics not addressed elsewhere in the project description. (R) indicates a requirement, (H) indicates a hint, and (N) indicates a note.
1. (R) Although we are only using the BST for integers, the BST must remain a generic class.
2. (R) Duplicate values are not allowed. Attempts to insert a duplicate value should be ignored.
3. (R) Attempts to remove non-existent values should be ignored.
4. (R) From a coding perspective, the easiest way to avoid duplicate insertions or attempting to remove non-existent elements is to first call find( ). However, this technique is NOT permitted for two reasons.
Calling find( ) before each insert/remove doubles the running time for these operations and is therefore inefficient.
Recusively coding the insert/remove methods to handle these situations is a great learning experience.
5. (R) The level order print (PRINT command) outputs the value of each node, the size of the tree rooted at that node, and the value of the node's parent in that order, inside parenthesis, separated by commas. (node value, tree size, parent value). Since the root has no parent, print NULL for the root's parent value. For readability, separate the levels with a blank line and print no more than 6 node/size/parent values per line. If a level requires multiple lines, use consecutive lines (without a blank line between the ...
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
New folder/jsjf/ArrayStack.classpackage jsjf;
publicsynchronizedclass ArrayStack implements StackADT {
privatestaticfinal int DEFAULT_CAPACITY = 100;
private int top;
private Object[] stack;
public void ArrayStack();
public void ArrayStack(int);
public void push(Object);
private void expandCapacity();
public Object pop() throws exceptions.EmptyCollectionException;
public Object peek() throws exceptions.EmptyCollectionException;
public int size();
public boolean isEmpty();
public String toString();
}
New folder/jsjf/ArrayStack.javaNew folder/jsjf/ArrayStack.javapackage jsjf;
import jsjf.exceptions.*;
import java.util.Arrays;
// -------------------------------------------------------
// Author: Yifu Wu
// Date: 03/10/16
// Source Name: ArrayStack<T>
// Due date: 03/10/16
// Description:
/**
* An array implementation of a stack in which the bottom of the
* stack is fixed at index 0.
*
* @author Java Foundations
* @version 4.0
*/
publicclassArrayStack<T>implementsStackADT<T>
{
privatefinalstaticint DEFAULT_CAPACITY =100;
privateint top;
private T[] stack;
/**
* Creates an empty stack using the default capacity.
*/
publicArrayStack()
{
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty stack using the specified capacity.
* @param initialCapacity the initial size of the array
*/
publicArrayStack(int initialCapacity)
{
top =0;
stack =(T[])(newObject[initialCapacity]);
}
/**
* Adds the specified element to the top of this stack, expanding
* the capacity of the array if necessary.
* @param element generic element to be pushed onto stack
*/
publicvoid push(T element)
{
if(size()== stack.length)
expandCapacity();
stack[top]= element;
top++;
}
/**
* Creates a new array to store the contents of this stack with
* twice the capacity of the old one.
*/
privatevoid expandCapacity()
{
//stack = Arrays.copyOf(stack, stack.length * 2);
System.out.println("Expanding stack capacity\n");
T[] temp =(T[])(newObject[2*top]);
for(int i=0; i< top; i++)
temp[i]= stack[i];
stack = temp;
}
/**
* Removes the element at the top of this stack and returns a
* reference to it.
* @return element removed from top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T pop()throwsEmptyCollectionException
{
if(isEmpty())
thrownewEmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top]=null;
return result;
}
/**
* Returns a reference to the element at the top of this stack.
* The element is not removed from the stack.
* @return element on top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T peek()throwsEmptyCollectionException
{
if(isEmpty())
thrownewEmptyCollectionException("stack");
return stack[top-1];
}
/**
* Returns the number of elements in ...
Hi, Please find my code.I have correted all of your classes.Plea.pdfpritikulkarni20
Hi, Please find my code.
I have correted all of your classes.
Please let me know in case if do not get concpt.
######## Node.java ###########
public class Node {
private E element;
private Node next;
public Node() {
this.element = null;
this.next = null;
}
public Node(E e) {
this.element = e;
this.next = null;
}
public E getElement() {
return this.element;
}
public void setElement(E element) {
this.element= element;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
########## Stack.java #############
public class Stack {
private int N;
private Node top;
public Stack() {
N = 0;
this.top =null;
}
/*
* places element on the top of the stack
*/
public void push(E element){
Node temp = new Node(element);
temp.setNext(top);
top = temp;
N++;
}
/*
* remove the top node and return its contents
*/
public E pop(){
if(top == null)
return null;
E e = top.getElement();
top = top.getNext();
N--;
return e;
}
/*
* Look at the top element of the Stack and return it, without removing
*/
public E peek(){
if(top == null)
return null;
return top.getElement();
}
//returns the size of the stack
public int size(){
return N; //replace
}
public boolean isEmpty(){
return top==null;
}
}
############ Queue.java ############
public class Queue {
private Node front;
private Node back;
private int N;
public Queue() {
this.front = null;
this.back = null;
N = 0;
}
/*
* places element in the back of the Queue
*/
public void enqueue(E element){
Node temp = new Node(element);
if(front == null) {
front = temp;
back = temp;
}
else{
back.setNext(temp);
back = temp;
}
N++;
}
/*
* remove the front node of the queue and return it
*/
public E dequeue(){
if(front == null) {
return null;
}
E item = front.getElement();
front = front.getNext();
// if we had only one element
if(front == null){
back = null;
}
N--;
return item;
}
/*
* Look at the front of the queue and return it, without removing
*/
public E peek(){
if(back == null)
return null;
return back.getElement();
}
//returns the size of the queue
public int size(){
return N;
}
public boolean isEmpty(){
return front==null;
}
}
########### Palindrome.java ############
import java.util.Scanner;
public class Palindrome
{
public static void main(String[ ] args)
{
Scanner input = new Scanner(System.in);
String inputString;
System.out.print(\"Please enter your string: \");
inputString = input.next( );
if (isPalindrome( inputString )){
System.out.println(\"Yes it is a palindrome.\");
}
else{
System.out.println(\"No this is not a palindrome.\");
}
}
public static boolean isPalindrome(String input)
{
Queue q = new Queue ();
Stack s = new Stack ();
char letter;
int i;
for (i = 0; i < input.length( ); i++)
{
letter = input.charAt(i);
q.enqueue(letter);
s.push(letter);
}
while (!q.isEmpty( ))
{
if (q.dequeue() != s.pop( ))
return false;
}
return true;
}
}
/*
Sample Output:
Please enter your string: MadaM
Yes it is a palindrome.
*/
Solution
Hi, Please find my code.
I have correted all of your classes.
Pl.
In this lab, you will be given a simple code for a min Heap, and you.pdfcharanjit1717
In this lab, you will be given a simple code for a min Heap, and youre going to complete some of
the methods to handle some edge cases. Tasks for today: There are mainly two tasks, and the
logic of both of them is provided in their bodies: 1) Fully implement AddItem(). 2) Fully
implement HeapUp() Use the following start-up code. The main code and a demo class are
provided as .cs files. Use them to test your code. Once you complete the above two tasks, upload
the source code for your MinHeap class to Blackboard. class BinaryHeap : IEnumerable where T
: IComparable { private T[] array; private int count; // Number of elements (nodes) public
BinaryHeap(int size) { array = new T[size]; count = 0; } public T GetItem(int index) { return
array[index]; } private void SetItem(int index, T value) { while (index >= array.Length)
Grow(array.Length * 2); array[index] = value; } private void Grow(int newsize) {
Array.Resize(ref array, newsize); } // Indices of left and right children private int
LeftChildIndex(int pos) { return 2 * pos + 1; } private int RightChildIndex(int pos) { return 2 *
pos + 2; } private int GetParentIndex(int pos) => (pos - 1) / 2; private T GetRightChild(int pos)
=> array[RightChildIndex(pos)]; private T GetLeftChild(int pos) => array[LeftChildIndex(pos)];
private T GetParent(int pos) => array[GetParentIndex(pos)]; // "Has" methods to determine if the
indices exist private bool HasLeftChild(int pos) { if (LeftChildIndex(pos) < count) return true;
else return false; } private bool HasRightChild(int pos) { if (RightChildIndex(pos) < count)
return true; else return false; } private bool IsRoot(int pos) => pos == 0; // (true if element is
root) // Swap, uh, swaps two values given two indicies. This should be private but I originally
had it public for some reason. private void Swap(int position1, int position2) { T first =
array[position1]; array[position1] = array[position2]; array[position2] = first; } public void
AddItem(T value) { // This is part of la //Insert Logic // If the tree is empty, insert at the bottom
(it does that already) // if not, insert at the end, // From the end you either need to swap to the
root, and keep minheapify (Heapdown) // or, you should probably implement move up (for lab 6,
you need to implement // for that you run a while loop, check if the current position both isn't the
root, and is higher priority than a parent (in this case that probably means it's a lower value) // if
it is, swap with parent, and keep doing that until it's its in the array[count] = value; count++;
ReCalculateUp(); } private void HeapDown() { //CompareTo //this.CompareTo(value) returns <
0 if this < value //this.CompareTo(value) returns >0 if this > value int index = 0; while
(HasLeftChild(index)) { var smallerIndex = LeftChildIndex(index); if (HasRightChild(index)
&& (GetRightChild(index).CompareTo(GetLeftChild(index))<0) ) //there's a set of ( ) around the
right expression that are redundant but hopefully easier to read { smallerI.
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfFootageetoffe16
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding a reference to a node’s
parent, as shown below:
BST.TreeNode
#element
#left : TreeNode
#right: TreeNode
#parent: TreeNode
Implement the insert and delete methods in BST class to update the parent for each node in the
tree.
Add the following new method in BST:
/** Return the node for the specific element.
* Return null if the element is not in the tree. */
private TreeNode getNode(E element)
/** Returns true if the node for the element is a lead */
private boolean isLeaf(E element)
/** Returns the path of the element from the specific element to the root in an array list */
public ArrayList getPath(E e)
Write a test program that prompts the user to enter 10 integers, adds them to the tree, deletes the
first integer from the tree, and displays the paths for all leaf nodes.
Sample run
Enter 10 integers :
45 54 67 56 50 45 23 59 23 67
[50, 54, 23]
[59, 56, 67, 54, 23]
Solution
import java.util.NoSuchElementException; public class TreeSet> implements Set {
private TreeNode root; private int size; // Constructs an empty set. public
TreeSet() { root = null; size = 0; } // Adds the given value to this
set, if it was not already in the set. // If the element is already a member of this set, adding it
again has no effect. public void add(E value) { root = add(root, value); }
// private recursive helper for add // uses the \"x = change(x)\" pattern: // pass in
current state of root // return out desired new state of root private TreeNode
add(TreeNode node, E value) { if (node == null) { node = new
TreeNode(value); // reached dead end; put new node here size++; }
else if (value.compareTo(node.data) > 0) { node.right = add(node.right, value);
} else if (value.compareTo(node.data) < 0) { node.left = add(node.left,
value); } // else a duplicate; do nothing return node; } // Returns
true if this set contains the given element value. public boolean contains(E value) {
return contains(root, value); } // private recursive helper for contains private
boolean contains(TreeNode node, E value) { if (node == null) { return
false; } else if (value.compareTo(node.data) > 0) { return
contains(node.right, value); } else if (value.compareTo(node.data) < 0) {
return contains(node.left, value); } else { // value.equals(root.data);
found it! return true; } } // Returns the minimum value in this
set. // Throws a NoSuchElementException if this set is empty. public E getMin() {
if (root == null) { throw new NoSuchElementException(\"empty tree\");
} return getMin(root); } // private recursive helper for getMin
private E getMin(TreeNode node) { if (node.left == null) { return
node.data; } else { return getMin(node.left); } }
// Returns true if this set does not contain any elements. public boolean isEmpty() {
return size == 0; } // Prints all elements of this tree in a left-to-right order (in-order)
traversal. public void print() { print(root); } // private recursive helper
for print private void print(TreeNode .
On the code which has a class in which I implementing a binary tree .pdfwasemanivytreenrco51
On the code which has a class in which I implementing a binary tree using an array. This array,
named store, stores Node in entries corresponding to
nodes in the tree and null if the node does not exist. Complete the countLeavesmethod so that it
returns the number of leaves in this tree.
Code:
Solution
import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import
java.util.NoSuchElementException; /** * Implementation of an abstract set using an array-
based binary tree. This is * used to help teach binary tree\'s and will have more details explained
in * future lectures. * * @author William J. Collins * @author Matthew Hertz * @param
Data type (which must be Comparable) of the elements in this tree. */ public class
ArrayBinaryTree> extends AbstractSet { /** Entry in the data store where the root node can be
found. */ private static final int ROOT = 0; /** Array used to store the nodes which consist of
this binary tree. */ protected Node[] store; /** Number of elements within the tree. */
protected int size; /** * Initializes this ArrayBinaryTree object to be empty. This creates the
array * in which items will be stored. */ @SuppressWarnings(\"unchecked\") public
ArrayBinaryTree() { store = new Node[63]; size = 0; } /** * Initializes this
ArrayBinaryTree object to contain a shallow copy of a * specified ArrayBinaryTree object.
The worstTime(n) is O(n), where n is the * number of elements in the specified
ArrayBinaryTree object. * * @param otherTree The tree which will be copied to create our
new tree, */ @SuppressWarnings(\"unchecked\") public ArrayBinaryTree(ArrayBinaryTree
otherTree) { store = (Node[]) Arrays.copyOf(otherTree.store, otherTree.store.length); size =
otherTree.size; } public int countLeaves() { } /** * Returns the size of this
ArrayBinaryTree object. * * @return the size of this ArrayBinaryTree object. */
@Override public int size() { return size; } /** * Returns an iterator that will return the
elements in this ArrayBinaryTree, * but without any specific ordering. * * @return Iterator
positioned at the smallest element in this ArrayBinaryTree * object. */ @Override
public Iterator iterator() { return new ArrayTreeIterator(); } /** * Determines if there is at
least one element in this ArrayBinaryTree object * that equals a specified element. The
worstTime(n) is O(n) and * averageTime(n) is O(log n). * * @param obj - the element
sought in this ArrayBinaryTree object. * @return true - if there is an element in this
ArrayBinaryTree object that * equals obj; otherwise, return false. * @throws
ClassCastException - if obj cannot be compared to the elements in * this
ArrayBinaryTree object. * @throws NullPointerException - if obj is null. */ @Override
public boolean contains(Object obj) { return getEntry(obj) != null; } /** * Ensures that
this ArrayBinaryTree object contains a specified element. The * worstTime(n) is O(n) for this
addition. * * @param element Element we want to be certain is contained within.
package com.java2novice.ds.linkedlist;
import java.util.NoSuchElementException;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
/**
* this class keeps track of each element information
* @author java2novice
*
*/
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
/**
* returns the size of the linked list
* @return
*/
public int size() { return size; }
/**
* return whether the list is empty or not
* @return
*/
public boolean isEmpty() { return size == 0; }
/**
* adds element at the starting of the linked list
* @param element
*/
public void addFirst(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
/**
* adds element at the end of the linked list
* @param element
*/
public void addLast(E element) {
Node tmp = new Node(element, null, tail);
if(tail != null) {tail.next = tmp;}
tail = tmp;
if(head == null) { head = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
/**
* this method walks forward through the linked list
*/
public void iterateForward(){
System.out.println(\"iterating forward..\");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}
/**
* this method walks backward through the linked list
*/
public void iterateBackward(){
System.out.println(\"iterating backword..\");
Node tmp = tail;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.prev;
}
}
/**
* this method removes element from the start of the linked list
* @return
*/
public E removeFirst() {
if (size == 0) throw new NoSuchElementException();
Node tmp = head;
head = head.next;
head.prev = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
/**
* this method removes element from the end of the linked list
* @return
*/
public E removeLast() {
if (size == 0) throw new NoSuchElementException();
Node tmp = tail;
tail = tail.prev;
tail.next = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
public static void main(String a[]){
DoublyLinkedListImpl dll = new DoublyLinkedListImpl();
dll.addFirst(10);
dll.addFirst(34);
dll.addLast(56);
dll.addLast(364);
dll.iterateForward();
dll.removeFirst();
dll.removeLast();
dll.iterateBackward();
}
}
Solution
package com.java2novice.ds.linkedlist;
import java.util.NoSuchElementException;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
/**
* this class keeps track of each element information
* @author java2novice
*
*/
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
/**
* returns the size of the l.
According to the IRS, 1.1 of tax returns will be audited in 2011. A.pdfxlynettalampleyxc
According to the IRS, 1.1% of tax returns will be audited in 2011. A random sample of 40 tax
returns was selected. Use the Poisson distribution to approximate the binomial distribution to
determine the probability that more than two of these tax returns will be audited.0.1215
Solution
for poisson distribution, mean = np = 40(0.011) = 0.44
by using excel function =1-POISSON(1,0.44,1), P(x>=2) = 0.0726.
Write a SELECT statement that returns a single value that represents.pdfxlynettalampleyxc
Write a SELECT statement that returns a single value that represents the sum of the largest
unpaid invoices submitted by each vendor. Use a common table expression(cte) that returns
MAX(InvoiceTotal) grouped by VendorID, filtering for invoices with a balanced due.
Solution
WITH INVOICE_CTE (VendorID,maxInvoiceTotal)
AS
(
Select VendorID,MAX(InvoiceTotal) as maxInvoiceTotal
from Invoice
where due>0
)
Select MAX(maxInvoiceTotal) from
INVOICE_CTE.
More Related Content
Similar to For the code below complete the preOrder() method so that it perform.pdf
Note- Can someone help me with the Public boolean add(E value) method.pdfStewart29UReesa
Note: Can someone help me with the Public boolean add(E value) method and Private void
add(E value,Node n) method. I have everything but it is not working. Also need help with the
remove methods. Both public and private methods for remove. package edu.ust.cisc; import
java.util.Iterator; import java.util.NoSuchElementException; public class CiscSortedLinkedList
> implements CiscList { /** * A reference to this list's dummy node. Its next reference should
refer to the node containing the first element * in this list, or it should refer to itself if the list is
empty. The next reference within the node containing * the last element in this list should refer to
dummy, thus creating a cyclic list. */ private Node dummy; /** * Number of elements in the list.
*/ private int size; /** * Constructs an empty CiscSortedLinkedList instance with a non-null
dummy node whose next reference refers to * itself. */ public CiscSortedLinkedList() { dummy
= new Node<>(null, null); dummy.next = dummy; } /** * Returns the number of elements in
this list. * * @return the number of elements in this list */ @Override public int size() { return
size; } /** * Returns {@code true} if this list contains no elements. * * @return {@code true} if
this list contains no elements */ @Override public boolean isEmpty() { return size==0; } /** *
Returns {@code true} if this list contains the specified element (compared using the {@code
equals} method). * This implementation should stop searching as soon as it is able to determine
that the specified element is not * present. * @param o element whose presence in this list is to
be tested * @return {@code true} if this list contains the specified element * @throws
NullPointerException if the specified element is null */ @Override public boolean
contains(Object o) { if(o==null){ throw new NullPointerException(); } return
containsHelper(o,dummy.next); } private boolean containsHelper(Object o, Node node){
if(node== dummy){ return false; } else if(o.equals(node.data)){ return true; } else{ return
containsHelper(o,node.next); } } /** * Returns an iterator over the elements in this list in proper
sequence. * * @return an iterator over the elements in this list in proper sequence */ @Override
public Iterator iterator() { //return new Iterator (){ //private Node curr = dummy.next; //private
Node prev = dummy; //private boolean canRemove = false; return new CiscLinkedListIterator();
} /** * Returns an array containing all of the elements in this list in proper sequence (from first
to last element). * *
The returned array will be "safe" in that no references to it are maintained by this list. (In other
words, * this method must allocate a new array even if this list is backed by an array). The caller
is thus free to modify * the returned array. * * @return an array containing all of the elements in
this list in proper sequence */ @Override public Object[] toArray() { Object[] arr = new
Object[size]; int i = 0; for(Node current = dummy;curren.
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxGavinUJtMathist
JAVA
Demonstrate the use of your APL in a PartB_Driver class by doing the following. Create a static method called removeConsecutiveDuplicates that removes any consecutive duplicate strings from an array positional list of Strings and returns the number of strings left after the removal. After calling the method, the positional list parameter should contain the same sequence of strings as before but with any consecutive duplicates removed. Illustrate your method using the following sets of strings and display the content of the list after executing the method.
NOTE: You MUST use a combination/variation of ALL the add and set methods (AddFirst, AddLast, AddBefore, AddAfter, and set) in creating one of the following original lists.
- harry ron tom tom tom hermione
- harry harry tom ron mary harry
- tom ron harry hermione mary
- mary mary tom james hermione hermione james harry harry harry
You MUST NOT use any other auxiliary data structure e.g., arrays in your implementation ofremoveConsecutiveDuplicates.
Sample Output (for last set of Strings)
Original positional list:
[0] mary [1] mary [2] tom [3] james [4] hermione [5] hermione [6] james [7] harry [8] harry [9] harry
APL.java
public class ArrayPositionalList<E> implements PositionalList<E> {
private static class ArrPos<E> implements Position<E> {
private int index;
private E element;
public ArrPos(E e, int i) {
index = i;
element = e;
}
public E getElement() throws IllegalStateException {
if (index == -1) {
throw new IllegalStateException("Position no longer valid");
}
return element;
}
public void setElement(E e) {
element = e;
}
public int getIndex() {
return index;
}
public void setIndex(int i) {
index = i;
}
}
public static final int CAPACITY = 16;
private ArrPos<E>[] data;
private int size = 0;
public ArrayPositionalList() {
this(CAPACITY);
}
public ArrayPositionalList(int capacity) {
data = (ArrPos<E>[]) new ArrPos[capacity];
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public Position first() {
if (!isEmpty())
return data[0];
return null;
}
@Override
public Position last() {
if (!isEmpty())
return data[size - 1];
return null;
}
@Override
public Position before(Position p) throws IllegalArgumentException {
if (p.getIndex() > 0 && p.getIndex() < size) {
return data[p.getIndex() - 1];
}
if (p.getIndex() == 0)
return null;
throw new IllegalArgumentException();
}
@Override
public Position after(Position p) throws IllegalArgumentException {
if (p.getIndex() >= 0 && p.getIndex() < size - 1) {
return data[p.getIndex() + 1];
}
if (p.getIndex() == size - 1)
return null;
throw new IllegalArgumentException();
}
@Override
public Position addFirst(E e) {
if (size < data.length) {
for (int i = size - 1; i >= 0; i--) {
data[i + 1] = data[i];
data[i + 1].setIndex(data[i + 1].getIndex() + 1);
}
data[0] = new ArrPos<E>(e, 0);
size++;
return data[0];
}
return null;
}
@Override
public Position addLast(E e) {
if (size < data.length) {
da.
4. The size of instructions can be fixed or variable. What are advant.pdfmumnesh
4. The size of instructions can be fixed or variable. What are advantage and disadvantage of
fixed compared to variable? point) eft 2 20 0 C-4131-28 Add suction 131-26 nvaction 125-2 PC
egister daiess mancion 120-16 date 1 regnter 2 nstructien 31-00 eg stcrs Read U ALLu dela tlata
dvts 02 rstend In the above figure (single-cycle implementation), current instruction is SW S1,
4(S2) (SW: Store Word; current addrss for this instruction is 100 in decimal; S1 and $2 are
initially 8). For redundancy, you should write \"X\" instead of 0 or . You should write the reason
for cach question as well. 5. What is the value of RegDst? (1 point) 6. What is the value of
RegWrite? (I point) 7. What is the value after sign-extension? 1 point) 8. What is the value of
MemRead? (1 point) 9. What is the value of MemtoReg? (1 point) In the above figure, current
instruction is ADDI $1. S2, #-1(which is minus l) (ADDI is ADD Immediate; current address for
this instruction s 100 in decimal and S2 are initially1). For redundancy, you should write “X\',
instead of 0 or 1 . You should write the reason for each question as well. 10. What is the value
(immediate value) of instruction [15-0)? Write the value in 6-bit binary (1 point) 11. What is the
value after sign extension? Write the value in 32-bit binary. (I point) 12. What is the value of
Reg Write? (1 point) 13. What is the value of MemtoReg? (1 point) 2/4
Solution
import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import
java.util.NoSuchElementException; /** * Implementation of an abstract set using an array-
based binary tree. This is * used to help teach binary tree\'s and will have more details explained
in * future lectures. * * @author William J. Collins * @author Matthew Hertz * @param
Data type (which must be Comparable) of the elements in this tree. */ public class
ArrayBinaryTree> extends AbstractSet { /** Entry in the data store where the root node can be
found. */ private static final int ROOT = 0; /** Array used to store the nodes which consist of
this binary tree. */ protected Node[] store; /** Number of elements within the tree. */
protected int size; /** * Initializes this ArrayBinaryTree object to be empty. This creates the
array * in which items will be stored. */ @SuppressWarnings(\"unchecked\") public
ArrayBinaryTree() { store = new Node[63]; size = 0; } /** * Initializes this
ArrayBinaryTree object to contain a shallow copy of a * specified ArrayBinaryTree object.
The worstTime(n) is O(n), where n is the * number of elements in the specified
ArrayBinaryTree object. * * @param otherTree The tree which will be copied to create our
new tree, */ @SuppressWarnings(\"unchecked\") public ArrayBinaryTree(ArrayBinaryTree
otherTree) { store = (Node[]) Arrays.copyOf(otherTree.store, otherTree.store.length); size =
otherTree.size; } public int countLeaves() { } /** * Returns the size of this
ArrayBinaryTree object. * * @return the size of this ArrayBinaryTree object. */
@Overrid.
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = \"I am part of a lost generation#and I refuse to believe that#\";
sb.append(set1);
String set2 = \"I can change the world#I realize this may be a shock but#\";
sb.append(set2);
String set3 = \"\'Happiness comes from within\'#is a lie, and#\";
sb.append(set3);
String set4 = \"\'Money will make me happy\'#So in 30 years I will tell my children#\";
sb.append(set4);
String set5 = \"they are not the most important thing in my life#\";
sb.append(set5);
String set6 = \"My employer will know that#I have my priorities straight because#\";
sb.append(set6);
String set7 = \"work#is more important than#family#I tell you this#\";
sb.append(set7);
String set8 = \"Once upon a time#Families stayed together#\";
sb.append(set8);
String set9 = \"but this will not be true in my era#\";
sb.append(set9);
String set10 = \"This is a quick fix society#Experts tell me#\";
sb.append(set10);
String set11 = \"30 years from now, I will be celebrating the 10th anniversary of my
divorce#\";
sb.append(set11);
String set12 = \"I do not concede that#I will live in a country of my own making#\";
sb.append(set12);
String set13 = \"In the future#Environmental destruction will be the norm#\";
sb.append(set13);
String set14 = \"No longer can it be said that#My peers and I care about this earth#\";
sb.append(set14);
String set15 = \"It will be evident that#My generation is apathetic and lethargic#\";
sb.append(set15);
String set16 = \"It is foolish to presume that#There is hope#\";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split(\"#\");
System.out.println(\"========== Original Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println(\"========== Reverse Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: \'#\':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyS.
Given below is the completed implementation of MyLinkedList class. O.pdfinfo430661
Given below is the completed implementation of MyLinkedList class. Other classes are not
modified and remain same as in question - MyList, MyAbstractList, TestMyLinkedList.
The output of TestMyLinkedList is shown below. Please don\'t forget to rate the answer if it
helped. Thank you very much.
Since the MyList is not completely pasted in the question ... giving the complete class file below
MyList.java
public interface MyList> extends java.lang.Iterable
{
// Add a new element at the end of this list
public void add (E e);
// Add a new element at specified index in this list
public void add (int index, E e);
// Return true if this list contains the element
public boolean contains (E e);
// Return the element at the specified index
public E get (int index);
// Return the index of the first matching element
// Return -1 if no match.
public int indexOf (E e);
// Return the index of the last matching element
// Return -1 if no match.
public int lastIndexOf (E e);
E remove(int index);
void clear();
E set(int index, E e);
}
MyLinkedList.java
public class MyLinkedList> extends MyAbstractList
implements Comparable>
{
private Node head, tail; // head and tail pointers
// Create a default list
public MyLinkedList()
{
}
public int size()
{
return size;
}
// Need this for implementing Comparable
public int compareTo (MyLinkedList e)
{
return(size() - e.size());
}
// Create a list from an array of objects
public MyLinkedList (E[] objects)
{
super(objects); // Passes the array up to abstract parent
}
// Return the head element in the list
public E getFirst()
{
if (size == 0)
{
return null;
}
else
{
return head.element;
}
}
// Return the last element in the list
public E getLast()
{
if (size == 0)
{
return null;
}
else
{
return tail.element;
}
}
// Add an element to the beginning of the list
public void addFirst (E e)
{
// Create a new node for element e
Node newNode = new Node(e);
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // new node is only node
{
tail = head;
}
}
// Add an element to the end of the list
public void addLast (E e)
{
// Create a new node for element e
Node newNode = new Node(e);
if (tail == null)
{
head = tail = newNode; // new node is only node
}
else
{
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
// Remove the head node and
// return the object from the removed node
public E removeFirst()
{
if (size == 0)
{
return null;
}
else
{
Node temp = head;
head = head.next;
size--;
if (head == null)
{
tail = null;
}
return temp.element;
}
}
// Remove the last node and return the object from it
public E removeLast()
{
if (size == 0)
{
return null;
}
else if (size == 1)
{
Node temp = head;
head = tail = null;
size = 0;
return temp.element;
}
else
{
Node current = head;
for (int i = 0; i < size - 2; i++)
{
current = current.next;
}
Node temp = tail;
tai.
Please complete all the code as per instructions in Java programming.docxcgraciela1
Please complete all the code as per instructions in Java programming import org.w3c.dom.Node; import javax.xml.crypto.NodeSetData; import java.awt.*; import java.util.Iterator; import java.util.NoSuchElementException; /** * This class implements an acyclic (non-cyclic), doubly-linked list. * @param */ public class CiscDoublyLinkedList implements CiscList { /** * A reference to the first node in the list (or null if list is empty). */ private Node head; /** * A reference to the last node int the list (or null if list is empty). */ private Node tail; /** * Number of elements in the list. */ private int size; /** * Returns the number of elements in this list. * * * @return the number of elements in this list */ @Override public int size() { return size; } /** * Returns {@code true} if this list contains no elements. * * * @return {@code true} if this list contains no elements */ @Override public boolean isEmpty() { if (size == 0){ return true; } return false; } /** * Returns {@code true} if this list contains the specified element (compared using the {@code equals} method). * * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element * @throws NullPointerException if the specified element is null */ @Override public boolean contains(Object o) { if(o == null) { throw new NullPointerException(); } Node node = head; while(node != null) { if(node.data.equals(o)){ return true; } node = node.next; } return false; } /** * Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not * contain the element (compared using the {@code equals} method). * * * @param o element to search for * @return the index of the first occurrence of the specified element in this list, or -1 if this list does not * contain the element * @throws NullPointerException if the specified element is null */ @Override public int indexOf(Object o) { if (o == null){ throw new NullPointerException(); } for(int i =0; i = size){ throw new IndexOutOfBoundsException(); } return null; } /** * Appends the specified element to the end of this list. * * *
Lists may place the specified element at arbitrary locations if desired. In particular, an ordered list will * insert the specified element at its sorted location. List classes should clearly specify in their documentation * how elements will be added to the list if different from the default behavior (end of this list). * * @param e element to be appended to this list * @return {@code true} * @throws NullPointerException if the specified element is null */ @Override public boolean add(E e) { if(e == null){ throw new NullPointerException(); } return false; } /** * Replaces the element at the specified position in this list with the specified element. * * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position *.
I need help implementing a Stack with this java programming assignme.pdfsauravmanwanicp
I need help implementing a Stack with this java programming assignment:
Given a doubly linked list (code provided below) implement a Stack. You must use the doubly
link list class and utilize it as an object in your implementation of the stack.
A Stack is a Last in First Out (LiFO) structure which translates to the processes of outputting the
last element which was inputted in the collection. The Stack is based on the process of putting
things on top of one another and taking the item on top (think of a stack of papers).
Operations to implement:
push (E): Add an element to the start of the sequence
pop: Remove an element from the start of the sequence
Peek: Return the first element of the sequence without removing it
atIndex(x): Return the element at the given index (x) Or throw an exception if it is out of bound
(if you can control the user input then do that instead)
Size: Return the size of the Stack
isEmpty: Boolean, returns true if the Stack is empty
Empty: Empty the Stack
Code Part 1:
public class DoublyLinkedList{
private DNode head;
private DNode tail;
private int size;
public DoublyLinkedList(){ // construct an empty list
this.tail = new DNode (null, null, this.head);
this.head = new DNode (null, this.tail, null);
this.size = 0;
}
public DoublyLinkedList(DNode next){ // constructs a list
// out of a single node
this.tail = new DNode (null, null, next);
this.head = new DNode (null, next, null);
next.changeNext(this.tail);
next.changePrev(this.head);
this.size = 1;
}
public DoublyLinkedList(Object [] objectArray){ // construct a list out of
// an array
this.tail = new DNode (null, null, this.head);
this.head = new DNode (null, this.tail, null);
DNode temp = this.head;
for (Object e : objectArray)
{
//Anonomus function
new DNode (e, temp.getNext(),temp).insertBetweenNodes(temp, temp.getNext());
temp = temp.getNext();
this.size += 1;
}
}
public void addToFrontofList(Object toAdd){ // Appends the begining
// of the list
DNode temp = new DNode (toAdd, this.head.getNext(), this.head);
this.head.getNext().changePrev(temp);
this.head.changeNext(temp);
this.size += 1;
}
public void addToendofList (Object toAdd) // appends the end of the list
// with a node
{
DNode temp = new DNode (toAdd, this.tail, this.tail.getPrev());
this.tail.getPrev().changeNext(temp);
this.tail.changePrev(temp);
this.size += 1;
}
public void insertAfterNode(DNode current, Object input)// Inserts a new
// a new node after
// current node
{
current.insertAfterNode(input);
this.size += 1;
}
public int getSize() // returns the size of the list
{
return this.size;
}
public String toString()
{
String result = \"\";
for (DNode temp = this.head.getNext();
temp.hasNext(); temp = temp.getNext())
{
result += temp.getValue();
result += \" -> \";
}
result += \"End of list\";
return result;
}
}
and code part2:
public class DNode{
private Object e; // place holder for the type of object the
//collection is storing
private DNode next; // reference to the next node in the sequence
// of.
Can you please debug this Thank you in advance! This program is sup.pdfFashionBoutiquedelhi
Can you please debug this? Thank you in advance! This program is supposed to use stacks and
find the paths of an airplane. It should tell you whether or not the plane goes from the requested
city to the requested destination. requestFile.txt contains the requests, flightFile.txt contains the
flights and cityFile.txt contains the city\'s that the airline serves.
My errors: my output is simply \"Hpair does not serve Los Angeles.\" Thats it and it stops.
It should look something like (these are not real values of the file just an example):
\"Request is to fly from cityA to CityB.
Hpair flight from cityA to CityB.
Request is to fly from cityC to cityD.
Sorry, HPAir does not serve City D
Request is to fly from cityE to CityF
Sorry, HPAir does not fly from cityE to CityF\"
**It said to use ispath.cpp but I got confused on how to implement it completely.\"
isPath.cpp
//***I did not include ispath.cpp in my program. Parts of it are in the map.h portion.
main.cpp
#include
#include
#include \"Map.h\"
using namespace std;
int main()
{
Map aMap;
aMap.readFlights();
aMap.verifyRequestedFile();
}
StackInterface.h
#ifndef StackInterface_h
#define StackInterface_h
template
class StackInterface
{
/** Checks if the stack is empty.
@return True if the stack is empty or false if the stack is not.*/
virtual bool isEmpty() const = 0;
/** Adds a new item to the stack
@post newEntry is at the top of the stack
@param newEntry is the object to be added to the stack
@return True if successfully added, otherwise false. */
virtual bool push(const ItemType& newEntry) = 0;
/** Removes item from stack
@post The top item in the stack is removed
@return True if the item was removed, false if it was not. */
virtual bool pop() = 0;
/** Returns the top item in the stack
@pre The stack is not empty
@post The top item in the stack is returned
@return The top of the stack */
virtual ItemType peek() const = 0;
};
#endif /* StackInterface_h */
Node.h
#ifndef node_h
#define node_h
template
class Node {
public:
Node();
Node (const ItemType &anItem);
Node(const ItemType &anItem, Node * nextNodePtr);
void setItem(const ItemType &anItem);
void setNext(Node * nextNodePtr);
ItemType getItem() const;
Node* getNext() const;
private:
ItemType item;
Node* next;
};
template
Node::Node():next(nullptr){}
template
Node::Node(const ItemType &anItem):item(anItem), next(nullptr){}
template
Node::Node(const ItemType &anItem, Node * nextNodePtr):item(anItem), next(nextNodePtr)
{
}
template
void Node::setItem(const ItemType &anItem){
item = anItem;
}
template
void Node::setNext(Node * nextNodePtr) {
next = nextNodePtr;
}
template
ItemType Node::getItem() const {
return item;
}
template
Node* Node::getNext()const{
return next;
}
#endif /* node_h */
LinkedStack.h
#include
#ifndef LinkedStack_h
#define LinkedStack_h
#include \"Node.h\"
#include \"StackInterface.h\"
template
class LinkedStack:public StackInterface{
public:
LinkedStack();
LinkedStack(const LinkedStack &aStack); //space matter?***********
virt.
Please review my code (java)Someone helped me with it but i cannot.pdffathimafancyjeweller
Please make it to clear 12-95. The basketball passed through the hoop even though it barely
cleared the hands of the player B who attempted to block it. Neglecting the size of the ball,
determine the magnitude vn of its initial velocity and the height h of the ball when it passes over
player B 10 ft 5 ft Prob. 12-95
Solution
Consider the motion along horizontal direction
Vox = initial velocity in horizontal direction = Va Cos30
X = horizontal distance = 25 + 3 = 28 ft
t = time taken
t = X / Vox = 28/(Va Cos30) eq-1
consider the motion in vertical direction
Y = vertical displacement = 10 - 7 = 3 ft
a = acceleration = - 32.2
Voy = initial velocity = Va Sin30
t = time taken
using the equation
Y = Voy t + (0.5) a t2
3 = (Va Sin30) (28/(Va Cos30)) + (0.5) (- 32.2) (28/(Va Cos30))2
Va = 35.8 m/s
t\' = time taken to reach B = 25 / (Va Cos30) = 25 / (35.8 Cos30) = 0.81 sec
h = 7 + Voy t\' + (0.5) a t\'2
h = 7 + (35.8 Sin30) (0.81) + (0.5) (- 32.2) (0.81)2
h = 10.94 ft.
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
Required to augment the author's Binary Search Tree (BST) code to support these new operations. Method names below are merely suggestions. (The author’s class is attached separately in the file called “authordoc”. I just built a simple test tree in the author’s main method which can be used to test the various operations. )
1. AnyType nthElement(int n) -- returns the n-th element (starting from 1) of the in-order traversal of the BST.
2. int rank( AnyType x ) -- returns the "rank" of x. The rank of an element is its position (starting with 1) in an in-order traversal.
3. AnyType median( ) -- returns the median (middle) element in the BST. If the BST contains an even number of elements, returns the smaller of the two medians.
4. boolean isPerfect( ) -- returns true if the BST is a perfect binary tree.
5. boolean isComplete( ) -- returns true if the BST is a complete binary tree.
6. String toString( int nrLevels ) -- generates the level-order output described in the sample output below.
Most of these operations could easily be implemented by performing an in-order traversal inside the BST and perhaps placing the results in an ArrayList. However, such a method is extremely inefficient. Instead, we are going to achieve faster performance by "augmenting" the BST nodes. You will add a new private integer data member ("tree size") to the BinaryNode which stores the size of the tree rooted at that node (including the root). You must develop your own algorithms for these operations, but obviously you will use the new tree size data member to guide your search. Think before you code and think recursively!
These items cover those topics not addressed elsewhere in the project description. (R) indicates a requirement, (H) indicates a hint, and (N) indicates a note.
1. (R) Although we are only using the BST for integers, the BST must remain a generic class.
2. (R) Duplicate values are not allowed. Attempts to insert a duplicate value should be ignored.
3. (R) Attempts to remove non-existent values should be ignored.
4. (R) From a coding perspective, the easiest way to avoid duplicate insertions or attempting to remove non-existent elements is to first call find( ). However, this technique is NOT permitted for two reasons.
Calling find( ) before each insert/remove doubles the running time for these operations and is therefore inefficient.
Recusively coding the insert/remove methods to handle these situations is a great learning experience.
5. (R) The level order print (PRINT command) outputs the value of each node, the size of the tree rooted at that node, and the value of the node's parent in that order, inside parenthesis, separated by commas. (node value, tree size, parent value). Since the root has no parent, print NULL for the root's parent value. For readability, separate the levels with a blank line and print no more than 6 node/size/parent values per line. If a level requires multiple lines, use consecutive lines (without a blank line between the ...
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
New folder/jsjf/ArrayStack.classpackage jsjf;
publicsynchronizedclass ArrayStack implements StackADT {
privatestaticfinal int DEFAULT_CAPACITY = 100;
private int top;
private Object[] stack;
public void ArrayStack();
public void ArrayStack(int);
public void push(Object);
private void expandCapacity();
public Object pop() throws exceptions.EmptyCollectionException;
public Object peek() throws exceptions.EmptyCollectionException;
public int size();
public boolean isEmpty();
public String toString();
}
New folder/jsjf/ArrayStack.javaNew folder/jsjf/ArrayStack.javapackage jsjf;
import jsjf.exceptions.*;
import java.util.Arrays;
// -------------------------------------------------------
// Author: Yifu Wu
// Date: 03/10/16
// Source Name: ArrayStack<T>
// Due date: 03/10/16
// Description:
/**
* An array implementation of a stack in which the bottom of the
* stack is fixed at index 0.
*
* @author Java Foundations
* @version 4.0
*/
publicclassArrayStack<T>implementsStackADT<T>
{
privatefinalstaticint DEFAULT_CAPACITY =100;
privateint top;
private T[] stack;
/**
* Creates an empty stack using the default capacity.
*/
publicArrayStack()
{
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty stack using the specified capacity.
* @param initialCapacity the initial size of the array
*/
publicArrayStack(int initialCapacity)
{
top =0;
stack =(T[])(newObject[initialCapacity]);
}
/**
* Adds the specified element to the top of this stack, expanding
* the capacity of the array if necessary.
* @param element generic element to be pushed onto stack
*/
publicvoid push(T element)
{
if(size()== stack.length)
expandCapacity();
stack[top]= element;
top++;
}
/**
* Creates a new array to store the contents of this stack with
* twice the capacity of the old one.
*/
privatevoid expandCapacity()
{
//stack = Arrays.copyOf(stack, stack.length * 2);
System.out.println("Expanding stack capacity\n");
T[] temp =(T[])(newObject[2*top]);
for(int i=0; i< top; i++)
temp[i]= stack[i];
stack = temp;
}
/**
* Removes the element at the top of this stack and returns a
* reference to it.
* @return element removed from top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T pop()throwsEmptyCollectionException
{
if(isEmpty())
thrownewEmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top]=null;
return result;
}
/**
* Returns a reference to the element at the top of this stack.
* The element is not removed from the stack.
* @return element on top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T peek()throwsEmptyCollectionException
{
if(isEmpty())
thrownewEmptyCollectionException("stack");
return stack[top-1];
}
/**
* Returns the number of elements in ...
Hi, Please find my code.I have correted all of your classes.Plea.pdfpritikulkarni20
Hi, Please find my code.
I have correted all of your classes.
Please let me know in case if do not get concpt.
######## Node.java ###########
public class Node {
private E element;
private Node next;
public Node() {
this.element = null;
this.next = null;
}
public Node(E e) {
this.element = e;
this.next = null;
}
public E getElement() {
return this.element;
}
public void setElement(E element) {
this.element= element;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
########## Stack.java #############
public class Stack {
private int N;
private Node top;
public Stack() {
N = 0;
this.top =null;
}
/*
* places element on the top of the stack
*/
public void push(E element){
Node temp = new Node(element);
temp.setNext(top);
top = temp;
N++;
}
/*
* remove the top node and return its contents
*/
public E pop(){
if(top == null)
return null;
E e = top.getElement();
top = top.getNext();
N--;
return e;
}
/*
* Look at the top element of the Stack and return it, without removing
*/
public E peek(){
if(top == null)
return null;
return top.getElement();
}
//returns the size of the stack
public int size(){
return N; //replace
}
public boolean isEmpty(){
return top==null;
}
}
############ Queue.java ############
public class Queue {
private Node front;
private Node back;
private int N;
public Queue() {
this.front = null;
this.back = null;
N = 0;
}
/*
* places element in the back of the Queue
*/
public void enqueue(E element){
Node temp = new Node(element);
if(front == null) {
front = temp;
back = temp;
}
else{
back.setNext(temp);
back = temp;
}
N++;
}
/*
* remove the front node of the queue and return it
*/
public E dequeue(){
if(front == null) {
return null;
}
E item = front.getElement();
front = front.getNext();
// if we had only one element
if(front == null){
back = null;
}
N--;
return item;
}
/*
* Look at the front of the queue and return it, without removing
*/
public E peek(){
if(back == null)
return null;
return back.getElement();
}
//returns the size of the queue
public int size(){
return N;
}
public boolean isEmpty(){
return front==null;
}
}
########### Palindrome.java ############
import java.util.Scanner;
public class Palindrome
{
public static void main(String[ ] args)
{
Scanner input = new Scanner(System.in);
String inputString;
System.out.print(\"Please enter your string: \");
inputString = input.next( );
if (isPalindrome( inputString )){
System.out.println(\"Yes it is a palindrome.\");
}
else{
System.out.println(\"No this is not a palindrome.\");
}
}
public static boolean isPalindrome(String input)
{
Queue q = new Queue ();
Stack s = new Stack ();
char letter;
int i;
for (i = 0; i < input.length( ); i++)
{
letter = input.charAt(i);
q.enqueue(letter);
s.push(letter);
}
while (!q.isEmpty( ))
{
if (q.dequeue() != s.pop( ))
return false;
}
return true;
}
}
/*
Sample Output:
Please enter your string: MadaM
Yes it is a palindrome.
*/
Solution
Hi, Please find my code.
I have correted all of your classes.
Pl.
In this lab, you will be given a simple code for a min Heap, and you.pdfcharanjit1717
In this lab, you will be given a simple code for a min Heap, and youre going to complete some of
the methods to handle some edge cases. Tasks for today: There are mainly two tasks, and the
logic of both of them is provided in their bodies: 1) Fully implement AddItem(). 2) Fully
implement HeapUp() Use the following start-up code. The main code and a demo class are
provided as .cs files. Use them to test your code. Once you complete the above two tasks, upload
the source code for your MinHeap class to Blackboard. class BinaryHeap : IEnumerable where T
: IComparable { private T[] array; private int count; // Number of elements (nodes) public
BinaryHeap(int size) { array = new T[size]; count = 0; } public T GetItem(int index) { return
array[index]; } private void SetItem(int index, T value) { while (index >= array.Length)
Grow(array.Length * 2); array[index] = value; } private void Grow(int newsize) {
Array.Resize(ref array, newsize); } // Indices of left and right children private int
LeftChildIndex(int pos) { return 2 * pos + 1; } private int RightChildIndex(int pos) { return 2 *
pos + 2; } private int GetParentIndex(int pos) => (pos - 1) / 2; private T GetRightChild(int pos)
=> array[RightChildIndex(pos)]; private T GetLeftChild(int pos) => array[LeftChildIndex(pos)];
private T GetParent(int pos) => array[GetParentIndex(pos)]; // "Has" methods to determine if the
indices exist private bool HasLeftChild(int pos) { if (LeftChildIndex(pos) < count) return true;
else return false; } private bool HasRightChild(int pos) { if (RightChildIndex(pos) < count)
return true; else return false; } private bool IsRoot(int pos) => pos == 0; // (true if element is
root) // Swap, uh, swaps two values given two indicies. This should be private but I originally
had it public for some reason. private void Swap(int position1, int position2) { T first =
array[position1]; array[position1] = array[position2]; array[position2] = first; } public void
AddItem(T value) { // This is part of la //Insert Logic // If the tree is empty, insert at the bottom
(it does that already) // if not, insert at the end, // From the end you either need to swap to the
root, and keep minheapify (Heapdown) // or, you should probably implement move up (for lab 6,
you need to implement // for that you run a while loop, check if the current position both isn't the
root, and is higher priority than a parent (in this case that probably means it's a lower value) // if
it is, swap with parent, and keep doing that until it's its in the array[count] = value; count++;
ReCalculateUp(); } private void HeapDown() { //CompareTo //this.CompareTo(value) returns <
0 if this < value //this.CompareTo(value) returns >0 if this > value int index = 0; while
(HasLeftChild(index)) { var smallerIndex = LeftChildIndex(index); if (HasRightChild(index)
&& (GetRightChild(index).CompareTo(GetLeftChild(index))<0) ) //there's a set of ( ) around the
right expression that are redundant but hopefully easier to read { smallerI.
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfFootageetoffe16
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding a reference to a node’s
parent, as shown below:
BST.TreeNode
#element
#left : TreeNode
#right: TreeNode
#parent: TreeNode
Implement the insert and delete methods in BST class to update the parent for each node in the
tree.
Add the following new method in BST:
/** Return the node for the specific element.
* Return null if the element is not in the tree. */
private TreeNode getNode(E element)
/** Returns true if the node for the element is a lead */
private boolean isLeaf(E element)
/** Returns the path of the element from the specific element to the root in an array list */
public ArrayList getPath(E e)
Write a test program that prompts the user to enter 10 integers, adds them to the tree, deletes the
first integer from the tree, and displays the paths for all leaf nodes.
Sample run
Enter 10 integers :
45 54 67 56 50 45 23 59 23 67
[50, 54, 23]
[59, 56, 67, 54, 23]
Solution
import java.util.NoSuchElementException; public class TreeSet> implements Set {
private TreeNode root; private int size; // Constructs an empty set. public
TreeSet() { root = null; size = 0; } // Adds the given value to this
set, if it was not already in the set. // If the element is already a member of this set, adding it
again has no effect. public void add(E value) { root = add(root, value); }
// private recursive helper for add // uses the \"x = change(x)\" pattern: // pass in
current state of root // return out desired new state of root private TreeNode
add(TreeNode node, E value) { if (node == null) { node = new
TreeNode(value); // reached dead end; put new node here size++; }
else if (value.compareTo(node.data) > 0) { node.right = add(node.right, value);
} else if (value.compareTo(node.data) < 0) { node.left = add(node.left,
value); } // else a duplicate; do nothing return node; } // Returns
true if this set contains the given element value. public boolean contains(E value) {
return contains(root, value); } // private recursive helper for contains private
boolean contains(TreeNode node, E value) { if (node == null) { return
false; } else if (value.compareTo(node.data) > 0) { return
contains(node.right, value); } else if (value.compareTo(node.data) < 0) {
return contains(node.left, value); } else { // value.equals(root.data);
found it! return true; } } // Returns the minimum value in this
set. // Throws a NoSuchElementException if this set is empty. public E getMin() {
if (root == null) { throw new NoSuchElementException(\"empty tree\");
} return getMin(root); } // private recursive helper for getMin
private E getMin(TreeNode node) { if (node.left == null) { return
node.data; } else { return getMin(node.left); } }
// Returns true if this set does not contain any elements. public boolean isEmpty() {
return size == 0; } // Prints all elements of this tree in a left-to-right order (in-order)
traversal. public void print() { print(root); } // private recursive helper
for print private void print(TreeNode .
On the code which has a class in which I implementing a binary tree .pdfwasemanivytreenrco51
On the code which has a class in which I implementing a binary tree using an array. This array,
named store, stores Node in entries corresponding to
nodes in the tree and null if the node does not exist. Complete the countLeavesmethod so that it
returns the number of leaves in this tree.
Code:
Solution
import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import
java.util.NoSuchElementException; /** * Implementation of an abstract set using an array-
based binary tree. This is * used to help teach binary tree\'s and will have more details explained
in * future lectures. * * @author William J. Collins * @author Matthew Hertz * @param
Data type (which must be Comparable) of the elements in this tree. */ public class
ArrayBinaryTree> extends AbstractSet { /** Entry in the data store where the root node can be
found. */ private static final int ROOT = 0; /** Array used to store the nodes which consist of
this binary tree. */ protected Node[] store; /** Number of elements within the tree. */
protected int size; /** * Initializes this ArrayBinaryTree object to be empty. This creates the
array * in which items will be stored. */ @SuppressWarnings(\"unchecked\") public
ArrayBinaryTree() { store = new Node[63]; size = 0; } /** * Initializes this
ArrayBinaryTree object to contain a shallow copy of a * specified ArrayBinaryTree object.
The worstTime(n) is O(n), where n is the * number of elements in the specified
ArrayBinaryTree object. * * @param otherTree The tree which will be copied to create our
new tree, */ @SuppressWarnings(\"unchecked\") public ArrayBinaryTree(ArrayBinaryTree
otherTree) { store = (Node[]) Arrays.copyOf(otherTree.store, otherTree.store.length); size =
otherTree.size; } public int countLeaves() { } /** * Returns the size of this
ArrayBinaryTree object. * * @return the size of this ArrayBinaryTree object. */
@Override public int size() { return size; } /** * Returns an iterator that will return the
elements in this ArrayBinaryTree, * but without any specific ordering. * * @return Iterator
positioned at the smallest element in this ArrayBinaryTree * object. */ @Override
public Iterator iterator() { return new ArrayTreeIterator(); } /** * Determines if there is at
least one element in this ArrayBinaryTree object * that equals a specified element. The
worstTime(n) is O(n) and * averageTime(n) is O(log n). * * @param obj - the element
sought in this ArrayBinaryTree object. * @return true - if there is an element in this
ArrayBinaryTree object that * equals obj; otherwise, return false. * @throws
ClassCastException - if obj cannot be compared to the elements in * this
ArrayBinaryTree object. * @throws NullPointerException - if obj is null. */ @Override
public boolean contains(Object obj) { return getEntry(obj) != null; } /** * Ensures that
this ArrayBinaryTree object contains a specified element. The * worstTime(n) is O(n) for this
addition. * * @param element Element we want to be certain is contained within.
package com.java2novice.ds.linkedlist;
import java.util.NoSuchElementException;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
/**
* this class keeps track of each element information
* @author java2novice
*
*/
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
/**
* returns the size of the linked list
* @return
*/
public int size() { return size; }
/**
* return whether the list is empty or not
* @return
*/
public boolean isEmpty() { return size == 0; }
/**
* adds element at the starting of the linked list
* @param element
*/
public void addFirst(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
/**
* adds element at the end of the linked list
* @param element
*/
public void addLast(E element) {
Node tmp = new Node(element, null, tail);
if(tail != null) {tail.next = tmp;}
tail = tmp;
if(head == null) { head = tmp;}
size++;
System.out.println(\"adding: \"+element);
}
/**
* this method walks forward through the linked list
*/
public void iterateForward(){
System.out.println(\"iterating forward..\");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}
/**
* this method walks backward through the linked list
*/
public void iterateBackward(){
System.out.println(\"iterating backword..\");
Node tmp = tail;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.prev;
}
}
/**
* this method removes element from the start of the linked list
* @return
*/
public E removeFirst() {
if (size == 0) throw new NoSuchElementException();
Node tmp = head;
head = head.next;
head.prev = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
/**
* this method removes element from the end of the linked list
* @return
*/
public E removeLast() {
if (size == 0) throw new NoSuchElementException();
Node tmp = tail;
tail = tail.prev;
tail.next = null;
size--;
System.out.println(\"deleted: \"+tmp.element);
return tmp.element;
}
public static void main(String a[]){
DoublyLinkedListImpl dll = new DoublyLinkedListImpl();
dll.addFirst(10);
dll.addFirst(34);
dll.addLast(56);
dll.addLast(364);
dll.iterateForward();
dll.removeFirst();
dll.removeLast();
dll.iterateBackward();
}
}
Solution
package com.java2novice.ds.linkedlist;
import java.util.NoSuchElementException;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
/**
* this class keeps track of each element information
* @author java2novice
*
*/
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
/**
* returns the size of the l.
According to the IRS, 1.1 of tax returns will be audited in 2011. A.pdfxlynettalampleyxc
According to the IRS, 1.1% of tax returns will be audited in 2011. A random sample of 40 tax
returns was selected. Use the Poisson distribution to approximate the binomial distribution to
determine the probability that more than two of these tax returns will be audited.0.1215
Solution
for poisson distribution, mean = np = 40(0.011) = 0.44
by using excel function =1-POISSON(1,0.44,1), P(x>=2) = 0.0726.
Write a SELECT statement that returns a single value that represents.pdfxlynettalampleyxc
Write a SELECT statement that returns a single value that represents the sum of the largest
unpaid invoices submitted by each vendor. Use a common table expression(cte) that returns
MAX(InvoiceTotal) grouped by VendorID, filtering for invoices with a balanced due.
Solution
WITH INVOICE_CTE (VendorID,maxInvoiceTotal)
AS
(
Select VendorID,MAX(InvoiceTotal) as maxInvoiceTotal
from Invoice
where due>0
)
Select MAX(maxInvoiceTotal) from
INVOICE_CTE.
which represents the ground state for the N- ion i. w.ia ere sm.pdfxlynettalampleyxc
which represents the ground state for the N- ion
i. w.ia ere sms he Morral su rrie ...dae ... lilili
Solution
The ground state for the N- ion
option e..
The ground state of an atom or ion is the state in which all its electrons are found in the possible
lowest energy orbitals .
your rest of the image of questions are not clear ..
What is the ecological and environmental importance of salinityoxyg.pdfxlynettalampleyxc
What is the ecological and environmental importance of salinity/oxygen consumption of grass
shrimp?
Solution
Grass shrimp acts as detritivores,grass shrimp aid in the mechanical break down of organic
matter such as fibrous plant materials into tiny particles that are suspended in the water column,
and thus provides rich food source for smaller organisms. Predation : In estuaries, numerous fish
species and other aquatic carnivores , eat large quantities of grass shrimp. Grass shrimp are hosts
for numerous species of parasites and ectocommensals. Grass shrimp is pollution tolerant and
live in areas of high salinity. It consumes algae and seagrasses, therefore plays an important role
in the ecology of the estuary..
WEP has vulnerabilities. Which of the following is not a reason why .pdfxlynettalampleyxc
WEP has vulnerabilities. Which of the following is not a reason why it is vulnerable?
A. Shared WEP keys among all clients
B. An RC4 engine not properly initialized
C. 20-bit initialization vector
D. 40-bit WEP keys
Solution
C. One issue with WEP is the initialization vector (IV), it was 24 bits, not 20. Answers A, B, and
D detail some of the vulnerabilities of WEP. For example, WEP uses a single shared key among
all clients, which means that you are authenticating groups, not devices or single users. Also,
RC4 is the correct encryption type and can be implemented in 40- or 104-bit configuration, but
WEP does not properly initialize it. This means that the key values roll over and are predictable.
Finally, a 24-bit IV vector is too short, and a 40-bit key is weak..
Two astronauts are 2.40 m apart in their spaceship. One speaks to the.pdfxlynettalampleyxc
Two astronauts are 2.40 m apart in their spaceship. One speaks to the other. The conversation is
transmitted to earth via electromagnetic waves. The time it takes for sound waves to travel at 343
m/s through the air between the astronauts equals the time it takes for the electromagnetic waves
to travel to the earth. How far away from the earth is the spaceship Number Units
Solution
time taken by sound to travel 2.40 m,
t = 2.40 / 343 s
spaceship is at the distance at light can travel in time t.
distance = speed x time
= (3 x 10^8 ) (2.40 / 343)
= 2.099 x 10^6 m.
The ratio of the probability of disease in an exposed group to the p.pdfxlynettalampleyxc
The ratio of the probability of disease in an exposed group to the probability of disease in an
unexposed group is called the: 1. Relative risk 2. Odds ratio 3. Risk difference 4. Attributable
risk
Solution
The ratio of the probability of disease in an exposed group to the probability of disease in an
unexposed group is called relative risk.
RR=P(diseased/exposed)/P(diseased/unexposed).
The output should now look like this Row 1 sum 30 Row 2 sum.pdfxlynettalampleyxc
The output should now look like this:
Row 1 sum: 30
Row 2 sum: 48
Row 3 sum: 55
Count: 12
Grand total: 133
Mean: 11.08
Even numbers: 7
Odd numbers: 5
How to add even and odd numbers counts to existing code
public class Problem {
public static void main(String [] args)
{
int iVal;
int iRow;
int iRowSum;
int iToken;
int totalSum = 0;
int totalEle = 0;
iRowSum = 0;
iRow = 1;
try
{
Scanner ifsInput = new Scanner(new File(\"c:\\home\\student\\lastname/9_1_Input.txt\"));
while(ifsInput.hasNextLine())
{
while(ifsInput.hasNextInt())
{
for(iToken = 0; iToken <= 3; iToken++)
{
iVal = ifsInput.nextInt();
iRowSum = iRowSum + iVal;
// increasing count of total element
totalEle++;
}
// adding into totalSum
totalSum = totalSum + iRowSum;
System.out.println(\"Row \" + iRow + \" sum: \" + iRowSum);
iRowSum = 0;
iRow++;
}
}
// added new code to print grand total and mean value
System.out.println(\"Count: \"+totalEle);
System.out.println(\"Grand total: \"+totalSum);
System.out.println(\"Mean: \"+String.format(\".2f\", (double)/totalSum/totalEle);
}
catch (FileNotFoundException sMsg)
{
System.out.println(\"The file cannot be found or opened.\");
}
}
}
Solution
Input999.txt( Save this file under D Drive Then the path of the file pointing to it is
D:\\\\Input999.txt)
11 22 33 44
22 33 44 55
33 44 55 66
___________________________
Problem.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Problem {
public static void main(String [] args)
{
//Declaring variables
int iVal;
int iRow;
int iRowSum;
int iToken;
double mean=0.0;
int evenCount=0,oddCount=0;
int totalSum = 0;
int totalEle = 0;
iRowSum = 0;
iRow = 1;
try
{
Scanner ifsInput = new Scanner(new File(\"D:\\\\Input999.txt\"));
while(ifsInput.hasNextLine())
{
while(ifsInput.hasNextInt())
{
for(iToken = 0; iToken <= 3; iToken++)
{
iVal = ifsInput.nextInt();
//Calculating the even count
if(iVal%2==0)
evenCount++;
//Calculating the odd count
else
oddCount++;
//Calculating the sum of elements in each row
iRowSum = iRowSum + iVal;
// increasing count of total element
totalEle++;
}
// adding into totalSum
totalSum = totalSum + iRowSum;
//Displaying the sum of elements in each row
System.out.println(\"Row \" + iRow + \" sum: \" + iRowSum);
iRowSum = 0;
iRow++;
}
}
//Displaying the number of elements
System.out.println(\"Count: \"+totalEle);
//Displaying the sum of all elements
System.out.println(\"Grand total: \"+totalSum);
//Calculating the mean
mean=(double)totalSum/totalEle;
//Displaying the mean
System.out.printf(\"Mean: %.2f\ \",mean);
//Displaying the number of even nos
System.out.println(\"Even Numbers :\"+evenCount);
//Displaying the number of odd nos
System.out.println(\"Odd Numbers :\"+oddCount);
}
catch (FileNotFoundException sMsg)
{
System.out.println(\"The file cannot be found or opened.\");
}
}
}
_________________________________
Output:
Row 1 sum: 110
Row 2 sum: 154
Row 3 sum: 198
Count: 12
Grand total: 462
Mean: 38.50
Even Numbers :6
Odd Numbers :6
______.
The end problem in eukaryotic DNA replicationa. is solved by t.pdfxlynettalampleyxc
The \"end problem\" in eukaryotic DNA replication
a. is solved by telomerase
b. refers to loss of chromosome ends during replication
c. is solved by an RNA dependent DNA polymerase
d. A and B
e. all of the above
Solution
Answer : The correct answer is E ( All of the above)
Explanation :
Telomerases are the ribonucleoprotein complexes containing a small RNA that serves as a
template for addition of new six nucleotide repeats. Or Telomerase, the enzyme that synthesizes
the telomere ends of linear chromosomes, is a specialized reverse transcriptase that contains an
internal RNA template. Telomeres undergo cycles of shortening of the lagging strands due to the
inability to complete synthesis.
Most normal cells lose telomerase activity with increaseing age of the organism and repeated
generations of the cell division. In other words, after certain number of divisions normal cells
reaches the Hayflicks limit beyond which cells will no longer devide instead they die.
In germ-line cells, which contain telomerase activity, telomere lengths are maintained; for
example, telomerase is highly expressed only in cells that need to divide regularly especially in
male sperm cells. Whereas somatic cells lack telomerase activity due to which they die after
certain number of generations.
In cancer cells/tumor cells, end replication problems observed in normal cells will be taken care
by the telomerase enzyme which makes the cells to bypass the Hayflick limit and become
immortal, thus avoiding cell death Many cancer cells are considered \'immortal\' because
telomerase activity supports them to live longer than somatic cells. 90% of the cancer cells retain
the ability to express telomerase and acquires the ability to proloferate indefinitely..
Suppose that one obtained the following DNA sequence data for the fou.pdfxlynettalampleyxc
Suppose that one obtained the following DNA sequence data for the four fly families and a non-
fly insect (the outgroup) from a gene that is not related to morphology. We will call the DNA
sequence positions 1 through 10, for reference (in fly family A, position 1 is a T, while position
10 is an A). Which of the characters (nucleotide positions) are variable among the fly families
(not counting the outgroup? Which of the characters (nucleotide positions) are phylogenetically
informative for cladistics? (Phylogenetically informative traits are those for which there is
variation in the group of interest, and for which there is evidence of synapomorphies.)
Solution
Purines are 2 ringed structure= A,G whereas, pyramidines aresingle ringed structure = C,T
Generally A = T (A double bonds with T) and G=C (G triple H bonds with C).
Mutation causes a change in theDNA sequence. Two types
1. Transversions: Purine instead of a pyramidine or vice versa (Less frequent so more important
for cladistics) A/G to C/T or vice versa. 2 ringed structure to 1 ringed structure
See this is seen in all fly families at 7th(ABCD:AGGC) , 8th (ABCD:CTAC) and 9th
(ABCD:GCTG)positions
2. Transitions: Purine instead of a puirne and pyramidine instead of a pyramidine (Easy and
frequent)
The Nucleotide positions are Bolded in the table are variable among the fly families. Among all
Fly family C is most variable. (Take A, B, C, D and leave Out group).
Phylogenetically informative traits are those for which there is variation in the group of interest
and for which there is evidence of synapomorphies. All this is to know the members of a group
which share a common history and to know their closely related species. Synapomorphy means
any characteristic which is present in an ancestral species and that is shared exclusively (either in
more or less modified form) by its evolutionary descendants.
Mostly there is a much variation in the 7th, 8th and 9th position of the nucleotide in all fly
families sequence so this will be more phylogenetically informative for cladistics and the 5th
sequence is the most stable one. From the sequence fly family C is much more related to the out
group sequence than all familiesFLY FAMILYDNA Sequence alignedpositions
order12345678910ATGCGTTACGABTGCATTGTCACTCCGTAGATTDGCAGTTCCGAOU
T GROUPGCAGTTGATT.
Set up a JavaFX GUI-based program that shows a 10 times 10 grid of la.pdfxlynettalampleyxc
Set up a JavaFX GUI-based program that shows a 10 times 10 grid of labels that forms a
multiplication table, with the labels displaying the multiplication problems, rather than the
answers. Provide a text input field and a button with an event handler that reads an integer value
from the text input and changes the CSS styling in some obvious way for all problems in the
table with the given answer. When a new answer is entered and the button is clicked, change all
the labels back to the original style, then change the labels showing problems for the new answer
to the new style. Use CSS, not setters, for all the styling. The main point of this lab is to learn
JavaFX, so the grading will include a heavy emphasis on the neatness and general appearance of
your GUI.
Solution
Code:
//multiTable.java
// import required packages
import java.util.List;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
// class for revrse multiplication table
public class multiTable extends Application
{
// over ride nethod for setup the grid
@Override
public void start(Stage primaryStage)
{
BorderPane pane1 = new BorderPane();
pane1.setTop(getHbox1());
HBox h_box = new HBox(15);
h_box.setPadding(new Insets(15, 15, 15, 15));
h_box.setAlignment(Pos.TOP_CENTER);
h_box.getStyleClass().add(\"hbox2\");
Label labl = new Label(\"Enter Answer: \");
h_box.getChildren().add(labl);
TextField textfield1 = new TextField();
h_box.getChildren().add(textfield1);
GridPane grid_pane1 = setUpGrid();
gridmaker griddp = new gridmaker(grid_pane1);
Button Answer = new Button(\"Find problems\");
Answer.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler()
{
@Override
public void handle(Event arg0)
{
List fact = factors(textfield1);
for (int[] RCx1 : fact) {
Node node = griddp.get_chldren()[RCx1[0]][RCx1[1]];
node.setStyle(\"-fx-background-color: green\");
}
}
});
h_box.getChildren().add(Answer);
pane1.setCenter(h_box);
pane1.setBottom(grid_pane1);
Scene scene = new Scene(pane1, 550, 650);
scene.getStylesheets().add(getClass().getResource(\"application.css\").toExternalForm());
primaryStage.setTitle(\"lab 6\");
primaryStage.setScene(scene);
primaryStage.show();
}
// method for grid layout
private HBox getHbox1()
{
HBox hbox2 = new HBox(15);
hbox2.setPadding(new Insets(15, 15, 15, 15));
hbox2.setAlignment(Pos.TOP_CENTER);
hbox2.getStyleClass().add(\"hbox1\");
Label labl = new Label(\"Multiplication Table\");
hbox2.getChildren().add(labl);
return hbox2;
}
// method to setup a grid
public GridPane setUpGrid() {
GridPane pane1 = new GridPane();
Label[][].
Sample of DNA isolated from bacterium X contains 17.5 of adenine.pdfxlynettalampleyxc
Sample of DNA isolated from bacterium X contains 17.5% of adenine bases. What percentages
of guanine, thymine, and cytosine bases would you expect to find in the same sample of DNA?
Match the following types of transport across a biological membrane (designated I, II, or III)
with the statements designated A-D: Simple diffusion (SD) Facilitated diffusion (FD) Active
transport (AT) Write down your answers in the blank space next to each statement below. Note,
that more than one answer may apply each statement: Process is energy dependent: ___ Process
needs transmembrane transporter/channel: ___ Process occurs down the concentration gradient:
___ Processes can establish a concentration gradient: ___
Solution
Answer 2. Given that adenine bases in the isolated DNA of the bacterium is 17.5%. Since
Adenine is known to pair with thymine. So, the percentage of thymine will also be 17.5%.
Adenine and thymine will make 35 % of the total nitrogen bases of the DNA. Rest of the DNA
will be made from Guanine and Cytosine. Guanine and Cytosine are known to pair with each
other. So, their content in the DNA will also be same. 100-35% will give us 65 %. So Guanine
will be 32.5% and Cytosine will be 32.5%
Answer 3.
Process occur down the concentration gradient - Simple Diffusion(SD)
Process need transmembrane transporter/Channel- Facilitated Diffusion (FD)
Process is energy dependent- Active transport (AT)
Process can establish a concentration gradient- Facilitated Diffusion (FD) and Active transport
(AT).
Practice using layouts Anderson, Franceschi import javax..pdfxlynettalampleyxc
/* Practice using layouts
Anderson, Franceschi
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NestedLayoutPractice extends JFrame
{
private Container contents;
private Game game;
private BorderLayout bl;
private JLabel bottom;
// ***** Task 1: declare a JPanel named top
// also declare three JButton instance variables
// that will be added to the JPanel top
// these buttons will determine the grid size of the game:
// 3-by-3, 4-by-4, or 5-by-5
// Part 1 student code starts here:
private final JPanel top;
private JButton [] topButtones;
String [] topGridSize =
{\"3-by-3\",
\"4-by-4\",
\"5-by-5\",
};
private JButton reset;
// Part 1 student code ends here.
public NestedLayoutPractice()
{
super(\"Practicing layout managers\");
contents = getContentPane();
// ***** Task 2:
// instantiate the BorderLayout manager bl
// Part 2 student code starts here:
// set the layout manager of the content pane contents to bl:
// bl = new BorderLayout (); (not suer if this is right)
//set.BorderLayout(bl); (not suer if this is right)
game = new Game(3); // instantiating the GamePanel object
// add panel (game) to the center of the content pane
// Part 2 student code ends here.
bottom = new JLabel(\"Have fun playing this Tile Puzzle game\",
SwingConstants.CENTER);
// ***** Task 3:
// instantiate the JPanel component named top
// Part 3 student code starts here:
//top = new JPanle ();(not suer if this is right)
// set the layout of top to a 1-by-3 grid(not suer if this is right)
// panel.setLayout (new GridLayout (3, 1));(not suer if this is right)
// instantiate the JButtons that determine the grid size
// topButtones [0] = new JButton (\"3-by-3 \"); (not suer if this is right)
// add the buttons to JPanel top
//top.add (topButtones[0]);(not suer if this is right)
//top.add (topButtones[1]);
//top.add (topButtones[2]);
// add JPanel top to the content pane as its north component
c.add(top, \"north\");
// Part 3 student code ends here.
// ***** Task 5:
// Note: search for and complete Task 4 before performing this task
// Part 5 student code starts here:
// declare and instantiate an ActionListener
//topButtones[0].addActionListnere(this);(not suer if this is right)
//topButtones[1].addActionListnere(this);
//topButtones[2].addActionListnere(this);
// register the listener on the 3 buttons
// that you declared in Task 1
// Part 5 student code ends here.
contents.add(bottom, BorderLayout.SOUTH);
setSize(325, 325);
setVisible(true);
}
// ***** Task 4:
// create a private inner class that implements ActionListener
// your method should identify which of the 3 buttons
// was the source of the event
// depending on which button was pressed,
// call the setUpGame method of the Game class
// with arguments 3, 4, or 5
// the API of that method is:
// public void setUpGame(int nSides)
// At the end of the method call validate()
// Part 4 student code starts here:
public void actionPreformed(ActionEvent ae)
{
if (ae.getActionCommand(). equ.
Please, I need a correct answer and clear explanation. open image an.pdfxlynettalampleyxc
Please, I need a correct answer and clear explanation. open image and zoom for a clear view.
Thanks,
Using the West Jet Financial statements, answer the following questions R1 2-4 p.106-109)
b. Why do you think West Jet does not report a cost of goods sold
c. Explain what “Advanced ticket sales” in the current liabilities section represents
e. How much did West Jet use in 2013 to acquire new aircraft? Which statement did you find this
information on?
RI2-4
(Determination of items from a Canadian company\'s financial statements)
Calgary-based WestJet Airlines Ltd. provides services throughout Canada and to some
international destinations. Excerpts from its 2013 financial statements are in Exhibits 2-19A to 2-
19C.
Exhibit 2-19A WESTJET AIRLINES LTD.\'S 2013 CONSOLIDATED STATEMENT OF
EARNINGS
Consolidated Statement of Earnings
For the years ended December 31
(Stated in thousands of Canadian dollars, except per share amounts)
Note
2013
2012
Revenue:
Guest
3,337,569
3,133,492
Other
324,628
293,917
3,662,197
3,427,409
Operating expenses:
Aircraft fuel
1,039,448
992,787
Airport operations
459,465
424,911
Flight operations and navigational charges
410,052
376,050
Sales and distribution
356,988
333,106
Marketing, general and administration
222,567
202,398
Depreciation and amortization
200,840
185,401
Inflight
176,907
162,633
Aircraft leasing
175,646
173,412
Maintenance
169,197
154,406
Employee profit share
51,577
46,585
3,262,687
3,051,689
Earnings from operations
399,510
375,720
Non-operating income (expense):
Finance income
15
17,848
18,391
Finance cost
15
(43,447)
(48,900)
Gain on foreign exchange
1,136
1,061
Gain (loss) on disposal of property and equipment
(2,962)
469
Loss on fuel derivatives
—
(6,512)
(27,425)
(35,491)
Earnings before income tax
372,085
340,229
Income tax expense (recovery):
Current
154,964
66,230
Deferred
(51,601)
31,607
11
103,363
97,837
Net earnings
268,722
242,392
Exhibit 2-19B WESTJET AIRLINES LTD.\'S 2013 CONSOLIDATED STATEMENT OF
FINANCIAL POSITION
Consolidated Statement of Financial Position
At December 31
(Stated in thousands of Canadian dollars)
Note
2013
2012
Assets
Current assets:
Cash and cash equivalents
5
1,256,005
1,408,199
Restricted cash
6
58,106
51,623
Accounts receivable
19
42,164
37,576
Prepaid expenses, deposits and other
19
133,263
101,802
Inventory
19
36,722
35,595
1,526,260
1,634,795
Non-current assets:
Property and equipment
7
2,487,734
1,985,599
Intangible assets
8
58,691
50,808
Other assets
19
70,778
75,413
Total assets
4,143,463
3,746,615
Liabilities and Shareholders\' Equity
Current liabilities:
Accounts payable and accrued liabilities
19
543,167
460,003
Advance ticket sales
19
551,022
480,947
Non-refundable guest credits
19
46,975
47,859
Current portion of maintenance provisions
9
76,105
34,135
Current portion of long-term debt
10
189,191
164,909
1,406,460
1,187,853
Non-current liabilities:
Maintenance provisions
9
142,411
145,656
Long-term debt
10
689,204
574,139
Other liabilities
19
8,834
9,914
.
Patient 2 Patient #2 Jan Johnson Next, Dr. Gupta sees Jan Johnson. .pdfxlynettalampleyxc
Patient 2 Patient #2: Jan Johnson Next, Dr. Gupta sees Jan Johnson. She is a 12-year-old female.
She is in the 7th grade and has been on the school swim team for the past four years. She is a
good student and is generally a happy child. Lately, Jan\'s mother has been worried about her
daughter. Jan has been very irritable the past few months and at first, her mother thought it was
related to the onset of puberty. In addition to mood changes, Mrs. Johnson has also noted a few
other changes in Jan she is often too tired to attend swimming practice and has complained of
feeling too weak to swim and of having headaches. Despite her decreased physical activity, Jan
has been eating almost non-stop but has lost about 5 lbs, she is also drinking more than usual and
has been vomiting frequently. Jan saw her primary care physician, and after running some tests,
has sent Jan to follow up with Dr. Gupta. Jan\'s blood work and patient information from his
chart are listed below.
Solution
1.Jan is easily fatigued, eating too much (polyphagia) drinking too much water (polydipsia),
sudden weight loss and nausea are the symptoms. All these symptoms relate to the metabolic
disorder called Diabetes.
2.jan is having high blood glucose level than what is considered to be normal. This indicates the
insulin receptors have become resistant to insulin which is type 2 diabetes or adequate amounts
of insulin is not being secreted by the pancreas which is type 1 diabetes. If untreated, diabetes
can be life threatening in the long term. It leads to diabetic retinopathy, kidney parenchymal
changes, coronary artet disease, diabetic foot etc.
3. I must collect information about her diet, frequency of urination, recent injuries, family history
of diabetes, any blurred vision,..
Non-math and physics question, but engineering orientated.Identify.pdfxlynettalampleyxc
Non-math and physics question, but engineering orientated.
Identify and discuss what you know are the significant milestones in materials used for
commercial aircraft since the end of the Second World War?
Include the manufacturing, maintenance and reliability aspects if relevant.
Limit your answer to three principal types of material.
Provide essay answers with a maximum of 500 words. Use current APA format for all
references. (minimum of 3 references) Thanks!
Solution
On December 17, 1903, Orville and Wilbur Wright capped four years of research and design
efforts with a 120-foot, 12-second flight at Kitty Hawk, North Carolina - the first powered flight
in a heavier-than-air machine. Prior to that, people had flown only in balloons and gliders. The
first person to fly as a passenger was Leon Delagrange, who rode with French pilot Henri
Farman from a meadow outside of Paris in 1908. Charles Furnas became the first American
airplane passenger when he flew with Orville Wright at Kitty Hawk later that year.
Aircraft Innovations
For the airlines to attract passengers away from the railroads, they needed both larger and faster
airplanes. They also needed safer airplanes. Accidents, such as the one in 1931 that killed Notre
Dame Football Coach Knute Rockne along with six others, kept people from flying
Aircraft manufacturers responded to the challenge. There were so many improvements to aircraft
in the 1930s that many believe it was the most innovative period in aviation history. Air-cooled
engines replaced water-cooled engines, reducing weight and making larger and faster planes
possible. Cockpit instruments also improved, with better altimeters, airspeed indicators, rate-of-
climb indicators, compasses, and the introduction of artificial horizon, which showed pilots the
attitude of the aircraft relative to the ground - important for flying in reduced visibility.
designers already knew that as an aircraft approaches the speed of sound (Mach 1), in the
transonic region, shock waves begin forming, causing a large increase in drag. Wings, already
thin, had to become thinner and finer. Fineness is a measure of how thin the wing is compared to
its front-to-back chord. A small, highly loaded wing has less drag and so some early types used
this type, including the Bell X-1 rocket plane and the Lockheed F-104 Starfighter. But these craft
had high takeoff speeds, the Starfighter causing significant pilot deaths during takeoff, and small
wings fell out of use. An approach pioneered by German designers during the war was to sweep
the wing at an angle, delaying the buildup of shock waves. But this made the wing structure
longer and more flexible, making the aircraft more likely to suffer from bending or aeroelasticity
and even causing a reversal in the action of the flight controls. Stall behaviour of the swept wing
was also poorly understood and could be extremely sharp. Other problems included divergent
oscillations which could build up lethal forces. In re.
Name three properties of the waveform that can be changed with the m.pdfxlynettalampleyxc
Name three properties of the waveform that can be changed with the multifunction
synthesizer/function generator.
Solution
Produce sine triangular sawtoothvwave form ..
*it can generate wide range of frequencies cover .1 Hz to 11 KHz
*frquency stability .1 % to analog generator and 550 ppm for digital generator
Output voltage can be 10 v peak to peak.
Inventory Valuation FIFO, LIFO, and Average The company reported the.pdfxlynettalampleyxc
Inventory Valuation: FIFO, LIFO, and Average The company reported the following inventory
data for the year: Practice 9-7 Units Cost per Unit 300 $1750 Beginning inventory Purchases:
900 1,200 400 18.00 18.25 March 23. Units remaining at year-end. . . . . . .. Compute (1) cost of
goods sold and (2) ending inventory assuming (a) FIFO inventory valuation, (b)LIFOin- ventory
valuation, and (c) average cost inventory valuation. The company uses a periodic inventory
system Practice 9-8 Inventory Valuation: Complications with a Perpetual System Refer to
Practice 9-7. Assume that the sales occurred as follows: Units Sold 100 600 1,300 July 15
November 1 Total Compute (1) cost of goods sold and (2) ending inventory assuming (a) FIFO
inventory valuation, (b) LIFO inven- tory valuation, and (c) average cost inventory valuation,
The company uses a perpetual inventory system
Solution
Answer
Units sold = 2400 – 400 = 2000
FIFO
Cost of Goods available for sale
Cost of Goods Sold
Endging Inventory
Units
Cost/unit
COG for sale
Units sold
Cost/unit
COGS
Units
Cost/unit
Ending inventory
Beginning Inventory
300
17.5
5250
300
17.5
5250
0
17.5
0
Purchases:
Mar-23
900
18
16200
900
18
16200
0
18
0
Sep-16
1200
18.25
21900
800
18.25
14600
400
18.25
7300
TOTAL
2400
43350
2000
36050
400
7300
LIFO
Cost of Goods available for sale
Cost of Goods Sold
Endging Inventory
Units
Cost/unit
COG for sale
Units sold
Cost/unit
COGS
Units
Cost/unit
Ending inventory
Beginning Inventory
300
17.5
5250
0
17.5
0
300
17.5
5250
Purchases:
Mar-23
900
18
16200
800
18
14400
100
18
1800
Sep-16
1200
18.25
21900
1200
18.25
21900
0
18.25
0
TOTAL
2400
43350
2000
36300
400
7050
---Average Cost Valuation
Cost of opening units + Purchases = $43350
Opening units + Purchased units = 2400
Average cost = 43350 / 2400 = $18.0625 per unit
Cost of Goods Sold = 2000 units sold x $18.0625 = $36125
Value of ending Inventory = 400 units x $18.0625 = $7225
FIFO
Opening + Purchases
Cost of Goods Sold
Closing Inventory
Opening units
300
17.50
5250
300
17.50
5250.00
Jan 16 Sale
100
17.50
1750
200
17.50
3500.00
Mar 23 Purchase
900
18.00
16200
200
17.50
3500.00
900
18.00
16200.00
July 15 Sale
200
17.50
3500
500
18.00
9000.00
400
18.00
7200
Sept 16 Purchase
1200
18.25
21900
500
18.00
9000.00
1200
18.25
21900.00
Nov 1 Sale
500
18.00
9000
400
18.25
7300.00
800
18.25
14600
TOTAL
2400
43350
2000
36050
400
7300.00
Units
Value
Cost of Goods Sold
2000
36050
Closing Inventory
400
7300
LIFO
Opening + Purchases
Cost of Goods Sold
Closing Inventory
Opening units
300
17.50
5250
300
17.50
5250.00
Jan 16 Sale
100
17.50
1750
200
17.50
3500.00
Mar 23 Purchase
900
18.00
16200
200
17.50
3500.00
900
18.00
16200.00
July 15 Sale
600
18.00
10800
200
17.50
3500.00
0
0.00
0
300
18.00
5400.00
Sept 16 Purchase
1200
18.25
21900
200
17.50
3500.00
300
18.00
5400.00
1200
18.25
21900.00
Nov 1 Sale
1200
18.25
21900
200
17.50
3500.00
100
18.00
1800
200
18.00
3600.00
TOTAL
2400
43350.00
2000
36250.00
400
7100
Units
Value
Cost of Goods Sold
2000
36250
.
In December 2009, a 45-year-old female presented to the emergency dep.pdfxlynettalampleyxc
In December 2009, a 45-year-old female presented to the emergency department (ED) 2 days
following abrupt onset of sore throat, nonproductive cough, chills, and mild fever. A chest
radiograph was performed, which was normal. She was diagnosed with bronchitis and asked to
follow up with her primary care physician, who subsequently started her on levofloxacin and
albuterol. Four days later she presented again to the ED with worsening cough, dispread, fever
(38.3 degree C; 101 degree F), and generalized lethargy. Additionally, she reported new
symptoms including a global headache, dizziness, myalgias, and arthralgias. She had no
abdominal pain, but reported nausea and anorexia. Her chest radiograph showed diffuse
reticulonodular opacities throughout the left lung, which were not present on her visit 4 days
previously. The patient was admitted for further evaluation. Questioning revealed the following:
she had a history of diabetes and hypertension. she smoked an average of a pack of cigarettes
daily, and she had received the seasonal influenza vaccine. Her husband was recently ill with
cough, but no order symptoms. On day 2 of hospitalization the patient\'s respiratory rate
increased from 22 to 46 and her oxygen saturation dropped while on oxygen administered by
nasal canola. She was transferred to an intensive care unit, where her respiratory status quickly
deteriorated, necessitating emergency intubation. A new chest radiograph showed bilateral
involvement, and she was begun on vancomycin, anreonam, and azithromycin. Blood cultures
drawn on her admission were negative, and an expectorated sputum sample taken at the same
time was not processed due to poor specimen quality. A PCR test performed on a
nasopharyngeal swab was positive for a viral agent, revealing the etiology of her infection (Fig.
10.1). What is the agent causing her infection? What are the key virulence factors of this agent?
How does this virus change over time? What made this virus unique in 2009?
Solution
Answer= 1] The agent causing her infection is influenza virus
Human influenza virus can evolve rapidly by 2 mechanisms
1] antigenic shift = genetic reassortment between a human & non human virus in non human
host
2] antigenic drift = accumulation of mutations that facilitate evasion of host immune response
New influenza viruses can be constantly emeges from environment
2] influenza constantly change by 2 different ways
antigenic drift = These are small changes in genes of influenza viruses that happen continuously
over time
as the virus replicates
Antigenic shift = is an abrupt major changes resulting in hemagglutinin & neuraminidase
proteins in influenza viruses that infect humans
Such a shift occured in 2009 when H1N1 virus with a new combination of genes emerged to
infect people & quickly spread causing a pandemic
when shift happens most people has no protection against H1N1.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Honest Reviews of Tim Han LMA Course Program.pptxtimhan337
Personal development courses are widely available today, with each one promising life-changing outcomes. Tim Han’s Life Mastery Achievers (LMA) Course has drawn a lot of interest. In addition to offering my frank assessment of Success Insider’s LMA Course, this piece examines the course’s effects via a variety of Tim Han LMA course reviews and Success Insider comments.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
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.
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.
Overview on Edible Vaccine: Pros & Cons with Mechanism
For the code below complete the preOrder() method so that it perform.pdf
1. For the code below complete the preOrder() method so that it performs a preOrder traversal of
the tree. For each node it traverses, it should call sb.append() to add a "[" the results of
traversing the subtree rooted at that node, and then a "]". You should add a space before the
results of the left and right child traversals, but only if the node exists.
code:
Solution
In preorder Nodes visited are in the order of
code:
package edu.buffalo.cse116;
import java.util.AbstractSet;
import java.util.Iterator;
public class BinarySearchTree> extends AbstractSet {
protected Entry root;
protected int size;
/**
* Initializes this BinarySearchTree object to be empty, to contain only
* elements of type E, to be ordered by the Comparable interface, and to
* contain no duplicate elements.
*/
public BinarySearchTree() {
root = null;
size = 0;
}
/**
* Initializes this BinarySearchTree object to contain a shallow copy of a
* specified BinarySearchTree object. The worstTime(n) is O(n), where n is the
* number of elements in the specified BinarySearchTree object.
*
* @param otherTree - the specified BinarySearchTree object that this
* BinarySearchTree object will be assigned a shallow copy of.
*/
public BinarySearchTree(BinarySearchTree otherTree) {
root = copy(otherTree.root, null);
2. size = otherTree.size;
}
/* Method to complete is here! */
public void preOrder(Entry ent, StringBuilder sb) {
preorder(root)
protected Entry copy(Entry p, Entry parent) {
if (p != null) {
Entry q = new Entry(p.element, parent);
q.left = copy(p.left, q);
q.right = copy(p.right, q);
return q;
}
return null;
} // method copy
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BinarySearchTree)) {
return false;
}
return equals(root, ((BinarySearchTree) obj).root);
}
public boolean equals(Entry p, Entry q) {
if ((p == null) || (q == null)) {
return p == q;
}
if (!p.element.equals(q.element)) {
return false;
}
if (equals(p.left, q.left) && equals(p.right, q.right)) {
return true;
}
return false;
}
/**
* Returns the size of this BinarySearchTree object.
3. *
* @return the size of this BinarySearchTree object.
*/
@Override
public int size() {
return size;
}
/**
* Iterator method will be implemented for a future
*
* @return an iterator positioned at the smallest element in this
* BinarySearchTree object.
*/
@Override
public Iterator iterator() {
throw new UnsupportedOperationException("Not implemented yet!");
}
/**
* Determines if there is at least one element in this BinarySearchTree object
* that equals a specified element. The worstTime(n) is O(n) and
* averageTime(n) is O(log n).
*
* @param obj - the element sought in this BinarySearchTree object.
* @return true - if there is an element in this BinarySearchTree object that
* equals obj; otherwise, return false.
* @throws ClassCastException - if obj cannot be compared to the elements in
* this BinarySearchTree object.
* @throws NullPointerException - if obj is null.
*/
@Override
public boolean contains(Object obj) {
return getEntry(obj) != null;
}
/**
* Ensures that this BinarySearchTree object contains a specified element. The
* worstTime(n) is O(n) and averageTime(n) is O(log n).
4. *
* @param element - the element whose presence is ensured in this
* BinarySearchTree object.
* @return true - if this BinarySearchTree object changed as a result of this
* method call (that is, if element was actually inserted); otherwise,
* return false.
* @throws ClassCastException - if element cannot be compared to the elements
* already in this BinarySearchTree object.
* @throws NullPointerException - if element is null.
*/
@Override
public boolean add(E element) {
if (root == null) {
if (element == null) {
throw new NullPointerException();
}
root = new Entry(element, null);
size++ ;
return true;
}
else {
Entry temp = root;
int comp;
while (true) {
comp = element.compareTo(temp.element);
if (comp == 0) {
return false;
}
if (comp < 0) {
if (temp.left != null) {
temp = temp.left;
} else {
temp.left = new Entry(element, temp);
size++ ;
return true;
} // temp.left == null
5. } else if (temp.right != null) {
temp = temp.right;
} else {
temp.right = new Entry(element, temp);
size++ ;
return true;
} // temp.right == null
} // while
} // root not null
} // method add
/**
* Ensures that this BinarySearchTree object does not contain a specified
* element. The worstTime(n) is O(n) and averageTime(n) is O(log n).
*
* @param obj - the object whose absence is ensured in this BinarySearchTree
* object.
* @return true - if this BinarySearchTree object changed as a result of this
* method call (that is, if obj was actually removed); otherwise,
* return false.
* @throws ClassCastException - if obj cannot be compared to the elements
* already in this BinarySearchTree object.
* @throws NullPointerException - if obj is null.
*/
@Override
public boolean remove(Object obj) {
Entry e = getEntry(obj);
if (e == null) {
return false;
}
deleteEntry(e);
return true;
}
/**
* Finds the Entry object that houses a specified element, if there is such an
* Entry. The worstTime(n) is O(n), and averageTime(n) is O(log n).
*
6. * @param obj - the element whose Entry is sought.
* @return the Entry object that houses obj - if there is such an Entry;
* otherwise, return null.
* @throws ClassCastException - if obj is not comparable to the elements
* already in this BinarySearchTree object.
* @throws NullPointerException - if obj is null.
*/
@SuppressWarnings("unchecked")
protected Entry getEntry(Object obj) {
int comp;
if (obj == null) {
throw new NullPointerException();
}
if (!(obj instanceof Comparable)) {
return null;
}
Comparable compObj = (Comparable) obj;
Entry e = root;
while (e != null) {
comp = compObj.compareTo(e.element);
if (comp == 0) {
return e;
} else if (comp < 0) {
e = e.left;
} else {
e = e.right;
}
} // while
return null;
}
/**
* Deletes the element in a specified Entry object from this BinarySearchTree.
*
* @param p - the Entry object whose element is to be deleted from this
* BinarySearchTree object.
* @return the Entry object that was actually deleted from this
7. * BinarySearchTree object.
*/
protected Entry deleteEntry(Entry p) {
size-- ;
// If p has two children, replace p's element with p's successor's
// element, then make p reference that successor.
if ((p.left != null) && (p.right != null)) {
Entry s = successor(p);
p.element = s.element;
p = s;
} // p had two children
// At this point, p has either no children or one child.
Entry replacement;
if (p.left != null) {
replacement = p.left;
} else {
replacement = p.right;
}
// If p has at least one child, link replacement to p.parent.
if (replacement != null) {
replacement.parent = p.parent;
if (p.parent == null) {
root = replacement;
} else if (p == p.parent.left) {
p.parent.left = replacement;
} else {
p.parent.right = replacement;
}
} // p has at least one child
else if (p.parent == null) {
root = null;
} else {
if (p == p.parent.left) {
p.parent.left = null;
} else {
p.parent.right = null;
8. }
} // p has a parent but no children
return p;
} // method deleteEntry
/**
* Finds the successor of a specified Entry object in this BinarySearchTree.
* The worstTime(n) is O(n) and averageTime(n) is constant.
*
* @param e - the Entry object whose successor is to be found.
* @return the successor of e, if e has a successor; otherwise, return null.
*/
protected Entry successor(Entry e) {
if (e == null) {
return null;
} else if (e.right != null) {
// successor is leftmost Entry in right subtree of e
Entry p = e.right;
while (p.left != null) {
p = p.left;
}
return p;
} // e has a right child
else {
// go up the tree to the left as far as possible, then go up
// to the right.
Entry p = e.parent;
Entry ch = e;
while ((p != null) && (ch == p.right)) {
ch = p;
p = p.parent;
} // while
return p;
} // e has no right child
} // method successor
@Override
public String toString() {
9. StringBuilder sb = new StringBuilder();
preOrder(root, sb);
return sb.toString();
}
protected static class Entry {
protected E element;
protected Entry left = null, right = null, parent;
/**
* Initializes this Entry object. This default constructor is defined for
* the sake of subclasses of the BinarySearchTree class.
*/
public Entry() {}
/**
* Initializes this Entry object from element and parent.
*/
public Entry(E element, Entry parent) {
this.element = element;
this.parent = parent;
} // constructor
} // class Entry
} // class BinarySearchTree