//Modifications highlighted in bold letters
//DropOutStack.java
import java.util.Arrays;
public class DropOutStack {
/**
* Defines the interface to a stack collection.
*
* @author Java Foundations
* @version 4.0
*/
public interface StackADT {
/**
* 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
*/
public T pop();
/**
* Returns without removing the top element of this stack.
*
* @return the element on top of the stack
*/
public T peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if the stack is empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size();
/**
* Returns a string representation of this stack.
*
* @return a string representation of the stack
*/
public String toString();
}
/**
* Represents the situation in which a collection is empty.
*
* @author Java Foundations
* @version 4.0
*/
public static class EmptyCollectionException extends RuntimeException {
/**
* Sets up this exception with an appropriate message.
*
* @param collection
* the name of the collection
*/
public EmptyCollectionException(String collection) {
super(\"The \" + collection + \" is empty.\");
}
}
/**
* Program entry point for stack testing.
*
* @param args
* Argument list.
*/
public static void main(String[] args) {
ArrayDropOutStack stack = new ArrayDropOutStack(4);
System.out.println(\"DROP-OUT STACK TESTING\");
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(\"Stack : \"+stack.toString());
System.out.println(\"pushing 5 element \");
stack.push(5);
System.out.println(\"Now stack elements\");
System.out.println(stack.toString());
System.out.println(\"The size of the stack is: \" + stack.size());
if (!stack.isEmpty())
System.out.println(\"The stack contains:\ \" + stack.toString());
stack.pop();
System.out.println(\"poping element 5\"+stack.toString());
System.out.println(\"The size of the stack is: \" + stack.size());
System.out.println(\"pushing 7 element \");
stack.push(7);
System.out.println(\"Now stack elements\");
System.out.println(stack.toString());
System.out.println(\"pushing 8 element \");
stack.push(8);
System.out.println(\"Now stack elements\");
System.out.println(stack.toString());
if (!stack.isEmpty())
System.out.println(\"The stack contains:\ \" + stack.toString());
}
/**
* An array implementation of a stack in which the bottom of the stack is
* fixed at index 0.
*
* @author Java Foundations
* @version 4.0
*/
public static class ArrayDropOutStack implements StackADT {
private final static int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
/**
* Creates an empty stack using the default capacity.
*/
public ArrayDropOutStack() {
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty stack using.
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.
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 ...
/**
* @author Derek Harter
* @cwid 123 45 678
* @class
* @ide Visual Studio Community 2017
* @date
* @assg C++ Stacks videos
*
* @description A Stack ADT with two concrete impelementation
* examples: an array based stack implementaiton (AStack), and
* a linked list based implementation (LStack).
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//-------------------------------------------------------------------------
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*/
virtual int size() const = 0;
/** tostring
* Represent stack as a string
*/
virtual string tostring() const = 0;
// operload operators, mostly to support boolean comparison between
// two stacks for testing
bool operator==(const Stack<T>& rhs) const;
virtual const T& operator[](int index) const = 0;
// overload output stream operator for all stacks using tostring()
template <typename U>
friend ostream& operator<<(ostream& out, const Stack<U>& aStack);
};
/** Stack equivalence
* Compare two given stacks to determine if they are equal or not.
* stacks are equal if they are both of the same size, and each corresponding
* item on each stack is equal at the same position on the stack.
* This function relies on overloaded operator[] to access items on stack
* by index for the comparis.
1 The goal is to implement DataStructuresArrayStack accor.pdfsaradashata
(1) The goal is to implement DataStructures.ArrayStack according to the interface ADTs.StackADT
********************************************
package DataStructures;
import ADTs.StackADT;
import Exceptions.EmptyCollectionException;
import Exceptions.StackOverflowException;
public class ArrayStack<T> implements StackADT<T> {
/** The index of where the top of the stack is */
int top;
/** The array that holds the stack */
T[] buffer;
public ArrayStack() {
}
public ArrayStack(int initialCapacity) {
}
}
*******************************************************
package ADTs;
import Exceptions.EmptyCollectionException;
import Exceptions.StackOverflowException;
/**
* An interface for a Stack
* Specific stack implementations will implement this interface
* For use Data Structures & Algorithms
*
*
* author unknown
*/
public interface StackADT<T> extends CollectionADT<T> {
/**
* Adds the specified element to the top of the stack
*
* @param element element to be pushed onto the stack
*/
public void push(T element) throws StackOverflowException;
/**
* Removes and returns the element that is on top of the stack
*
* @return the element removed from the stack
* @throws EmptyCollectionException
*/
public T pop() throws EmptyCollectionException;
/**
* Returns (without removing) the element that is on top of the stack
*
* @return the element on top of the stack
* @throws EmptyCollectionException
*/
public T peek() throws EmptyCollectionException;
}
*****************************************
package ADTs;
import Exceptions.*;
/**
* An interface for an ordered (NOT SORTED) List
* Elements stay in the order they are put in to the list
* For use in Data Structures & Algorithms
*
*
* @author unknown
*/
public interface ListADT<T> extends CollectionADT<T> {
/**
* Adds the specified element to the list at the front
*
* @param element: the element to be added
*
*/
public void addFirst(T element);
/**
* Adds the specified element to the end of the list
*
* @param element: the element to be added
*/
public void addLast(T element);
/**
* Adds the specified element to the list after the existing element
*
* @param existing: the element that is in the list already
* @param element: the element to be added
* @throws ElementNotFoundException if existing isn't in the list
*/
public void addAfter(T existing, T element) throws ElementNotFoundException,
EmptyCollectionException;
/**
* Removes and returns the specified element
*
* @return the element specified
* @throws EmptyCollectionException
* @throws ElementNotFoundException
*/
public T remove(T element) throws EmptyCollectionException, ElementNotFoundException;
/**
* Removes and returns the first element
*
* @return the first element in the list
* @throws EmptyCollectionException
*/
public T removeFirst() throws EmptyCollectionException;
/**
* Removes and returns the last element
*
* @return the last element in the list
* @throws EmptyCollectionException
*/
public T removeLast() throws EmptyCollectionException;
/**
* Returns (wit.
Need help with writing the test cases for the following code in java-.docxLucasmHKChapmant
Need help with this question ASAP! Please and thanks
2 points The is typically the most powerful stakeholder for the project but is often not the most powerful person in the company. 2 points The two axes on grid we use to measure the impact a stakeholder could have on our project and how we manage the relationship with them are and
.
Implement the ADT stack by using an array stack to contain its entri.pdfSIGMATAX1
Implement the ADT stack by using an array stack to contain its entries. Expand the array
dynamically, as necessary. Maintain the stack’s bottom entry in stack[stack.length – 1].
Your Stack class must implement StackInterface (provided). You may use ArrayStack.java
(provided) as the starting point for your implementation.
You must implement a comprehensive set of unit tests using the main() method (and private
utility methods) in ArrayStack.java.
ArrayStack.java
public class ArrayStack implements StackInterface
{
private T[] stack; // Array of stack entries
private int topIndex; // Index of top entry
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayStack()
{
this(DEFAULT_CAPACITY);
} // end default constructor
public ArrayStack(int initialCapacity)
{
checkCapacity(initialCapacity);
// The cast is safe because the new array contains null entries
@SuppressWarnings(\"unchecked\")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
initialized = true;
} // end constructor
// < Implementations of the stack operations go here. >
// < Implementations of the private methods go here; checkCapacity and
// checkInitialization are analogous to those in Chapter 2. >
// . . .
} // end ArrayStack
StackInterface.java
public interface StackInterface
{
/** Adds a new entry to the top of this stack.
@param newEntry An object to be added to the stack. */
public void push(T newEntry);
/** Removes and returns this stack\'s top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty before the operation. */
public T pop();
/** Retrieves this stack\'s top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty. */
public T peek();
/** Detects whether this stack is empty.
@return True if the stack is empty. */
public boolean isEmpty();
/** Removes all entries from this stack. */
public void clear();
} // end StackInterface
Solution
StackTester.java
public class StackTester
{
public static void main(String[] args)
{
ArrayStack aS = new ArrayStack();
aS.push(3);
aS.push(5);
aS.push(10);
aS.push(11);
System.out.println(\"\"+ aS.peek() + \", \" + aS.pop() + \", \" + aS.peek2());
aS.remove(1);
}
}
ArrayStack.java
import java.util.Arrays;
public class ArrayStack implements StackInterface
{
private T[] stack;
private int topIndex;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayStack()
{
this(DEFAULT_CAPACITY);
}
public ArrayStack(int initialCapacity)
{
checkCapacity(initialCapacity);
@SuppressWarnings(\"unchecked\")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
initialized = true;
}
public boolean isEmpty()
{
return topIndex < 0;
}
private void ensureCapacity()
{
if(topIndex == stack.length - 1)
{
int newLength = 2*stack.length;
.
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.
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.
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 ...
/**
* @author Derek Harter
* @cwid 123 45 678
* @class
* @ide Visual Studio Community 2017
* @date
* @assg C++ Stacks videos
*
* @description A Stack ADT with two concrete impelementation
* examples: an array based stack implementaiton (AStack), and
* a linked list based implementation (LStack).
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//-------------------------------------------------------------------------
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*/
virtual int size() const = 0;
/** tostring
* Represent stack as a string
*/
virtual string tostring() const = 0;
// operload operators, mostly to support boolean comparison between
// two stacks for testing
bool operator==(const Stack<T>& rhs) const;
virtual const T& operator[](int index) const = 0;
// overload output stream operator for all stacks using tostring()
template <typename U>
friend ostream& operator<<(ostream& out, const Stack<U>& aStack);
};
/** Stack equivalence
* Compare two given stacks to determine if they are equal or not.
* stacks are equal if they are both of the same size, and each corresponding
* item on each stack is equal at the same position on the stack.
* This function relies on overloaded operator[] to access items on stack
* by index for the comparis.
1 The goal is to implement DataStructuresArrayStack accor.pdfsaradashata
(1) The goal is to implement DataStructures.ArrayStack according to the interface ADTs.StackADT
********************************************
package DataStructures;
import ADTs.StackADT;
import Exceptions.EmptyCollectionException;
import Exceptions.StackOverflowException;
public class ArrayStack<T> implements StackADT<T> {
/** The index of where the top of the stack is */
int top;
/** The array that holds the stack */
T[] buffer;
public ArrayStack() {
}
public ArrayStack(int initialCapacity) {
}
}
*******************************************************
package ADTs;
import Exceptions.EmptyCollectionException;
import Exceptions.StackOverflowException;
/**
* An interface for a Stack
* Specific stack implementations will implement this interface
* For use Data Structures & Algorithms
*
*
* author unknown
*/
public interface StackADT<T> extends CollectionADT<T> {
/**
* Adds the specified element to the top of the stack
*
* @param element element to be pushed onto the stack
*/
public void push(T element) throws StackOverflowException;
/**
* Removes and returns the element that is on top of the stack
*
* @return the element removed from the stack
* @throws EmptyCollectionException
*/
public T pop() throws EmptyCollectionException;
/**
* Returns (without removing) the element that is on top of the stack
*
* @return the element on top of the stack
* @throws EmptyCollectionException
*/
public T peek() throws EmptyCollectionException;
}
*****************************************
package ADTs;
import Exceptions.*;
/**
* An interface for an ordered (NOT SORTED) List
* Elements stay in the order they are put in to the list
* For use in Data Structures & Algorithms
*
*
* @author unknown
*/
public interface ListADT<T> extends CollectionADT<T> {
/**
* Adds the specified element to the list at the front
*
* @param element: the element to be added
*
*/
public void addFirst(T element);
/**
* Adds the specified element to the end of the list
*
* @param element: the element to be added
*/
public void addLast(T element);
/**
* Adds the specified element to the list after the existing element
*
* @param existing: the element that is in the list already
* @param element: the element to be added
* @throws ElementNotFoundException if existing isn't in the list
*/
public void addAfter(T existing, T element) throws ElementNotFoundException,
EmptyCollectionException;
/**
* Removes and returns the specified element
*
* @return the element specified
* @throws EmptyCollectionException
* @throws ElementNotFoundException
*/
public T remove(T element) throws EmptyCollectionException, ElementNotFoundException;
/**
* Removes and returns the first element
*
* @return the first element in the list
* @throws EmptyCollectionException
*/
public T removeFirst() throws EmptyCollectionException;
/**
* Removes and returns the last element
*
* @return the last element in the list
* @throws EmptyCollectionException
*/
public T removeLast() throws EmptyCollectionException;
/**
* Returns (wit.
Need help with writing the test cases for the following code in java-.docxLucasmHKChapmant
Need help with this question ASAP! Please and thanks
2 points The is typically the most powerful stakeholder for the project but is often not the most powerful person in the company. 2 points The two axes on grid we use to measure the impact a stakeholder could have on our project and how we manage the relationship with them are and
.
Implement the ADT stack by using an array stack to contain its entri.pdfSIGMATAX1
Implement the ADT stack by using an array stack to contain its entries. Expand the array
dynamically, as necessary. Maintain the stack’s bottom entry in stack[stack.length – 1].
Your Stack class must implement StackInterface (provided). You may use ArrayStack.java
(provided) as the starting point for your implementation.
You must implement a comprehensive set of unit tests using the main() method (and private
utility methods) in ArrayStack.java.
ArrayStack.java
public class ArrayStack implements StackInterface
{
private T[] stack; // Array of stack entries
private int topIndex; // Index of top entry
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayStack()
{
this(DEFAULT_CAPACITY);
} // end default constructor
public ArrayStack(int initialCapacity)
{
checkCapacity(initialCapacity);
// The cast is safe because the new array contains null entries
@SuppressWarnings(\"unchecked\")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
initialized = true;
} // end constructor
// < Implementations of the stack operations go here. >
// < Implementations of the private methods go here; checkCapacity and
// checkInitialization are analogous to those in Chapter 2. >
// . . .
} // end ArrayStack
StackInterface.java
public interface StackInterface
{
/** Adds a new entry to the top of this stack.
@param newEntry An object to be added to the stack. */
public void push(T newEntry);
/** Removes and returns this stack\'s top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty before the operation. */
public T pop();
/** Retrieves this stack\'s top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty. */
public T peek();
/** Detects whether this stack is empty.
@return True if the stack is empty. */
public boolean isEmpty();
/** Removes all entries from this stack. */
public void clear();
} // end StackInterface
Solution
StackTester.java
public class StackTester
{
public static void main(String[] args)
{
ArrayStack aS = new ArrayStack();
aS.push(3);
aS.push(5);
aS.push(10);
aS.push(11);
System.out.println(\"\"+ aS.peek() + \", \" + aS.pop() + \", \" + aS.peek2());
aS.remove(1);
}
}
ArrayStack.java
import java.util.Arrays;
public class ArrayStack implements StackInterface
{
private T[] stack;
private int topIndex;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayStack()
{
this(DEFAULT_CAPACITY);
}
public ArrayStack(int initialCapacity)
{
checkCapacity(initialCapacity);
@SuppressWarnings(\"unchecked\")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
initialized = true;
}
public boolean isEmpty()
{
return topIndex < 0;
}
private void ensureCapacity()
{
if(topIndex == stack.length - 1)
{
int newLength = 2*stack.length;
.
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.
create a new interface called DropoutStackADT for representing a dro.pdff3apparelsonline
create a new interface called DropoutStackADT for representing a dropout stack. It should
contain exactly the same methods as StackADT, and have documentation for the file and each
method in proper javadoc. Your file will be different from StackADT since a dropout stack acts
differently than a normal stack. When documenting methods that should support throwing an
exception, make a note in its javadocdescription.
Implement a drop-out stack using a linked structure. You use the LinearNode or
LinearDoubleNode classes. Follow the DropoutStackADT interface. See Base_A11Q3.java for a
starting place.
STACKADT
LinearDoubleNode
/**
* Represents a node in a linked list.
*
* @author Java Foundations
* @version 4.0
*/
public class LinearDoubleNode
{
private LinearDoubleNode next,prev;
private T element;
/**
* Creates an empty node.
*/
public LinearDoubleNode()
{
next = null;
element = null;
prev = null;
}
/**
* Creates a node storing the specified element.
* @param elem element to be stored
*/
public LinearDoubleNode(T elem)
{
next = null;
element = elem;
prev = null;
}
/**
* Returns the node that follows this one.
* @return reference to next node
*/
public LinearDoubleNode getNext()
{
return next;
}
/**
* Sets the node that follows this one.
* @param node node to follow this one
*/
public void setNext(LinearDoubleNode node)
{
next = node;
}
/**
* Returns the element stored in this node.
* @return element stored at the node
*/
public T getElement()
{
return element;
}
/**
* Sets the element stored in this node.
* @param elem element to be stored at this node
*/
public void setElement(T elem)
{
element = elem;
}
public LinearDoubleNode getPrev(){
return prev;
}
public void setPrev(LinearDoubleNode node){
prev = node;
}
}
Base File DROP-OUT STACK TESTING The size of the stack is: 4 The stack contains: The size
of the stack is 4 The stack contains:
Solution
public class DropOutStack implements StackADT {
private final int DEFAULT_CAPACITY = 10;
// refers to the item in the array being indexed
private int cIndex;
// holds the count of the stack
private int count;
private T[] stack;
public DropOutStack() {
cIndex = count = 0;
stack = (T[]) (new Object[DEFAULT_CAPACITY]);
}
public DropOutStack(int initialCapacity) {
cIndex = count = 0;
stack = (T[]) (new Object[initialCapacity]);
}
public T peek() throws EmptyCollectionException {
if (isEmpty())
throw new EmptyCollectionException(\"Drop-out Stack\");
return stack[(cIndex + stack.length - 1)%stack.length];
}
public T pop() throws EmptyCollectionException {
if (isEmpty())
throw new EmptyCollectionException(\"Drop-out Stack\");
cIndex = (cIndex + stack.length - 1)%stack.length;
T result = stack[cIndex];
stack[cIndex] = null;
count--;
return result;
}
public void push(T element) {
cIndex = cIndex % stack.length;
stack[cIndex] = element;
cIndex++;
if (count != stack.length)
count++;
}
public int size() {
return count;
}
public boolean isEmpty() {
return size() == 0;
}
public String toString() {
String str = \"\";
i.
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
So I have this code( StackInAllSocks ) and I implemented the method but I can't seem to figure
out why there isn't anything showing up on the console. It should pop,peek and push b using the
methods from the class called ArrayListTen . The ArrayListTen works fine and compiles the
tested code of Rigth# but for StackInAllSocks it doesn't complete at all. note that file
VodeDodeis not to be changed is just a Node storage area of the array list.
Did I implement the method on StackInAllSocks correctly? if so, should I not use the method
from the ArrayListTen .?
__________________________________________________________________________
: the code is : VodeDodeis
class VodeDode<T> {
private T data;
private VodeDode<T> next;
private VodeDode<T> prev;
public VodeDode(T data) {
this.data = data;
this.next = null;
this.prev = null;}
public T getData() {
return data;}
public void setData(T data) {
this.data = data;}
public VodeDode<T> getNext() {
return this.next;}
public void setNext(VodeDode<T> next) {
this.next = next;}
public VodeDode<T> getPrev() {
return this.prev;}
public void setPrev(VodeDode<T> prev) {
this.prev = prev;}
@Override
public String toString() {
return data.toString();}}
_________________________________________________________________________
CODE that works fine called ArrayListTen:
import java.util.Iterator;
public class ArrayListTen<T> implements Iterable<T> {
private VodeDode<T> head; //beginning of list
private VodeDode<T> tail; //end of list
private int size;
private VodeDode<T> new_item;
public ArrayListTen( ){
this.head = null;
this.tail = null;
this.size = 0;}
public int lenght() {
return size ;}
public T getBegin() {
if (this.head != null) {
return head.getData();}
else { return null;}}
public void addBegin(T value) {
VodeDode<T> newVodeDode =new VodeDode<T>(value);
if (this.head== null) {
head = newVodeDode;
tail =newVodeDode;}
else {VodeDode<T> temp = head;
head = newVodeDode;
head.setNext(temp);}
size++;}
public T removeBegin() {
if(this.head == null) {
return null;}
else {T current = head.getData();
if (tail == head) {
tail = null;
head = null;
} else {
head = head.getNext();
head.setPrev(null);}size--;
return current;}}
public T getEnd() {
if (tail != null) {
return tail.getData();
} else {
return null;}}
public void addEnd(T value) {
VodeDode<T> newVodeDode = new VodeDode<T>(value);
if (this.tail == null) {
head = newVodeDode;
tail = newVodeDode;
} else {
newVodeDode.setPrev(tail);
tail.setNext(newVodeDode);
tail = newVodeDode;}
size++;}
public T removeEnd() {
if(this.tail == null) {
return null;}
else {
T current = tail.getData();//was head.
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.getPrev();
tail.setNext(null);}
size--;
return current;}}
public T removeBN(T value) {
VodeDode<T> currVodeDode = head;
VodeDode<T> prevVodeDode = null;
while(currVodeDode != null){
if(currVodeDode.getData().equals(value)){
if(prevVodeDode != null){
prevVodeDode.setNext(currVodeDode.getNext());}
else{
head = curr.
Given the following ADT definition of a stack to use stack .docxshericehewat
Given the following ADT definition of a stack to use:
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*
* @returns int The current size (number of items) on the stack.
*/
virtual int size() const = 0;
};
perform the following tasks by writing code that uses a stack to accomplish the task. You will
need to create a stack of the needed type, then use the methods of the stack abstraction (push,
top, pop, etc.) to solve the given task asked for.
Question 7 (5 points)
Given a stack of integers, calculate the sum of the integer values. Also, the stack should still be
unchanged after you have calculated the sum Hint: take the items off the stack to sum them up
and keep them on a second temporary stack so you can put them all back on after you have
calculated the sum.
ANSWER FOR NUMBER 7:
int sumStackOfIntegers(Stack<int> currentStack) {
Stack<int> tempStack;
int sum = 0;
while(!currentStack.isEmpty()) {
int temp = currentStack.top();
tempStack.push(temp);
currentStack.pop();
sum += temp;
}
while(!tempStack.isEmpty()) {
int temp = tempStack.top();
currentStack.push(temp);
tempStack.pop();
}
return sum;
}
Stack Implementation
Given the following linked list implementation of a Stack ADT (this is the same implementation
you used in Assignment 10), add the asked for additional member methods to the linked list stack
implementation.
/** Node
* A basic node contaning an item and a link to t ...
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
StackInterface
/**
An interface for the ADT stack.
Do not modify this file
*/
package PJ2;
public interface StackInterface
{
/** Gets the current number of data in this stack.
@return the integer number of entries currently in the stack*/
public int size();
/** Adds a new data to the top of this stack.
@param aData an object to be added to the stack */
public void push(T aData);
/** Removes and returns this stack\'s top data.
@return either the object at the top of the stack or,
if the stack is empty before the operation, null */
public T pop();
/** Retrieves this stack\'s top data.
@return either the data at the top of the stack or
null if the stack is empty */
public T peek();
/** Detects whether this stack is empty.
@return true if the stack is empty */
public boolean empty();
/** Removes all data from this stack */
public void clear();
} // end StackInterface
SimpleLinkedStack.java
/**
A class of stacks whose entries are stored in a chain of nodes.
Implement all methods in SimpleLinkedStack class using
the inner Node class.
Main Reference : text book or class notes
Do not change or add data fields
Do not add new methods
You may access Node object fields directly, i.e. data and next
*/
package PJ2;
public class SimpleLinkedStack implements StackInterface
{
// Data fields
private Node topNode; // references the first node in the chain
private int count; // number of data in this stack
public SimpleLinkedStack()
{
// add stataments
} // end default constructor
public void push(T newData)
{
// add stataments
} // end push
public T peek()
{
// add stataments
return null;
} // end peek
public T pop()
{
// add stataments
return null;
} // end pop
public boolean empty()
{
// add stataments
return false;
} // end empty
public int size()
{
// add stataments
return -1;
} // end isEmpty
public void clear()
{
// add stataments
} // end clear
public String toString()
{
// add stataments
// note: data class in stack must implement toString() method
// return a list of data in Stack, separate them with \',\'
return \"\";
}
/****************************************************
private inner node class
Do not modify this class!!
you may access data and next directly
***************************************************/
private class Node
{
private T data; // entry in list
private Node next; // link to next node
private Node (T dataPortion)
{
data = dataPortion;
next = null; // set next to NULL
} // end constructor
private Node (T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode; // set next to refer to nextNode
} // end constructor
} // end Node
/****************************************************
Do not modify: Stack test
****************************************************/
public static void main (String args[])
{
System.out.println(\"\ \"+
\"*******************************************************\ \"+
\"Sample Expected output:\ \"+
\"\ \"+
\"OK: stack is empty\ \"+
\"Push 3 data: 10, 30, 50\ \"+
\"Print stack [50,30,10,]\ \"+
\"OK: sta.
we using java code DynamicArrayjava Replace all .pdfgudduraza28
we using java code /** * DynamicArray.java * * Replace all //TODO tags with your code * * Note
that below the "//TODO" tag there may be * something like "return null;", "return 0;", etc. * That line
is just "stubbed in" so the class * will compile. When you add your code (one or many *
statements), you will want to delete the "stubbed" line. * By "stubbed in" we mean "mocked" or
"faked in" temporarily. * * When testing, construct using the static factory methods:
DynamicList.newEmpty() DynamicList.fromGrowthFactor(growthFactor)
DynamicList.from(arrayElements) */ package model.list; import java.lang.reflect.Array; import
java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import
java.util.function.Consumer; import java.util.function.Function; import
model.linearpub.DynamicList; import model.linearpub.StructureIterator; public class
DynamicArray<E> implements DynamicList<E> { //--------------------------------- // Instance Variables
//TODO - declare instance variable(s) //--------------------------------- // Private Constructors /**
Constructs and returns new DynamicArray (no args constructor) */ private DynamicArray() {
this(defaultGrowthFactor()); } /** Constructs and returns new DynamicArray with "aGrowthFactor"
*/ private DynamicArray(double aGrowthFactor) { //TODO -- this is the constructor that should
//initialize the dynamic array as needed } //------------------------------------------------ public static double
defaultGrowthFactor() { //TODO - replace 0 with a good growth factor return 0; } protected static int
defaultInitialCapacity() { //TODO - replace 0 with a good initial capacity return 0; } //--------------------
List Statistics --------------------- /** * Return number of elements in this list. */ @Override public int
size() { //TODO return 0; } /** * Return true is this list contains no elements. */ @Override public
boolean isEmpty() { //TODO return false; } //------------------ Accessing Elements -------------------- /**
* Return element at given index. * Throws IndexOutOfBoundsException if passed index is invalid.
*/ @Override public E get(int index) { //TODO return null; } /** * Return first element * Throws
RuntimeException if list is empty */ @Override public E first() { //TODO return null; } /** * Return
last element * Throws RuntimeException if list is empty */ @Override public E last() { //TODO
return null; } /** * Return a new list containing the elements of this list * between the given index
"start" (inclusive) and * the given index "stop" (exclusive). * Throws IndexOutOfBoundsException if
either passed index is invalid. */ @Override public DynamicList<E> subList(int start, int stop) {
//TODO return null; } /** * Return index of first matching element (where searchFct outputs true) *
Return -1 if no match * Example usage (first list of integers, then employees): * index =
list.find(eaInteger -> eaInteger == 10); * index = employeeList.find(employee -> employee
.getFirstName().equals("Kofi.
A linked stack is implemented using a standard Node class as follows.pdfkisgstin23
A linked stack is implemented using a standard Node class as follows: import java.util.*; class
stack implements Iterable {private Node top; private int size; public stack () {top = null; size =
0;} public Object pop() {if (size == 0) throw new RuntimeException (\"\"); Object answer =
top.getData (); top = top.getNext (); Size --; return answer;} public void push (Object x) {Node
newNode = new Node (x top); top = newNode; size++;}//the iterator method is missing} Write a
class StackIterator to implement objects that can be returned by the stack iterator. Also write the
missing stack method called iterator. You can decide whether the iterator will run through the
data in the stack in LIFO or FIFO order (one choice is much easier).
Solution
Hi,
Pease find the program below:
import java.util.*;
import java.lang.Iterable;
@SuppressWarnings(\"rawtypes\")
public class LinkedStack implements Iterable{
private int n; // size of the stack
private Node first; // top of stack
// Helper linked list class
private class Node {
private Object item;
private Node next;
}
/**
* Initializes an empty stack.
*/
public LinkedStack() {
first = null;
n = 0;
}
/**
* Is this stack empty?
* @return true if this stack is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
}
/**
* Returns the number of items in the stack.
*/
public int size() {
return n;
}
/**
* Adds the item to this stack.
*/
public void push(Object item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
/**
* Removes and returns the item most recently added to this stack.
* @return the item most recently added
*/
public Object pop() {
if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");
Object item = first.item; // save item to return
first = first.next; // delete first node
n--; //decreases the size by 1
return item; // return the saved item
}
/**
* Returns (but does not remove) the item most recently added to this stack.
* @return the item most recently added to this stack
*/
public Object peek() {
if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");
return first.item;
}
/**
* Returns an iterator to this stack that iterates through the items in LIFO order.
*/
public Iterator iterator() {
return new ListIterator();
}
// an iterator, doesn\'t implement remove() since it\'s optional
private class ListIterator implements Iterator {
private int i = n;
private Node first1 = first; //the first node
public boolean hasNext()
{
return (i > 0);
}
public Object next()
{
Object item = first1.item;
first1 = first1.next;
i--;
return item;
}
public void remove()
{
// not needed as this is optional
}
}
//Main method to implement the test
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedStack */
LinkedStack ls = new LinkedStack();
/* Perform Stack Operations */
System.out.println(\"Linked Stack Test\ \");
char ch;
do
{
System.out.println(\"\ Linked Stack .
EmptyCollectionException-java -- - Represents the situation in which.docxBlakeSGMHemmingss
EmptyCollectionException.java
/*
* Represents the situation in which a collection is empty.
*/
public class EmptyCollectionException extends RuntimeException
{
/* General class level objects */
/*
* Sets up this exception with an appropriate message.
* @param collection the name of the collection
*/
public EmptyCollectionException(String collection)
{
super("The " + collection + " is empty.");
}
}
PriorityNode.java
/*
* Represents a node in a linked list.
*/
public class PriorityNode<T>
{
/* General class level objects */
private PriorityNode<T> _next;
private T _element;
private int _priority;
private final int _MAX_PRIORITY = 100;
/*
* Creates an empty node with a given priority.
*/
public PriorityNode(T elem, int priority)
{
// TODO To be completed as a Programming Project
}
/*
* Creates a node storing the specified element with a default priority.
*
* @param elem element to be stored
*/
public PriorityNode(T elem)
{
// TODO To be completed as a Programming Project
}
/*
* Returns the node that follows this one.
*
* @return reference to next node
*/
public PriorityNode<T> getNext()
{
// TODO To be completed as a Programming Project
}
/*
* Sets the node that follows this one.
*
* @param node node to follow this one
*/
public void setNext(PriorityNode<T> node)
{
// TODO To be completed as a Programming Project
}
/*
* Returns the element stored in this node.
*
* @return element stored at the node
*/
public T getElement()
{
// TODO To be completed as a Programming Project
}
/*
* Returns the priority of this node.
*
* @return element priority the node
*/
public int getPriority()
{
// TODO To be completed as a Programming Project
}
/*
* Sets the element stored in this node.
*
* @param elem element to be stored at this node
*/
public void setElement(T elem)
{
// TODO To be completed as a Programming Project
}
/*
* optional toString() override.
*/
//public String toString()
//{
// // TODO To be completed as a Programming Project
//}
}
PriorityQueue.java
/*
* LinkedQueue represents a linked implementation of a queue.
*/
public class PriorityQueue<T> implements PriorityQueueADT<T>
{
/* General class level objects */
private int _count;
private PriorityNode<T> _head, _tail;
/*
* Constructor - Creates an empty queue.
*/
public PriorityQueue()
{
_count = 0;
_head = _tail = null;
}
/*
* Adds one element to the rear of this queue.
* Higher priorities are inserted closer to the front of the queue
* Items with the same priority are processed in normal queue order
*
* @param element the element to be added to the rear of the queue
* @param priority relative priority of the queue item
*/
public void enqueue(T element, int priority)
{
// TODO To be completed as a Programming Project
// add in-order insertion of the PriorityNode based on getPriority() value
// the higher the priority is the closer to head it gets
// equivalent priority is normal .
Please do parts labeled TODO LinkedList.java Replace.pdfaioils
Please do parts labeled TODO
/**
* LinkedList.java
*
* Replace all //TODO tags with your code
*
* Note that below the "//TODO" tag there may be
* something like "return null;", "return 0;", etc.
* That line is just "stubbed in" so the class
* will compile. When you add your code (one or many
* statements), you will want to delete the "stubbed" line.
* By "stubbed in" we mean "mocked" or "faked in" temporarily.
*
* When testing, construct using the static factory methods:
LinkedList.newEmpty()
LinkedList.from(arrayElements)
*/
package model.list;
import java.lang.reflect.Array;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import model.linearpub.DynamicList;
import model.linearpub.StructureIterator;
//This class is NOT java.util.LinkedList
public class LinkedList implements DynamicList {
//---------------------------------
// Instance Variables
//TODO - declare instance variable(s)
//---------------------------------
// Private Constructor
/** Constructs and returns new LinkedList (no args constructor) */
private LinkedList() {
}
//-------------------- List Statistics ---------------------
/**
* Return number of elements in this list.
*/
@Override
public int size() {
//TODO
return 0;
}
/**
* Return true is this list contains no elements.
*/
@Override
public boolean isEmpty() {
//TODO
return false;
}
//------------------ Accessing Elements --------------------
/**
* Return element at given index.
* Throws IndexOutOfBoundsException if passed index is invalid.
*/
@Override
public E get(int index) {
//TODO
return null;
}
/**
* Return first element
* Throws RuntimeException if list is empty
*/
@Override
public E first() {
//TODO
return null;
}
/**
* Return last element
* Throws RuntimeException if list is empty
*/
@Override
public E last() {
//TODO
return null;
}
/**
* Return a new list containing the elements of this list
* between the given index "start" (inclusive) and
* the given index "stop" (exclusive).
* Throws IndexOutOfBoundsException if either passed index is invalid.
*/
@Override
public DynamicList subList(int start, int stop) {
//TODO
return null;
}
/**
* Return index of first matching element (where searchFct outputs true)
* Return -1 if no match
* Example usage (first list of integers, then employees):
* index = list.find(eaInteger -> eaInteger == 10);
* index = employeeList.find(employee -> employee .getFirstName().equals("Kofi"));
*/
@Override
public int findFirst(Function searchFct) {
//TODO
return 0;
}
/**
* Return index of last matching element (where searchFct outputs true)
* E.g., if searching for employee with name "Kofi" and there is a match
* at index=3 and index=8, findLast will return 8 (the last matching index).
* Hint: start search at end of list and work backwards through list.
* Return -1 if no match
*/
@Override
public int findLast(Function searchFct) {
//TODO
return 0;
}
//------------------- Setting Elem.
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 *.
package ADTs public interface CollectionADTltTgt .pdfsyedabdul78662
package ADTs;
public interface CollectionADT<T> {
public boolean isEmpty();
public int size();
@Override
public String toString();
}
**********************************************************
package ADTs;
import Exceptions.*;
/**
* An interface for an ordered (NOT SORTED) List
* Elements stay in the order they are put in to the list
* For use in Data Structures & Algorithms
*
*
* @author
*/
public interface ListADT<T> extends CollectionADT<T> {
/**
* Adds the specified element to the list at the front
*
* @param element: the element to be added
*
*/
public void addFirst(T element);
/**
* Adds the specified element to the end of the list
*
* @param element: the element to be added
*/
public void addLast(T element);
/**
* Adds the specified element to the list after the existing element
*
* @param existing: the element that is in the list already
* @param element: the element to be added
* @throws ElementNotFoundException if existing isn't in the list
*/
public void addAfter(T existing, T element) throws ElementNotFoundException,
EmptyCollectionException;
/**
* Removes and returns the specified element
*
* @return the element specified
* @throws EmptyCollectionException
* @throws ElementNotFoundException
*/
public T remove(T element) throws EmptyCollectionException, ElementNotFoundException;
/**
* Removes and returns the first element
*
* @return the first element in the list
* @throws EmptyCollectionException
*/
public T removeFirst() throws EmptyCollectionException;
/**
* Removes and returns the last element
*
* @return the last element in the list
* @throws EmptyCollectionException
*/
public T removeLast() throws EmptyCollectionException;
/**
* Returns (without removing) the first element in the list
*
* @return element at the beginning of the list
* @throws EmptyCollectionException
*/
public T first() throws EmptyCollectionException;
/**
* Returns (without removing) the last element in the list
*
* @return element at the end of the list
* @throws EmptyCollectionException
*/
public T last() throws EmptyCollectionException;
/**
* Return whether the list contains the given element.
*
* @param element
* @return
* @throws EmptyCollectionException
*/
public boolean contains(T element) throws EmptyCollectionException;
/**
* Returns the index of the given element.
*
* @param element
* @return the index of the element, or -1 if not found
*/
public int indexOf(T element);
/**
* Return the element at the given index of a list.
*
* @param element
* @return
* @throws EmptyCollectionException
*/
public T get(int index) throws EmptyCollectionException, InvalidArgumentException;
/**
* Set the at the given index of a list.
*
* @param element
* @return
* @throws EmptyCollectionException
*/
public void set(int index, T element) throws EmptyCollectionException, InvalidArgumentException;
}
**********************************************
package ADTs;
import Exceptions.EmptyCollectionException;
import Exceptions.QueueOverflowException;
public interface QueueADT<.
please read the steps below and it will tell you what we usi.pdfaggarwalopticalsco
please read the steps below and it will tell you what we using
/**
* DynamicArray.java
*
* Replace all //TODO tags with your code
*
* Note that below the "//TODO" tag there may be
* something like "return null;", "return 0;", etc.
* That line is just "stubbed in" so the class
* will compile. When you add your code (one or many
* statements), you will want to delete the "stubbed" line.
* By "stubbed in" we mean "mocked" or "faked in" temporarily.
*
* When testing, construct using the static factory methods:
DynamicList.newEmpty()
DynamicList.fromGrowthFactor(growthFactor)
DynamicList.from(arrayElements)
*/
package model.list;
import java.lang.reflect.Array;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import model.linearpub.DynamicList;
import model.linearpub.StructureIterator;
public class DynamicArray<E> implements DynamicList<E> {
//---------------------------------
// Instance Variables
//TODO - declare instance variable(s)
//---------------------------------
// Private Constructors
/** Constructs and returns new DynamicArray (no args constructor) */
private DynamicArray() {
this(defaultGrowthFactor());
}
/** Constructs and returns new DynamicArray with "aGrowthFactor" */
private DynamicArray(double aGrowthFactor) {
//TODO -- this is the constructor that should
//initialize the dynamic array as needed
}
//------------------------------------------------
public static double defaultGrowthFactor() {
//TODO - replace 0 with a good growth factor
return 0;
}
protected static int defaultInitialCapacity() {
//TODO - replace 0 with a good initial capacity
return 0;
}
//-------------------- List Statistics ---------------------
/**
* Return number of elements in this list.
*/
@Override
public int size() {
//TODO
return 0;
}
/**
* Return true is this list contains no elements.
*/
@Override
public boolean isEmpty() {
//TODO
return false;
}
//------------------ Accessing Elements --------------------
/**
* Return element at given index.
* Throws IndexOutOfBoundsException if passed index is invalid.
*/
@Override
public E get(int index) {
//TODO
return null;
}
/**
* Return first element
* Throws RuntimeException if list is empty
*/
@Override
public E first() {
//TODO
return null;
}
/**
* Return last element
* Throws RuntimeException if list is empty
*/
@Override
public E last() {
//TODO
return null;
}
/**
* Return a new list containing the elements of this list
* between the given index "start" (inclusive) and
* the given index "stop" (exclusive).
* Throws IndexOutOfBoundsException if either passed index is invalid.
*/
@Override
public DynamicList<E> subList(int start, int stop) {
//TODO
return null;
}
/**
* Return index of first matching element (where searchFct outputs true)
* Return -1 if no match
* Example usage (first list of integers, then employees):
* index = list.find(eaInteger -> eaInteger == 10);
* index = employeeList.find(emplo.
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.
please read below it will tell you what we are using L.pdfankit11134
please read below it will tell you what we are using
/**
* LinkedList.java
*
* Replace all //TODO tags with your code
*
* Note that below the "//TODO" tag there may be
* something like "return null;", "return 0;", etc.
* That line is just "stubbed in" so the class
* will compile. When you add your code (one or many
* statements), you will want to delete the "stubbed" line.
* By "stubbed in" we mean "mocked" or "faked in" temporarily.
*
* When testing, construct using the static factory methods:
LinkedList.newEmpty()
LinkedList.from(arrayElements)
*/
package model.list;
import java.lang.reflect.Array;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import model.linearpub.DynamicList;
import model.linearpub.StructureIterator;
//This class is NOT java.util.LinkedList
public class LinkedList<E> implements DynamicList<E> {
//---------------------------------
// Instance Variables
//TODO - declare instance variable(s)
//---------------------------------
// Private Constructor
/** Constructs and returns new LinkedList (no args constructor) */
private LinkedList() {
}
//-------------------- List Statistics ---------------------
/**
* Return number of elements in this list.
*/
@Override
public int size() {
//TODO
return 0;
}
/**
* Return true is this list contains no elements.
*/
@Override
public boolean isEmpty() {
//TODO
return false;
}
//------------------ Accessing Elements --------------------
/**
* Return element at given index.
* Throws IndexOutOfBoundsException if passed index is invalid.
*/
@Override
public E get(int index) {
//TODO
return null;
}
/**
* Return first element
* Throws RuntimeException if list is empty
*/
@Override
public E first() {
//TODO
return null;
}
/**
* Return last element
* Throws RuntimeException if list is empty
*/
@Override
public E last() {
//TODO
return null;
}
/**
* Return a new list containing the elements of this list
* between the given index "start" (inclusive) and
* the given index "stop" (exclusive).
* Throws IndexOutOfBoundsException if either passed index is invalid.
*/
@Override
public DynamicList<E> subList(int start, int stop) {
//TODO
return null;
}
/**
* Return index of first matching element (where searchFct outputs true)
* Return -1 if no match
* Example usage (first list of integers, then employees):
* index = list.find(eaInteger -> eaInteger == 10);
* index = employeeList.find(employee -> employee .getFirstName().equals("Kofi"));
*/
@Override
public int findFirst(Function<E, Boolean> searchFct) {
//TODO
return 0;
}
/**
* Return index of last matching element (where searchFct outputs true)
* E.g., if searching for employee with name "Kofi" and there is a match
* at index=3 and index=8, findLast will return 8 (the last matching index).
* Hint: start search at end of list and work backwards through list.
* Return -1 if no match
*/
@Override
public int findLast(Function<E, Boolean> searchFct.
java question Fill the add statement areaProject is to wo.pdfdbrienmhompsonkath75
java question: \"Fill the add statement area\"
Project is to work with stacks.
package p2;
public class Coordinate {
public int x;
public int y;
public Coordinate( int x, int y ) {
this.x = x;
this.y = y;
}
public String toString() {
return \"(\" + this.x + \",\" + this.y + \")\";
}
@Override
public boolean equals( Object object ) {
if( object == null ) {
return false;
}
if( ! Coordinate.class.isAssignableFrom( object.getClass() )) {
return false;
}
final Coordinate other = (Coordinate) object;
return this.x == other.x && this.y == other.y;
}
}
package p2;
public class Coordinate {
public int x;
public int y;
public Coordinate( int x, int y ) {
this.x = x;
this.y = y;
}
public String toString() {
return \"(\" + this.x + \",\" + this.y + \")\";
}
@Override
public boolean equals( Object object ) {
if( object == null ) {
return false;
}
if( ! Coordinate.class.isAssignableFrom( object.getClass() )) {
return false;
}
final Coordinate other = (Coordinate) object;
return this.x == other.x && this.y == other.y;
}
}
package p2;
import java.util.Vector;
public class Maze {
private char[][] maze;
private int height;
private int width;
/**
* Create a new Maze of the specified height and width, initializing every
* location as empty, with a \' \'.
**/
public Maze( int width, int height ) {
// ADD STATEMENTS HERE
}
/**
* Mutator to allow us to set the specified Coordinate as blocked,
* marking it with a \'X\'
**/
public void setBlocked( Coordinate coord ) {
// ADD STATEMENTS HERE
}
/**
* Mutator to allow us to set the specified Coordinate as having been visited,
* marking it with a \'*\'
**/
public void setVisited( Coordinate coord ) {
// ADD STATEMENTS HERE
}
/**
* Mutator to allow us to set the specified Coordinate as part of the path solution,
* marking it with a \'.\'
**/
public void setPath( Coordinate coord ) {
// ADD STATEMENTS HERE
}
/**
* Returns the character at the locatio specified by the Coordinate
**/
public char at( Coordinate coord ) {
// ADD STATEMENTS HERE
}
/**
* Returns a Coordinate array containing all Coordinates that are clear around
* the specified coordinate.
**/
public Coordinate[] clearAround( Coordinate coord ) {
Vector vector = new Vector();
// ADD STATEMENTS HERE
// Look at each of the locations around the specified Coordinate, and add it
// to the vector if it is clear (i.e. a space)
return vector.toArray( new Coordinate[0] );
}
/**
* Returns a Coordinate that provides the entrance location in this maze.
**/
public Coordinate start() {
return new Coordinate( 0, 1 );
}
/**
* Returns a Coordinate that provides the exit location from this maze.
**/
public Coordinate end() {
// ADD STATEMENTS HERE
}
/**
* The toString() method is responsible for creating a String representation
* of the Maze. See the project specification for sample output. Note that
* the String representation adds numbers across the top and side of the Maze
* to show the Coordinates of each cell in the maze.
**/
public String toString() {
StringBuilder buffer =.
Here is what I got so far, I dont know how to write union, interse.pdfarihantpatna
Gomez runs a small pottery firm. He hires one helper at $11,500 per year, pays annual rent of
$7,000 for his shop, and spends $22,500 per year on materials. He has $40,000 of his own funds
invested in equipment (pottery wheels, kilns, and so forth) that could earn him $6,500 per year if
alternatively invested. He has been offered $22,000 per year to work as a potter for a competitor.
He estimates his entrepreneurial talents are worth $4,500 per year (input cost for organizing
resources). Total annual revenue from pottery sales is $80,000. Calculate the accounting profit
and the economic profit for Gomez’s pottery firm.
Accounting Profit = $
Economic Profit = $
Solution
Let me first tell you what it is, so that you understand better -
In calculating economic profit, opportunity costs are deducted from revenues earned.
Opportunity costs are the alternative returns foregone by using the chosen inputs. As a result,
you can have a significant accounting profit with little to no economic profit.
For example, say you invest $100,000 to start a business, and in that year you earn $120,000 in
profits. Your accounting profit would be $20,000. However, say that same year you could have
earned an income of $45,000 had you been employed. Therefore, you have an economic loss of
$25,000 (120,000 - 100,000 - 45,000).Per AnnumHelper Salary11,500Shop Rent7000material
cost22500Gomez funds40000Alternate Investment income6,500Gomez goodwill
talent4500Annual Sales Revenue80000Annual Salary as potter22000Total Salary when working
as Potter22000+6500 = 28,500Total CostHelper Salary11,500Shop Rent7000Material
cost22500Gomez entrepreneurial talent450045,500Annual Sales Revenue80000Accounting
profit80,000 -45,500 = 34,500Economic Profit=34,500 -28,500=6000.
java write a program to evaluate the postfix expressionthe program.pdfarjuntelecom26
java write a program to evaluate the postfix expression
the program should ask users for input and show the postfix epression and then the result.
and to have a try and catch exception since we have an empty stack
Solution
Postfix.java
import java.util.Scanner;
public class Postfix
{
/**
* Reads and evaluates multiple postfix expressions.
*/
public static void main (String[] args)
{
String expression, again;
int result;
try
{
Scanner in = new Scanner(System.in);
do
{
PostfixEvaluator evaluator = new PostfixEvaluator();
System.out.println (\"Enter a valid postfix expression: \");
expression = in.nextLine();
result = evaluator.evaluate (expression);
System.out.println();
System.out.println (\"That expression equals \" + result);
System.out.print (\"Evaluate another expression [Y/N]? \");
again = in.nextLine();
System.out.println();
}
while (again.equalsIgnoreCase(\"y\"));
}
catch (Exception IOException)
{
System.out.println(\"Input exception reported\");
}
}
}
PostfixEvaluator.java
//import datastructures.ArrayStack;
import java.util.StringTokenizer;
public class PostfixEvaluator
{
/** constant for addition symbol */
private final char ADD = \'+\';
/** constant for subtraction symbol */
private final char SUBTRACT = \'-\';
/** constant for multiplication symbol */
private final char MULTIPLY = \'*\';
/** constant for division symbol */
private final char DIVIDE = \'/\';
/** the stack */
private ArrayStack stack;
/**
* Sets up this evaluator by creating a new stack.
*/
public PostfixEvaluator()
{
stack = new ArrayStack();
}
/**
* Evaluates the specified postfix expression. If an operand is
* encountered, it is pushed onto the stack. If an operator is
* encountered, two operands are popped, the operation is
* evaluated, and the result is pushed onto the stack.
* //param expr String representation of a postfix expression
* //return int value of the given expression
*/
public int evaluate (String expr)
{
int op1, op2, result = 0;
String token;
StringTokenizer tokenizer = new StringTokenizer (expr);
while (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();
if (isOperator(token))
{
op2 = (stack.pop()).intValue();
op1 = (stack.pop()).intValue();
result = evalSingleOp (token.charAt(0), op1, op2);
stack.push (new Integer(result));
}
else
stack.push (new Integer(Integer.parseInt(token)));
}
return result;
}
/**
* Determines if the specified token is an operator.
* //param token String representing a single token
* //return boolean true if token is operator
*/
private boolean isOperator (String token)
{
return ( token.equals(\"+\") || token.equals(\"-\") ||
token.equals(\"*\") || token.equals(\"/\") );
}
/**
* Performs integer evaluation on a single expression consisting of
* the specified operator and operands.
* //param operation operation to be performed
* //param op1 the first operand
* //param op2 the second operand
* //return int value of the expression
*/
private int evalSingleOp (char operation, int op1, int op2)
{
int result = 0;
switch .
In this lab, we will write an application to store a deck of cards i.pdfcontact41
In this lab, we will write an application to store a deck of cards in a linked list, and then write
methods to sort and shuffle the deck.
Copy your completed LinkedList class from Lab 4 into the LinkedList.java file below.
Complete all methods of the Card class as described by the Javadoc comments. The class
contains both a suit and a rank. A suit is one of the categories into which the cards of a deck are
divided. The rank is the relative importance of the card within its suit.
Note that the Card constructor must convert any rank and suit letters to uppercase.
For the equals() method, be sure to follow the steps outlined in Lesson 4. How to implement the
compareTo() method is also covered in Lesson 4.
Note that you are not allowed to add any additional methods or member variables to this class or
you will not receive credit for this assignment.
Complete all methods of the CardApp class in the CardApp.java file as described by the Javadoc
comments.
You may add as many methods as you would like to this file, but are not allowed to add any
additional member variables.
The CardApp program must prompt for and allow the user to enter the name of any input file as
shown in the Example output below.
Implement the shuffle() method as specified in the comments for shuffle(). After you have
shuffled the deck of cards, write the result into a file named shuffled.txt.
Implement the sort() method using bubble sort from Lesson 4. First sort by suit in alphabetical
order and then by rank from 2 to A. The pseudocode for bubble sort is as follows:
After you have sorted the deck of cards, write the result to a file named sorted.txt.
The CardApp.java file also contains the main() method of the application. Use Develop mode to
test your CardApp code along with your Card and LinkedList code.
All input and output files must contain a list of cards, with each card stored on its own line. See
the example files cards1.txt and cards2.txt for example file formats.
[[[cards1.txt]]]
2H
3H
4H
5H
6H
7H
8H
9H
10H
JH
[[[cards2.txt]]]
AS
2S
3S
4S
5S
6S
7S
8S
9S
10S
JS
QS
KS
AC
2C
3C
4C
5C
6C
7C
8C
9C
10C
JC
QC
KC
AH
2H
3H
4H
5H
6H
7H
8H
9H
10H
JH
QH
KH
AD
2D
3D
4D
5D
6D
7D
8D
9D
10D
JD
QD
KD
[[[CardApp.java]]]
/**
* CardApp.java
* @author Your name
* @author Partner's name
* CIS 22C, Applied Lab 1
*/
public class CardApp {
private LinkedList list;
/**
* User interface prompts user, reads and writes files.
*/
public static void main(String[] args) {
}
/**
* Default constructor to initialize the deck
*/
public CardApp() {
}
/**
* Inserts a new Card into the deck
* @param card a playing Card
*/
public void addCard(Card card) {
}
/**
* Shuffles cards following this algorithm:
* First swaps first and last card
* Next, swaps every even card with the card 3
* nodes away from that card. Stops when it
* reaches the 3rd to last node
* Then, swaps ALL cards with the card that is
* 2 nodes away from it, starting at the 2nd card
* and stopping stopping at the 3rd to last node
*/
public vo.
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.
steps are as follows Dissolve the (pressumably.pdfLalkamal2
steps are as follows : Dissolve the (pressumably solid) mixture in an organic
solven,,,,,,, Then, in a seperating funnel, add an (Aqueous) solution of sodium hydroxide. The
Phenol, and benzoic acid, as acids, will react with the base to form phenolate and benzenoate
ions, which will dissolve into the water layer. Collect this layer, and re-precipitate the organic
molecules by adding concentrated Hydrochloric acid. The phenol and Benzoic acid can be
seperated via their varying solubilities, (8.3g/100ml vs 0.34g/100ml. respectively) by heating the
mixture in water to dissolve the phenol, and then filtering of the (practically) insoluble benzoic
acid. The solution can then be acidified (with HCl) to return the phenol..,,,,,,,,,,,,, Now add a
solution of hydrochloric acid to the seperating funnel, which (as before) will react with the basic
anniline dossilving it into the water. Collect the aqueous layer and re-precipitate the anniline
with excess sodium hydroxide. ,,,,,,,,,,,,,,, finally boil off the remaining organic solvent to obtain
the napthalene, which was left untouched by all the acids and bases.,,,,,,,,, Flow chart : Mixture
+ xs HCl ----> anilinium(aq) Mixture - aniline + weak base (Na2CO3) ---> benzoate(aq)
Mixture - aniline - benzoic acid + base (NaOH) ---> p-bromophenoxide(aq) Mixture - aniline -
benzoic acid - p-bromophenol = naphthalene
Solution
steps are as follows : Dissolve the (pressumably solid) mixture in an organic
solven,,,,,,, Then, in a seperating funnel, add an (Aqueous) solution of sodium hydroxide. The
Phenol, and benzoic acid, as acids, will react with the base to form phenolate and benzenoate
ions, which will dissolve into the water layer. Collect this layer, and re-precipitate the organic
molecules by adding concentrated Hydrochloric acid. The phenol and Benzoic acid can be
seperated via their varying solubilities, (8.3g/100ml vs 0.34g/100ml. respectively) by heating the
mixture in water to dissolve the phenol, and then filtering of the (practically) insoluble benzoic
acid. The solution can then be acidified (with HCl) to return the phenol..,,,,,,,,,,,,, Now add a
solution of hydrochloric acid to the seperating funnel, which (as before) will react with the basic
anniline dossilving it into the water. Collect the aqueous layer and re-precipitate the anniline
with excess sodium hydroxide. ,,,,,,,,,,,,,,, finally boil off the remaining organic solvent to obtain
the napthalene, which was left untouched by all the acids and bases.,,,,,,,,, Flow chart : Mixture
+ xs HCl ----> anilinium(aq) Mixture - aniline + weak base (Na2CO3) ---> benzoate(aq)
Mixture - aniline - benzoic acid + base (NaOH) ---> p-bromophenoxide(aq) Mixture - aniline -
benzoic acid - p-bromophenol = naphthalene.
the two features of the asynchronus connection that allow the receiv.pdfLalkamal2
the two features of the asynchronus connection that allow the receiver to stay in sync with the
incoming data stream are the start bit and short frame connections . asynchronus connection are
asynchronus serial communications in which the communicating end points interfaces are not
continously synchronized by common clock signal and the data stream contains synchronization
in the form of start and stop signals before and after each unit of transmission .asynchronus start
and stop signals was widley used for dial up modem sources to time sharing computers and bbs
systems asynchronus start stop is the physical layer is used to connect computers to modems for
many dial up internet access applications using data link frame protocol such as ppp to create
packets made upto out of asynchronous serial characters .the examples that would benefit from
asynchronous connection are modems and usb that are connectedd to interfaces
Solution
the two features of the asynchronus connection that allow the receiver to stay in sync with the
incoming data stream are the start bit and short frame connections . asynchronus connection are
asynchronus serial communications in which the communicating end points interfaces are not
continously synchronized by common clock signal and the data stream contains synchronization
in the form of start and stop signals before and after each unit of transmission .asynchronus start
and stop signals was widley used for dial up modem sources to time sharing computers and bbs
systems asynchronus start stop is the physical layer is used to connect computers to modems for
many dial up internet access applications using data link frame protocol such as ppp to create
packets made upto out of asynchronous serial characters .the examples that would benefit from
asynchronous connection are modems and usb that are connectedd to interfaces.
More Related Content
Similar to Modifications highlighted in bold lettersDropOutStack.javaim.pdf
create a new interface called DropoutStackADT for representing a dro.pdff3apparelsonline
create a new interface called DropoutStackADT for representing a dropout stack. It should
contain exactly the same methods as StackADT, and have documentation for the file and each
method in proper javadoc. Your file will be different from StackADT since a dropout stack acts
differently than a normal stack. When documenting methods that should support throwing an
exception, make a note in its javadocdescription.
Implement a drop-out stack using a linked structure. You use the LinearNode or
LinearDoubleNode classes. Follow the DropoutStackADT interface. See Base_A11Q3.java for a
starting place.
STACKADT
LinearDoubleNode
/**
* Represents a node in a linked list.
*
* @author Java Foundations
* @version 4.0
*/
public class LinearDoubleNode
{
private LinearDoubleNode next,prev;
private T element;
/**
* Creates an empty node.
*/
public LinearDoubleNode()
{
next = null;
element = null;
prev = null;
}
/**
* Creates a node storing the specified element.
* @param elem element to be stored
*/
public LinearDoubleNode(T elem)
{
next = null;
element = elem;
prev = null;
}
/**
* Returns the node that follows this one.
* @return reference to next node
*/
public LinearDoubleNode getNext()
{
return next;
}
/**
* Sets the node that follows this one.
* @param node node to follow this one
*/
public void setNext(LinearDoubleNode node)
{
next = node;
}
/**
* Returns the element stored in this node.
* @return element stored at the node
*/
public T getElement()
{
return element;
}
/**
* Sets the element stored in this node.
* @param elem element to be stored at this node
*/
public void setElement(T elem)
{
element = elem;
}
public LinearDoubleNode getPrev(){
return prev;
}
public void setPrev(LinearDoubleNode node){
prev = node;
}
}
Base File DROP-OUT STACK TESTING The size of the stack is: 4 The stack contains: The size
of the stack is 4 The stack contains:
Solution
public class DropOutStack implements StackADT {
private final int DEFAULT_CAPACITY = 10;
// refers to the item in the array being indexed
private int cIndex;
// holds the count of the stack
private int count;
private T[] stack;
public DropOutStack() {
cIndex = count = 0;
stack = (T[]) (new Object[DEFAULT_CAPACITY]);
}
public DropOutStack(int initialCapacity) {
cIndex = count = 0;
stack = (T[]) (new Object[initialCapacity]);
}
public T peek() throws EmptyCollectionException {
if (isEmpty())
throw new EmptyCollectionException(\"Drop-out Stack\");
return stack[(cIndex + stack.length - 1)%stack.length];
}
public T pop() throws EmptyCollectionException {
if (isEmpty())
throw new EmptyCollectionException(\"Drop-out Stack\");
cIndex = (cIndex + stack.length - 1)%stack.length;
T result = stack[cIndex];
stack[cIndex] = null;
count--;
return result;
}
public void push(T element) {
cIndex = cIndex % stack.length;
stack[cIndex] = element;
cIndex++;
if (count != stack.length)
count++;
}
public int size() {
return count;
}
public boolean isEmpty() {
return size() == 0;
}
public String toString() {
String str = \"\";
i.
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
So I have this code( StackInAllSocks ) and I implemented the method but I can't seem to figure
out why there isn't anything showing up on the console. It should pop,peek and push b using the
methods from the class called ArrayListTen . The ArrayListTen works fine and compiles the
tested code of Rigth# but for StackInAllSocks it doesn't complete at all. note that file
VodeDodeis not to be changed is just a Node storage area of the array list.
Did I implement the method on StackInAllSocks correctly? if so, should I not use the method
from the ArrayListTen .?
__________________________________________________________________________
: the code is : VodeDodeis
class VodeDode<T> {
private T data;
private VodeDode<T> next;
private VodeDode<T> prev;
public VodeDode(T data) {
this.data = data;
this.next = null;
this.prev = null;}
public T getData() {
return data;}
public void setData(T data) {
this.data = data;}
public VodeDode<T> getNext() {
return this.next;}
public void setNext(VodeDode<T> next) {
this.next = next;}
public VodeDode<T> getPrev() {
return this.prev;}
public void setPrev(VodeDode<T> prev) {
this.prev = prev;}
@Override
public String toString() {
return data.toString();}}
_________________________________________________________________________
CODE that works fine called ArrayListTen:
import java.util.Iterator;
public class ArrayListTen<T> implements Iterable<T> {
private VodeDode<T> head; //beginning of list
private VodeDode<T> tail; //end of list
private int size;
private VodeDode<T> new_item;
public ArrayListTen( ){
this.head = null;
this.tail = null;
this.size = 0;}
public int lenght() {
return size ;}
public T getBegin() {
if (this.head != null) {
return head.getData();}
else { return null;}}
public void addBegin(T value) {
VodeDode<T> newVodeDode =new VodeDode<T>(value);
if (this.head== null) {
head = newVodeDode;
tail =newVodeDode;}
else {VodeDode<T> temp = head;
head = newVodeDode;
head.setNext(temp);}
size++;}
public T removeBegin() {
if(this.head == null) {
return null;}
else {T current = head.getData();
if (tail == head) {
tail = null;
head = null;
} else {
head = head.getNext();
head.setPrev(null);}size--;
return current;}}
public T getEnd() {
if (tail != null) {
return tail.getData();
} else {
return null;}}
public void addEnd(T value) {
VodeDode<T> newVodeDode = new VodeDode<T>(value);
if (this.tail == null) {
head = newVodeDode;
tail = newVodeDode;
} else {
newVodeDode.setPrev(tail);
tail.setNext(newVodeDode);
tail = newVodeDode;}
size++;}
public T removeEnd() {
if(this.tail == null) {
return null;}
else {
T current = tail.getData();//was head.
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.getPrev();
tail.setNext(null);}
size--;
return current;}}
public T removeBN(T value) {
VodeDode<T> currVodeDode = head;
VodeDode<T> prevVodeDode = null;
while(currVodeDode != null){
if(currVodeDode.getData().equals(value)){
if(prevVodeDode != null){
prevVodeDode.setNext(currVodeDode.getNext());}
else{
head = curr.
Given the following ADT definition of a stack to use stack .docxshericehewat
Given the following ADT definition of a stack to use:
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*
* @returns int The current size (number of items) on the stack.
*/
virtual int size() const = 0;
};
perform the following tasks by writing code that uses a stack to accomplish the task. You will
need to create a stack of the needed type, then use the methods of the stack abstraction (push,
top, pop, etc.) to solve the given task asked for.
Question 7 (5 points)
Given a stack of integers, calculate the sum of the integer values. Also, the stack should still be
unchanged after you have calculated the sum Hint: take the items off the stack to sum them up
and keep them on a second temporary stack so you can put them all back on after you have
calculated the sum.
ANSWER FOR NUMBER 7:
int sumStackOfIntegers(Stack<int> currentStack) {
Stack<int> tempStack;
int sum = 0;
while(!currentStack.isEmpty()) {
int temp = currentStack.top();
tempStack.push(temp);
currentStack.pop();
sum += temp;
}
while(!tempStack.isEmpty()) {
int temp = tempStack.top();
currentStack.push(temp);
tempStack.pop();
}
return sum;
}
Stack Implementation
Given the following linked list implementation of a Stack ADT (this is the same implementation
you used in Assignment 10), add the asked for additional member methods to the linked list stack
implementation.
/** Node
* A basic node contaning an item and a link to t ...
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
StackInterface
/**
An interface for the ADT stack.
Do not modify this file
*/
package PJ2;
public interface StackInterface
{
/** Gets the current number of data in this stack.
@return the integer number of entries currently in the stack*/
public int size();
/** Adds a new data to the top of this stack.
@param aData an object to be added to the stack */
public void push(T aData);
/** Removes and returns this stack\'s top data.
@return either the object at the top of the stack or,
if the stack is empty before the operation, null */
public T pop();
/** Retrieves this stack\'s top data.
@return either the data at the top of the stack or
null if the stack is empty */
public T peek();
/** Detects whether this stack is empty.
@return true if the stack is empty */
public boolean empty();
/** Removes all data from this stack */
public void clear();
} // end StackInterface
SimpleLinkedStack.java
/**
A class of stacks whose entries are stored in a chain of nodes.
Implement all methods in SimpleLinkedStack class using
the inner Node class.
Main Reference : text book or class notes
Do not change or add data fields
Do not add new methods
You may access Node object fields directly, i.e. data and next
*/
package PJ2;
public class SimpleLinkedStack implements StackInterface
{
// Data fields
private Node topNode; // references the first node in the chain
private int count; // number of data in this stack
public SimpleLinkedStack()
{
// add stataments
} // end default constructor
public void push(T newData)
{
// add stataments
} // end push
public T peek()
{
// add stataments
return null;
} // end peek
public T pop()
{
// add stataments
return null;
} // end pop
public boolean empty()
{
// add stataments
return false;
} // end empty
public int size()
{
// add stataments
return -1;
} // end isEmpty
public void clear()
{
// add stataments
} // end clear
public String toString()
{
// add stataments
// note: data class in stack must implement toString() method
// return a list of data in Stack, separate them with \',\'
return \"\";
}
/****************************************************
private inner node class
Do not modify this class!!
you may access data and next directly
***************************************************/
private class Node
{
private T data; // entry in list
private Node next; // link to next node
private Node (T dataPortion)
{
data = dataPortion;
next = null; // set next to NULL
} // end constructor
private Node (T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode; // set next to refer to nextNode
} // end constructor
} // end Node
/****************************************************
Do not modify: Stack test
****************************************************/
public static void main (String args[])
{
System.out.println(\"\ \"+
\"*******************************************************\ \"+
\"Sample Expected output:\ \"+
\"\ \"+
\"OK: stack is empty\ \"+
\"Push 3 data: 10, 30, 50\ \"+
\"Print stack [50,30,10,]\ \"+
\"OK: sta.
we using java code DynamicArrayjava Replace all .pdfgudduraza28
we using java code /** * DynamicArray.java * * Replace all //TODO tags with your code * * Note
that below the "//TODO" tag there may be * something like "return null;", "return 0;", etc. * That line
is just "stubbed in" so the class * will compile. When you add your code (one or many *
statements), you will want to delete the "stubbed" line. * By "stubbed in" we mean "mocked" or
"faked in" temporarily. * * When testing, construct using the static factory methods:
DynamicList.newEmpty() DynamicList.fromGrowthFactor(growthFactor)
DynamicList.from(arrayElements) */ package model.list; import java.lang.reflect.Array; import
java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import
java.util.function.Consumer; import java.util.function.Function; import
model.linearpub.DynamicList; import model.linearpub.StructureIterator; public class
DynamicArray<E> implements DynamicList<E> { //--------------------------------- // Instance Variables
//TODO - declare instance variable(s) //--------------------------------- // Private Constructors /**
Constructs and returns new DynamicArray (no args constructor) */ private DynamicArray() {
this(defaultGrowthFactor()); } /** Constructs and returns new DynamicArray with "aGrowthFactor"
*/ private DynamicArray(double aGrowthFactor) { //TODO -- this is the constructor that should
//initialize the dynamic array as needed } //------------------------------------------------ public static double
defaultGrowthFactor() { //TODO - replace 0 with a good growth factor return 0; } protected static int
defaultInitialCapacity() { //TODO - replace 0 with a good initial capacity return 0; } //--------------------
List Statistics --------------------- /** * Return number of elements in this list. */ @Override public int
size() { //TODO return 0; } /** * Return true is this list contains no elements. */ @Override public
boolean isEmpty() { //TODO return false; } //------------------ Accessing Elements -------------------- /**
* Return element at given index. * Throws IndexOutOfBoundsException if passed index is invalid.
*/ @Override public E get(int index) { //TODO return null; } /** * Return first element * Throws
RuntimeException if list is empty */ @Override public E first() { //TODO return null; } /** * Return
last element * Throws RuntimeException if list is empty */ @Override public E last() { //TODO
return null; } /** * Return a new list containing the elements of this list * between the given index
"start" (inclusive) and * the given index "stop" (exclusive). * Throws IndexOutOfBoundsException if
either passed index is invalid. */ @Override public DynamicList<E> subList(int start, int stop) {
//TODO return null; } /** * Return index of first matching element (where searchFct outputs true) *
Return -1 if no match * Example usage (first list of integers, then employees): * index =
list.find(eaInteger -> eaInteger == 10); * index = employeeList.find(employee -> employee
.getFirstName().equals("Kofi.
A linked stack is implemented using a standard Node class as follows.pdfkisgstin23
A linked stack is implemented using a standard Node class as follows: import java.util.*; class
stack implements Iterable {private Node top; private int size; public stack () {top = null; size =
0;} public Object pop() {if (size == 0) throw new RuntimeException (\"\"); Object answer =
top.getData (); top = top.getNext (); Size --; return answer;} public void push (Object x) {Node
newNode = new Node (x top); top = newNode; size++;}//the iterator method is missing} Write a
class StackIterator to implement objects that can be returned by the stack iterator. Also write the
missing stack method called iterator. You can decide whether the iterator will run through the
data in the stack in LIFO or FIFO order (one choice is much easier).
Solution
Hi,
Pease find the program below:
import java.util.*;
import java.lang.Iterable;
@SuppressWarnings(\"rawtypes\")
public class LinkedStack implements Iterable{
private int n; // size of the stack
private Node first; // top of stack
// Helper linked list class
private class Node {
private Object item;
private Node next;
}
/**
* Initializes an empty stack.
*/
public LinkedStack() {
first = null;
n = 0;
}
/**
* Is this stack empty?
* @return true if this stack is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
}
/**
* Returns the number of items in the stack.
*/
public int size() {
return n;
}
/**
* Adds the item to this stack.
*/
public void push(Object item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
/**
* Removes and returns the item most recently added to this stack.
* @return the item most recently added
*/
public Object pop() {
if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");
Object item = first.item; // save item to return
first = first.next; // delete first node
n--; //decreases the size by 1
return item; // return the saved item
}
/**
* Returns (but does not remove) the item most recently added to this stack.
* @return the item most recently added to this stack
*/
public Object peek() {
if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");
return first.item;
}
/**
* Returns an iterator to this stack that iterates through the items in LIFO order.
*/
public Iterator iterator() {
return new ListIterator();
}
// an iterator, doesn\'t implement remove() since it\'s optional
private class ListIterator implements Iterator {
private int i = n;
private Node first1 = first; //the first node
public boolean hasNext()
{
return (i > 0);
}
public Object next()
{
Object item = first1.item;
first1 = first1.next;
i--;
return item;
}
public void remove()
{
// not needed as this is optional
}
}
//Main method to implement the test
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedStack */
LinkedStack ls = new LinkedStack();
/* Perform Stack Operations */
System.out.println(\"Linked Stack Test\ \");
char ch;
do
{
System.out.println(\"\ Linked Stack .
EmptyCollectionException-java -- - Represents the situation in which.docxBlakeSGMHemmingss
EmptyCollectionException.java
/*
* Represents the situation in which a collection is empty.
*/
public class EmptyCollectionException extends RuntimeException
{
/* General class level objects */
/*
* Sets up this exception with an appropriate message.
* @param collection the name of the collection
*/
public EmptyCollectionException(String collection)
{
super("The " + collection + " is empty.");
}
}
PriorityNode.java
/*
* Represents a node in a linked list.
*/
public class PriorityNode<T>
{
/* General class level objects */
private PriorityNode<T> _next;
private T _element;
private int _priority;
private final int _MAX_PRIORITY = 100;
/*
* Creates an empty node with a given priority.
*/
public PriorityNode(T elem, int priority)
{
// TODO To be completed as a Programming Project
}
/*
* Creates a node storing the specified element with a default priority.
*
* @param elem element to be stored
*/
public PriorityNode(T elem)
{
// TODO To be completed as a Programming Project
}
/*
* Returns the node that follows this one.
*
* @return reference to next node
*/
public PriorityNode<T> getNext()
{
// TODO To be completed as a Programming Project
}
/*
* Sets the node that follows this one.
*
* @param node node to follow this one
*/
public void setNext(PriorityNode<T> node)
{
// TODO To be completed as a Programming Project
}
/*
* Returns the element stored in this node.
*
* @return element stored at the node
*/
public T getElement()
{
// TODO To be completed as a Programming Project
}
/*
* Returns the priority of this node.
*
* @return element priority the node
*/
public int getPriority()
{
// TODO To be completed as a Programming Project
}
/*
* Sets the element stored in this node.
*
* @param elem element to be stored at this node
*/
public void setElement(T elem)
{
// TODO To be completed as a Programming Project
}
/*
* optional toString() override.
*/
//public String toString()
//{
// // TODO To be completed as a Programming Project
//}
}
PriorityQueue.java
/*
* LinkedQueue represents a linked implementation of a queue.
*/
public class PriorityQueue<T> implements PriorityQueueADT<T>
{
/* General class level objects */
private int _count;
private PriorityNode<T> _head, _tail;
/*
* Constructor - Creates an empty queue.
*/
public PriorityQueue()
{
_count = 0;
_head = _tail = null;
}
/*
* Adds one element to the rear of this queue.
* Higher priorities are inserted closer to the front of the queue
* Items with the same priority are processed in normal queue order
*
* @param element the element to be added to the rear of the queue
* @param priority relative priority of the queue item
*/
public void enqueue(T element, int priority)
{
// TODO To be completed as a Programming Project
// add in-order insertion of the PriorityNode based on getPriority() value
// the higher the priority is the closer to head it gets
// equivalent priority is normal .
Please do parts labeled TODO LinkedList.java Replace.pdfaioils
Please do parts labeled TODO
/**
* LinkedList.java
*
* Replace all //TODO tags with your code
*
* Note that below the "//TODO" tag there may be
* something like "return null;", "return 0;", etc.
* That line is just "stubbed in" so the class
* will compile. When you add your code (one or many
* statements), you will want to delete the "stubbed" line.
* By "stubbed in" we mean "mocked" or "faked in" temporarily.
*
* When testing, construct using the static factory methods:
LinkedList.newEmpty()
LinkedList.from(arrayElements)
*/
package model.list;
import java.lang.reflect.Array;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import model.linearpub.DynamicList;
import model.linearpub.StructureIterator;
//This class is NOT java.util.LinkedList
public class LinkedList implements DynamicList {
//---------------------------------
// Instance Variables
//TODO - declare instance variable(s)
//---------------------------------
// Private Constructor
/** Constructs and returns new LinkedList (no args constructor) */
private LinkedList() {
}
//-------------------- List Statistics ---------------------
/**
* Return number of elements in this list.
*/
@Override
public int size() {
//TODO
return 0;
}
/**
* Return true is this list contains no elements.
*/
@Override
public boolean isEmpty() {
//TODO
return false;
}
//------------------ Accessing Elements --------------------
/**
* Return element at given index.
* Throws IndexOutOfBoundsException if passed index is invalid.
*/
@Override
public E get(int index) {
//TODO
return null;
}
/**
* Return first element
* Throws RuntimeException if list is empty
*/
@Override
public E first() {
//TODO
return null;
}
/**
* Return last element
* Throws RuntimeException if list is empty
*/
@Override
public E last() {
//TODO
return null;
}
/**
* Return a new list containing the elements of this list
* between the given index "start" (inclusive) and
* the given index "stop" (exclusive).
* Throws IndexOutOfBoundsException if either passed index is invalid.
*/
@Override
public DynamicList subList(int start, int stop) {
//TODO
return null;
}
/**
* Return index of first matching element (where searchFct outputs true)
* Return -1 if no match
* Example usage (first list of integers, then employees):
* index = list.find(eaInteger -> eaInteger == 10);
* index = employeeList.find(employee -> employee .getFirstName().equals("Kofi"));
*/
@Override
public int findFirst(Function searchFct) {
//TODO
return 0;
}
/**
* Return index of last matching element (where searchFct outputs true)
* E.g., if searching for employee with name "Kofi" and there is a match
* at index=3 and index=8, findLast will return 8 (the last matching index).
* Hint: start search at end of list and work backwards through list.
* Return -1 if no match
*/
@Override
public int findLast(Function searchFct) {
//TODO
return 0;
}
//------------------- Setting Elem.
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 *.
package ADTs public interface CollectionADTltTgt .pdfsyedabdul78662
package ADTs;
public interface CollectionADT<T> {
public boolean isEmpty();
public int size();
@Override
public String toString();
}
**********************************************************
package ADTs;
import Exceptions.*;
/**
* An interface for an ordered (NOT SORTED) List
* Elements stay in the order they are put in to the list
* For use in Data Structures & Algorithms
*
*
* @author
*/
public interface ListADT<T> extends CollectionADT<T> {
/**
* Adds the specified element to the list at the front
*
* @param element: the element to be added
*
*/
public void addFirst(T element);
/**
* Adds the specified element to the end of the list
*
* @param element: the element to be added
*/
public void addLast(T element);
/**
* Adds the specified element to the list after the existing element
*
* @param existing: the element that is in the list already
* @param element: the element to be added
* @throws ElementNotFoundException if existing isn't in the list
*/
public void addAfter(T existing, T element) throws ElementNotFoundException,
EmptyCollectionException;
/**
* Removes and returns the specified element
*
* @return the element specified
* @throws EmptyCollectionException
* @throws ElementNotFoundException
*/
public T remove(T element) throws EmptyCollectionException, ElementNotFoundException;
/**
* Removes and returns the first element
*
* @return the first element in the list
* @throws EmptyCollectionException
*/
public T removeFirst() throws EmptyCollectionException;
/**
* Removes and returns the last element
*
* @return the last element in the list
* @throws EmptyCollectionException
*/
public T removeLast() throws EmptyCollectionException;
/**
* Returns (without removing) the first element in the list
*
* @return element at the beginning of the list
* @throws EmptyCollectionException
*/
public T first() throws EmptyCollectionException;
/**
* Returns (without removing) the last element in the list
*
* @return element at the end of the list
* @throws EmptyCollectionException
*/
public T last() throws EmptyCollectionException;
/**
* Return whether the list contains the given element.
*
* @param element
* @return
* @throws EmptyCollectionException
*/
public boolean contains(T element) throws EmptyCollectionException;
/**
* Returns the index of the given element.
*
* @param element
* @return the index of the element, or -1 if not found
*/
public int indexOf(T element);
/**
* Return the element at the given index of a list.
*
* @param element
* @return
* @throws EmptyCollectionException
*/
public T get(int index) throws EmptyCollectionException, InvalidArgumentException;
/**
* Set the at the given index of a list.
*
* @param element
* @return
* @throws EmptyCollectionException
*/
public void set(int index, T element) throws EmptyCollectionException, InvalidArgumentException;
}
**********************************************
package ADTs;
import Exceptions.EmptyCollectionException;
import Exceptions.QueueOverflowException;
public interface QueueADT<.
please read the steps below and it will tell you what we usi.pdfaggarwalopticalsco
please read the steps below and it will tell you what we using
/**
* DynamicArray.java
*
* Replace all //TODO tags with your code
*
* Note that below the "//TODO" tag there may be
* something like "return null;", "return 0;", etc.
* That line is just "stubbed in" so the class
* will compile. When you add your code (one or many
* statements), you will want to delete the "stubbed" line.
* By "stubbed in" we mean "mocked" or "faked in" temporarily.
*
* When testing, construct using the static factory methods:
DynamicList.newEmpty()
DynamicList.fromGrowthFactor(growthFactor)
DynamicList.from(arrayElements)
*/
package model.list;
import java.lang.reflect.Array;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import model.linearpub.DynamicList;
import model.linearpub.StructureIterator;
public class DynamicArray<E> implements DynamicList<E> {
//---------------------------------
// Instance Variables
//TODO - declare instance variable(s)
//---------------------------------
// Private Constructors
/** Constructs and returns new DynamicArray (no args constructor) */
private DynamicArray() {
this(defaultGrowthFactor());
}
/** Constructs and returns new DynamicArray with "aGrowthFactor" */
private DynamicArray(double aGrowthFactor) {
//TODO -- this is the constructor that should
//initialize the dynamic array as needed
}
//------------------------------------------------
public static double defaultGrowthFactor() {
//TODO - replace 0 with a good growth factor
return 0;
}
protected static int defaultInitialCapacity() {
//TODO - replace 0 with a good initial capacity
return 0;
}
//-------------------- List Statistics ---------------------
/**
* Return number of elements in this list.
*/
@Override
public int size() {
//TODO
return 0;
}
/**
* Return true is this list contains no elements.
*/
@Override
public boolean isEmpty() {
//TODO
return false;
}
//------------------ Accessing Elements --------------------
/**
* Return element at given index.
* Throws IndexOutOfBoundsException if passed index is invalid.
*/
@Override
public E get(int index) {
//TODO
return null;
}
/**
* Return first element
* Throws RuntimeException if list is empty
*/
@Override
public E first() {
//TODO
return null;
}
/**
* Return last element
* Throws RuntimeException if list is empty
*/
@Override
public E last() {
//TODO
return null;
}
/**
* Return a new list containing the elements of this list
* between the given index "start" (inclusive) and
* the given index "stop" (exclusive).
* Throws IndexOutOfBoundsException if either passed index is invalid.
*/
@Override
public DynamicList<E> subList(int start, int stop) {
//TODO
return null;
}
/**
* Return index of first matching element (where searchFct outputs true)
* Return -1 if no match
* Example usage (first list of integers, then employees):
* index = list.find(eaInteger -> eaInteger == 10);
* index = employeeList.find(emplo.
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.
please read below it will tell you what we are using L.pdfankit11134
please read below it will tell you what we are using
/**
* LinkedList.java
*
* Replace all //TODO tags with your code
*
* Note that below the "//TODO" tag there may be
* something like "return null;", "return 0;", etc.
* That line is just "stubbed in" so the class
* will compile. When you add your code (one or many
* statements), you will want to delete the "stubbed" line.
* By "stubbed in" we mean "mocked" or "faked in" temporarily.
*
* When testing, construct using the static factory methods:
LinkedList.newEmpty()
LinkedList.from(arrayElements)
*/
package model.list;
import java.lang.reflect.Array;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import model.linearpub.DynamicList;
import model.linearpub.StructureIterator;
//This class is NOT java.util.LinkedList
public class LinkedList<E> implements DynamicList<E> {
//---------------------------------
// Instance Variables
//TODO - declare instance variable(s)
//---------------------------------
// Private Constructor
/** Constructs and returns new LinkedList (no args constructor) */
private LinkedList() {
}
//-------------------- List Statistics ---------------------
/**
* Return number of elements in this list.
*/
@Override
public int size() {
//TODO
return 0;
}
/**
* Return true is this list contains no elements.
*/
@Override
public boolean isEmpty() {
//TODO
return false;
}
//------------------ Accessing Elements --------------------
/**
* Return element at given index.
* Throws IndexOutOfBoundsException if passed index is invalid.
*/
@Override
public E get(int index) {
//TODO
return null;
}
/**
* Return first element
* Throws RuntimeException if list is empty
*/
@Override
public E first() {
//TODO
return null;
}
/**
* Return last element
* Throws RuntimeException if list is empty
*/
@Override
public E last() {
//TODO
return null;
}
/**
* Return a new list containing the elements of this list
* between the given index "start" (inclusive) and
* the given index "stop" (exclusive).
* Throws IndexOutOfBoundsException if either passed index is invalid.
*/
@Override
public DynamicList<E> subList(int start, int stop) {
//TODO
return null;
}
/**
* Return index of first matching element (where searchFct outputs true)
* Return -1 if no match
* Example usage (first list of integers, then employees):
* index = list.find(eaInteger -> eaInteger == 10);
* index = employeeList.find(employee -> employee .getFirstName().equals("Kofi"));
*/
@Override
public int findFirst(Function<E, Boolean> searchFct) {
//TODO
return 0;
}
/**
* Return index of last matching element (where searchFct outputs true)
* E.g., if searching for employee with name "Kofi" and there is a match
* at index=3 and index=8, findLast will return 8 (the last matching index).
* Hint: start search at end of list and work backwards through list.
* Return -1 if no match
*/
@Override
public int findLast(Function<E, Boolean> searchFct.
java question Fill the add statement areaProject is to wo.pdfdbrienmhompsonkath75
java question: \"Fill the add statement area\"
Project is to work with stacks.
package p2;
public class Coordinate {
public int x;
public int y;
public Coordinate( int x, int y ) {
this.x = x;
this.y = y;
}
public String toString() {
return \"(\" + this.x + \",\" + this.y + \")\";
}
@Override
public boolean equals( Object object ) {
if( object == null ) {
return false;
}
if( ! Coordinate.class.isAssignableFrom( object.getClass() )) {
return false;
}
final Coordinate other = (Coordinate) object;
return this.x == other.x && this.y == other.y;
}
}
package p2;
public class Coordinate {
public int x;
public int y;
public Coordinate( int x, int y ) {
this.x = x;
this.y = y;
}
public String toString() {
return \"(\" + this.x + \",\" + this.y + \")\";
}
@Override
public boolean equals( Object object ) {
if( object == null ) {
return false;
}
if( ! Coordinate.class.isAssignableFrom( object.getClass() )) {
return false;
}
final Coordinate other = (Coordinate) object;
return this.x == other.x && this.y == other.y;
}
}
package p2;
import java.util.Vector;
public class Maze {
private char[][] maze;
private int height;
private int width;
/**
* Create a new Maze of the specified height and width, initializing every
* location as empty, with a \' \'.
**/
public Maze( int width, int height ) {
// ADD STATEMENTS HERE
}
/**
* Mutator to allow us to set the specified Coordinate as blocked,
* marking it with a \'X\'
**/
public void setBlocked( Coordinate coord ) {
// ADD STATEMENTS HERE
}
/**
* Mutator to allow us to set the specified Coordinate as having been visited,
* marking it with a \'*\'
**/
public void setVisited( Coordinate coord ) {
// ADD STATEMENTS HERE
}
/**
* Mutator to allow us to set the specified Coordinate as part of the path solution,
* marking it with a \'.\'
**/
public void setPath( Coordinate coord ) {
// ADD STATEMENTS HERE
}
/**
* Returns the character at the locatio specified by the Coordinate
**/
public char at( Coordinate coord ) {
// ADD STATEMENTS HERE
}
/**
* Returns a Coordinate array containing all Coordinates that are clear around
* the specified coordinate.
**/
public Coordinate[] clearAround( Coordinate coord ) {
Vector vector = new Vector();
// ADD STATEMENTS HERE
// Look at each of the locations around the specified Coordinate, and add it
// to the vector if it is clear (i.e. a space)
return vector.toArray( new Coordinate[0] );
}
/**
* Returns a Coordinate that provides the entrance location in this maze.
**/
public Coordinate start() {
return new Coordinate( 0, 1 );
}
/**
* Returns a Coordinate that provides the exit location from this maze.
**/
public Coordinate end() {
// ADD STATEMENTS HERE
}
/**
* The toString() method is responsible for creating a String representation
* of the Maze. See the project specification for sample output. Note that
* the String representation adds numbers across the top and side of the Maze
* to show the Coordinates of each cell in the maze.
**/
public String toString() {
StringBuilder buffer =.
Here is what I got so far, I dont know how to write union, interse.pdfarihantpatna
Gomez runs a small pottery firm. He hires one helper at $11,500 per year, pays annual rent of
$7,000 for his shop, and spends $22,500 per year on materials. He has $40,000 of his own funds
invested in equipment (pottery wheels, kilns, and so forth) that could earn him $6,500 per year if
alternatively invested. He has been offered $22,000 per year to work as a potter for a competitor.
He estimates his entrepreneurial talents are worth $4,500 per year (input cost for organizing
resources). Total annual revenue from pottery sales is $80,000. Calculate the accounting profit
and the economic profit for Gomez’s pottery firm.
Accounting Profit = $
Economic Profit = $
Solution
Let me first tell you what it is, so that you understand better -
In calculating economic profit, opportunity costs are deducted from revenues earned.
Opportunity costs are the alternative returns foregone by using the chosen inputs. As a result,
you can have a significant accounting profit with little to no economic profit.
For example, say you invest $100,000 to start a business, and in that year you earn $120,000 in
profits. Your accounting profit would be $20,000. However, say that same year you could have
earned an income of $45,000 had you been employed. Therefore, you have an economic loss of
$25,000 (120,000 - 100,000 - 45,000).Per AnnumHelper Salary11,500Shop Rent7000material
cost22500Gomez funds40000Alternate Investment income6,500Gomez goodwill
talent4500Annual Sales Revenue80000Annual Salary as potter22000Total Salary when working
as Potter22000+6500 = 28,500Total CostHelper Salary11,500Shop Rent7000Material
cost22500Gomez entrepreneurial talent450045,500Annual Sales Revenue80000Accounting
profit80,000 -45,500 = 34,500Economic Profit=34,500 -28,500=6000.
java write a program to evaluate the postfix expressionthe program.pdfarjuntelecom26
java write a program to evaluate the postfix expression
the program should ask users for input and show the postfix epression and then the result.
and to have a try and catch exception since we have an empty stack
Solution
Postfix.java
import java.util.Scanner;
public class Postfix
{
/**
* Reads and evaluates multiple postfix expressions.
*/
public static void main (String[] args)
{
String expression, again;
int result;
try
{
Scanner in = new Scanner(System.in);
do
{
PostfixEvaluator evaluator = new PostfixEvaluator();
System.out.println (\"Enter a valid postfix expression: \");
expression = in.nextLine();
result = evaluator.evaluate (expression);
System.out.println();
System.out.println (\"That expression equals \" + result);
System.out.print (\"Evaluate another expression [Y/N]? \");
again = in.nextLine();
System.out.println();
}
while (again.equalsIgnoreCase(\"y\"));
}
catch (Exception IOException)
{
System.out.println(\"Input exception reported\");
}
}
}
PostfixEvaluator.java
//import datastructures.ArrayStack;
import java.util.StringTokenizer;
public class PostfixEvaluator
{
/** constant for addition symbol */
private final char ADD = \'+\';
/** constant for subtraction symbol */
private final char SUBTRACT = \'-\';
/** constant for multiplication symbol */
private final char MULTIPLY = \'*\';
/** constant for division symbol */
private final char DIVIDE = \'/\';
/** the stack */
private ArrayStack stack;
/**
* Sets up this evaluator by creating a new stack.
*/
public PostfixEvaluator()
{
stack = new ArrayStack();
}
/**
* Evaluates the specified postfix expression. If an operand is
* encountered, it is pushed onto the stack. If an operator is
* encountered, two operands are popped, the operation is
* evaluated, and the result is pushed onto the stack.
* //param expr String representation of a postfix expression
* //return int value of the given expression
*/
public int evaluate (String expr)
{
int op1, op2, result = 0;
String token;
StringTokenizer tokenizer = new StringTokenizer (expr);
while (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();
if (isOperator(token))
{
op2 = (stack.pop()).intValue();
op1 = (stack.pop()).intValue();
result = evalSingleOp (token.charAt(0), op1, op2);
stack.push (new Integer(result));
}
else
stack.push (new Integer(Integer.parseInt(token)));
}
return result;
}
/**
* Determines if the specified token is an operator.
* //param token String representing a single token
* //return boolean true if token is operator
*/
private boolean isOperator (String token)
{
return ( token.equals(\"+\") || token.equals(\"-\") ||
token.equals(\"*\") || token.equals(\"/\") );
}
/**
* Performs integer evaluation on a single expression consisting of
* the specified operator and operands.
* //param operation operation to be performed
* //param op1 the first operand
* //param op2 the second operand
* //return int value of the expression
*/
private int evalSingleOp (char operation, int op1, int op2)
{
int result = 0;
switch .
In this lab, we will write an application to store a deck of cards i.pdfcontact41
In this lab, we will write an application to store a deck of cards in a linked list, and then write
methods to sort and shuffle the deck.
Copy your completed LinkedList class from Lab 4 into the LinkedList.java file below.
Complete all methods of the Card class as described by the Javadoc comments. The class
contains both a suit and a rank. A suit is one of the categories into which the cards of a deck are
divided. The rank is the relative importance of the card within its suit.
Note that the Card constructor must convert any rank and suit letters to uppercase.
For the equals() method, be sure to follow the steps outlined in Lesson 4. How to implement the
compareTo() method is also covered in Lesson 4.
Note that you are not allowed to add any additional methods or member variables to this class or
you will not receive credit for this assignment.
Complete all methods of the CardApp class in the CardApp.java file as described by the Javadoc
comments.
You may add as many methods as you would like to this file, but are not allowed to add any
additional member variables.
The CardApp program must prompt for and allow the user to enter the name of any input file as
shown in the Example output below.
Implement the shuffle() method as specified in the comments for shuffle(). After you have
shuffled the deck of cards, write the result into a file named shuffled.txt.
Implement the sort() method using bubble sort from Lesson 4. First sort by suit in alphabetical
order and then by rank from 2 to A. The pseudocode for bubble sort is as follows:
After you have sorted the deck of cards, write the result to a file named sorted.txt.
The CardApp.java file also contains the main() method of the application. Use Develop mode to
test your CardApp code along with your Card and LinkedList code.
All input and output files must contain a list of cards, with each card stored on its own line. See
the example files cards1.txt and cards2.txt for example file formats.
[[[cards1.txt]]]
2H
3H
4H
5H
6H
7H
8H
9H
10H
JH
[[[cards2.txt]]]
AS
2S
3S
4S
5S
6S
7S
8S
9S
10S
JS
QS
KS
AC
2C
3C
4C
5C
6C
7C
8C
9C
10C
JC
QC
KC
AH
2H
3H
4H
5H
6H
7H
8H
9H
10H
JH
QH
KH
AD
2D
3D
4D
5D
6D
7D
8D
9D
10D
JD
QD
KD
[[[CardApp.java]]]
/**
* CardApp.java
* @author Your name
* @author Partner's name
* CIS 22C, Applied Lab 1
*/
public class CardApp {
private LinkedList list;
/**
* User interface prompts user, reads and writes files.
*/
public static void main(String[] args) {
}
/**
* Default constructor to initialize the deck
*/
public CardApp() {
}
/**
* Inserts a new Card into the deck
* @param card a playing Card
*/
public void addCard(Card card) {
}
/**
* Shuffles cards following this algorithm:
* First swaps first and last card
* Next, swaps every even card with the card 3
* nodes away from that card. Stops when it
* reaches the 3rd to last node
* Then, swaps ALL cards with the card that is
* 2 nodes away from it, starting at the 2nd card
* and stopping stopping at the 3rd to last node
*/
public vo.
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.
Similar to Modifications highlighted in bold lettersDropOutStack.javaim.pdf (20)
steps are as follows Dissolve the (pressumably.pdfLalkamal2
steps are as follows : Dissolve the (pressumably solid) mixture in an organic
solven,,,,,,, Then, in a seperating funnel, add an (Aqueous) solution of sodium hydroxide. The
Phenol, and benzoic acid, as acids, will react with the base to form phenolate and benzenoate
ions, which will dissolve into the water layer. Collect this layer, and re-precipitate the organic
molecules by adding concentrated Hydrochloric acid. The phenol and Benzoic acid can be
seperated via their varying solubilities, (8.3g/100ml vs 0.34g/100ml. respectively) by heating the
mixture in water to dissolve the phenol, and then filtering of the (practically) insoluble benzoic
acid. The solution can then be acidified (with HCl) to return the phenol..,,,,,,,,,,,,, Now add a
solution of hydrochloric acid to the seperating funnel, which (as before) will react with the basic
anniline dossilving it into the water. Collect the aqueous layer and re-precipitate the anniline
with excess sodium hydroxide. ,,,,,,,,,,,,,,, finally boil off the remaining organic solvent to obtain
the napthalene, which was left untouched by all the acids and bases.,,,,,,,,, Flow chart : Mixture
+ xs HCl ----> anilinium(aq) Mixture - aniline + weak base (Na2CO3) ---> benzoate(aq)
Mixture - aniline - benzoic acid + base (NaOH) ---> p-bromophenoxide(aq) Mixture - aniline -
benzoic acid - p-bromophenol = naphthalene
Solution
steps are as follows : Dissolve the (pressumably solid) mixture in an organic
solven,,,,,,, Then, in a seperating funnel, add an (Aqueous) solution of sodium hydroxide. The
Phenol, and benzoic acid, as acids, will react with the base to form phenolate and benzenoate
ions, which will dissolve into the water layer. Collect this layer, and re-precipitate the organic
molecules by adding concentrated Hydrochloric acid. The phenol and Benzoic acid can be
seperated via their varying solubilities, (8.3g/100ml vs 0.34g/100ml. respectively) by heating the
mixture in water to dissolve the phenol, and then filtering of the (practically) insoluble benzoic
acid. The solution can then be acidified (with HCl) to return the phenol..,,,,,,,,,,,,, Now add a
solution of hydrochloric acid to the seperating funnel, which (as before) will react with the basic
anniline dossilving it into the water. Collect the aqueous layer and re-precipitate the anniline
with excess sodium hydroxide. ,,,,,,,,,,,,,,, finally boil off the remaining organic solvent to obtain
the napthalene, which was left untouched by all the acids and bases.,,,,,,,,, Flow chart : Mixture
+ xs HCl ----> anilinium(aq) Mixture - aniline + weak base (Na2CO3) ---> benzoate(aq)
Mixture - aniline - benzoic acid + base (NaOH) ---> p-bromophenoxide(aq) Mixture - aniline -
benzoic acid - p-bromophenol = naphthalene.
the two features of the asynchronus connection that allow the receiv.pdfLalkamal2
the two features of the asynchronus connection that allow the receiver to stay in sync with the
incoming data stream are the start bit and short frame connections . asynchronus connection are
asynchronus serial communications in which the communicating end points interfaces are not
continously synchronized by common clock signal and the data stream contains synchronization
in the form of start and stop signals before and after each unit of transmission .asynchronus start
and stop signals was widley used for dial up modem sources to time sharing computers and bbs
systems asynchronus start stop is the physical layer is used to connect computers to modems for
many dial up internet access applications using data link frame protocol such as ppp to create
packets made upto out of asynchronous serial characters .the examples that would benefit from
asynchronous connection are modems and usb that are connectedd to interfaces
Solution
the two features of the asynchronus connection that allow the receiver to stay in sync with the
incoming data stream are the start bit and short frame connections . asynchronus connection are
asynchronus serial communications in which the communicating end points interfaces are not
continously synchronized by common clock signal and the data stream contains synchronization
in the form of start and stop signals before and after each unit of transmission .asynchronus start
and stop signals was widley used for dial up modem sources to time sharing computers and bbs
systems asynchronus start stop is the physical layer is used to connect computers to modems for
many dial up internet access applications using data link frame protocol such as ppp to create
packets made upto out of asynchronous serial characters .the examples that would benefit from
asynchronous connection are modems and usb that are connectedd to interfaces.
Telomerase is the enzyme responsible for maintenance of the length o.pdfLalkamal2
Telomerase is the enzyme responsible for maintenance of the length of telomeres by addition of
guanine-rich repetitive sequences, (Zvereva, 2010). Thus Telomerase, is a Specialized
Polymerase That Carries Its Own RNA Template. Thus it accounts for a faithful replication of
chromosomal ends as theTelomerase contains an RNA molecule that acts as a template for
extending the leading strand.
Solution
Telomerase is the enzyme responsible for maintenance of the length of telomeres by addition of
guanine-rich repetitive sequences, (Zvereva, 2010). Thus Telomerase, is a Specialized
Polymerase That Carries Its Own RNA Template. Thus it accounts for a faithful replication of
chromosomal ends as theTelomerase contains an RNA molecule that acts as a template for
extending the leading strand..
Suppose Bob sends an encrypted document to Alice. To be verifiable, .pdfLalkamal2
Suppose Bob sends an encrypted document to Alice. To be verifiable, Alice must be able to
convince herself that Bob sent the encrypted document. To be non-forgeable, Alice must be able
to convince herself that only Bob could have sent the encrypted document Alice must be able to
convince someone else that only Bob could have sent the document. To illustrate the latter
distinction, suppose Bob and Alice share a secret key, and they are the only ones in the world
who know the key. If Alice receives a document that was encrypted with the key, and knows that
she did not encrypt the document herself, then the document is known to be verifiable and non-
forgeable (assuming a suitably strong encryption system was used). However, Alice can not
convince someone else that Bob must have sent the document, since in fact Alice knew the key
herself and could have encrypted/sent the document.
Solution
Suppose Bob sends an encrypted document to Alice. To be verifiable, Alice must be able to
convince herself that Bob sent the encrypted document. To be non-forgeable, Alice must be able
to convince herself that only Bob could have sent the encrypted document Alice must be able to
convince someone else that only Bob could have sent the document. To illustrate the latter
distinction, suppose Bob and Alice share a secret key, and they are the only ones in the world
who know the key. If Alice receives a document that was encrypted with the key, and knows that
she did not encrypt the document herself, then the document is known to be verifiable and non-
forgeable (assuming a suitably strong encryption system was used). However, Alice can not
convince someone else that Bob must have sent the document, since in fact Alice knew the key
herself and could have encrypted/sent the document..
Platinum complexes like Asplastin are powerful antitumor medications.pdfLalkamal2
Platinum complexes like Asplastin are powerful antitumor medications and they are having
ability to cross the cell membrane and then reaches the nucleus and will attach to DNA and stop
cell growth. The transfer of this Asplastin is facilitated by a copper transporter (Ctr1-membrane-
dwelling protein which main function is to bring copper into cells). The |Ctr1 structure has of
three helical segments which appears to sit in the membrane, and one end can be seen protruding
into the cell, while the other end will be seen on the outside and a channel like structure will be
formed when three such molecules assemble together.
When Asplastin is injected in the body of a cancer patient, the Asplastin which have a central
platinum ion and four ligands (which includes two neighboring chloride ions and two
neighboring amino groups). The Ctr1 will displaces these four ligands from Asplastin and will
bind to the platinum ion itself and it will transfer it through the channel and released in the
cytosol of the cell. In addition to this few amount of Asplastin molecules will interact with the
methionine-rich extracellular end of the copper transporter to form a trimeric channel structure to
get transported as a little interior bubble filled with the outer medium and will released into
various organelles including nucleus.
How it acts on cancer cells: The 4 steps how Asplastin will act is (i) Cellular uptake of drug, (ii)
aquation/activation of Asplastin, (iii) Drug binding to DNA and (iv) Lesions formed on DNA
will make the cell to opt for apoptosis.
N7 sites of deoxyguanosine residues on the DNA are the most nucleophilic positions and are
preferentially platinated. Asplastin will form a monofunctional adducts on DNA (You can see
only one covalent bond to the genomic polymer). Like in second reaction second guanine base
will get substituted by chloride ligand, thus forming a cross-link on the DNA (either on the same
strand or it may be on different strands). The most common lesion are formed from 1,2-d(GpG)
intrastrand cross-links and finally due to drug action we can see bending and unwinding of the
double helix and cells with damaged DNA will be arrested at the G2/M transition of the cell
cycle and undergoes apoptosis.
Solution
Platinum complexes like Asplastin are powerful antitumor medications and they are having
ability to cross the cell membrane and then reaches the nucleus and will attach to DNA and stop
cell growth. The transfer of this Asplastin is facilitated by a copper transporter (Ctr1-membrane-
dwelling protein which main function is to bring copper into cells). The |Ctr1 structure has of
three helical segments which appears to sit in the membrane, and one end can be seen protruding
into the cell, while the other end will be seen on the outside and a channel like structure will be
formed when three such molecules assemble together.
When Asplastin is injected in the body of a cancer patient, the Asplastin which have a central
platinum ion and f.
Part 1 1)#include stdio.hint testWhileLoop() ; int testFo.pdfLalkamal2
Part 1:
1)
#include
int testWhileLoop() ;
int testForLoop() ;
int main()
{
printf(\"While loop test \ \");
testWhileLoop();
printf(\"For loop test \ \");
testForLoop();
return 0;
}
Part 2:
1)
#include
int testWhileLoop() ;
int main()
{
printf(\"While loop test \ \");
testWhileLoop();
return 0;
}
int testWhileLoop()
{
int count=0;
int n;
while (count<10)
{
printf(\"Enter an integer: \");
scanf(\"%d\",&n);
printf(\"You Entered: %d\ \",n);
count++;
}
}
2)
#include
int testWhileLoop() ;
int main()
{
printf(\"While loop test \ \");
testWhileLoop();
return 0;
}
int testWhileLoop()
{
int count=0;
int n;
int sum=0;
while (count<10)
{
printf(\"Enter an integer: \");
scanf(\"%d\",&n);
printf(\"You Entered: %d\ \",n);
count++;
sum=sum+n;
}
printf(\"Total sum of integers is: %d\ \",sum);
}
3)
#include
int testWhileLoop() ;
int main()
{
printf(\"While loop test \ \");
testWhileLoop();
return 0;
}
int testWhileLoop()
{
int count=0;
int n;
int sum=0;
while (count<10)
{
printf(\"Enter an integer between 5 and 20: \");
scanf(\"%d\",&n);
while(n<5 || n>20)
{
printf(\"Error: You must enter a value between 5 and 20: please renter: \");
scanf(\"%d\",&n);
}
printf(\"You Entered: %d\ \",n);
count++;
sum=sum+n;
}
printf(\"Total sum of integers is: %d\ \",sum);
}
Part 3:
#include
int testForLoop() ;
int main()
{
printf(\"For loop test \ \");
testForLoop();
return 0;
}
int testForLoop()
{
int count=0;
int n;
int sum=0;
for (count=0;count<10;count++)
{
printf(\"Enter an integer: \");
scanf(\"%d\",&n);
printf(\"You Entered: %d\ \",n);
sum=sum+n;
}
printf(\"Total sum of integers is: %d\ \",sum);
}
Solution
Part 1:
1)
#include
int testWhileLoop() ;
int testForLoop() ;
int main()
{
printf(\"While loop test \ \");
testWhileLoop();
printf(\"For loop test \ \");
testForLoop();
return 0;
}
Part 2:
1)
#include
int testWhileLoop() ;
int main()
{
printf(\"While loop test \ \");
testWhileLoop();
return 0;
}
int testWhileLoop()
{
int count=0;
int n;
while (count<10)
{
printf(\"Enter an integer: \");
scanf(\"%d\",&n);
printf(\"You Entered: %d\ \",n);
count++;
}
}
2)
#include
int testWhileLoop() ;
int main()
{
printf(\"While loop test \ \");
testWhileLoop();
return 0;
}
int testWhileLoop()
{
int count=0;
int n;
int sum=0;
while (count<10)
{
printf(\"Enter an integer: \");
scanf(\"%d\",&n);
printf(\"You Entered: %d\ \",n);
count++;
sum=sum+n;
}
printf(\"Total sum of integers is: %d\ \",sum);
}
3)
#include
int testWhileLoop() ;
int main()
{
printf(\"While loop test \ \");
testWhileLoop();
return 0;
}
int testWhileLoop()
{
int count=0;
int n;
int sum=0;
while (count<10)
{
printf(\"Enter an integer between 5 and 20: \");
scanf(\"%d\",&n);
while(n<5 || n>20)
{
printf(\"Error: You must enter a value between 5 and 20: please renter: \");
scanf(\"%d\",&n);
}
printf(\"You Entered: %d\ \",n);
count++;
sum=sum+n;
}
printf(\"Total sum of integers is: %d\ \",sum);
}
Part 3:
#include
int testForLoop() ;
int main()
{
printf(\"For loop test \ \");
testForLoop();
return 0;
}
int testForLoop()
{
int c.
Negative control plate with no DNA transforms competent cells withou.pdfLalkamal2
Negative control plate with no DNA transforms competent cells without any DNA on selection
media. , If more colonies are produced, shows the problem with antibiotic in the agar plate.
No ligase control plates provide information about digestion efficiency. it transform competent
cells withdigested plasmid or DNA. If several colonies are found, it shows that digestion did not
completed properly.
Solution
Negative control plate with no DNA transforms competent cells without any DNA on selection
media. , If more colonies are produced, shows the problem with antibiotic in the agar plate.
No ligase control plates provide information about digestion efficiency. it transform competent
cells withdigested plasmid or DNA. If several colonies are found, it shows that digestion did not
completed properly..
Message types used by the DHCP boot sequenceop Message type.h.pdfLalkamal2
Message types used by the DHCP boot sequence
op
: Message type.
htype
: Hardware address type defined at Internet Assigned Numbers Authority (IANA).
hlen
: Hardware address length, in octets.
hops
: Value set to zero by DHCP clients. Optionally used to count the number of relay agents that
forwarded the message.
xid
: A random number used to associate messages and responses between a client and a server.
secs
: Seconds elapsed since client began address acquisition or renewal process.
flags
: Flags set by client. The Broadcast flag is set if the client cannot receive unicast IP datagrams
(for example, before it is configured with an IP address).
ciaddr
: Used if the client has an IP address and can respond to Address Resolution Protocol (ARP)
requests.
yiaddr
: Address given to the DHCP client by the DHCP server.
siaddr
: IP address of the server that is offering a lease.
giaddr
: DHCP relay agent IP address.
chaddr
: Client hardware address.
sname
: Optional server host name. Not used in Windows Server 2008.
file
: The name of the file containing the boot image for a BOOTP client.
options
: Optional parameters field. In the DHCP protocol packet, each option begins with a single octet
tag, which holds the option code, and a second octet, which describes the option data length, in
bytes. For a complete list of the DHCP options available by default on a DHCP server running
on Windows Server 2008, see DHCP Tools and Options.
op
: Message type.
htype
: Hardware address type defined at Internet Assigned Numbers Authority (IANA).
hlen
: Hardware address length, in octets.
hops
: Value set to zero by DHCP clients. Optionally used to count the number of relay agents that
forwarded the message.
xid
: A random number used to associate messages and responses between a client and a server.
secs
: Seconds elapsed since client began address acquisition or renewal process.
flags
: Flags set by client. The Broadcast flag is set if the client cannot receive unicast IP datagrams
(for example, before it is configured with an IP address).
ciaddr
: Used if the client has an IP address and can respond to Address Resolution Protocol (ARP)
requests.
yiaddr
: Address given to the DHCP client by the DHCP server.
siaddr
: IP address of the server that is offering a lease.
giaddr
: DHCP relay agent IP address.
chaddr
: Client hardware address.
sname
: Optional server host name. Not used in Windows Server 2008.
file
: The name of the file containing the boot image for a BOOTP client.
options
: Optional parameters field. In the DHCP protocol packet, each option begins with a single octet
tag, which holds the option code, and a second octet, which describes the option data length, in
bytes. For a complete list of the DHCP options available by default on a DHCP server running
on Windows Server 2008, see DHCP Tools and Options.
Solution
Message types used by the DHCP boot sequence
op
: Message type.
htype
: Hardware address type defined at Internet Assigned Numbers Authority.
Law of conservation of matter(mass)In any closed system subjected .pdfLalkamal2
Law of conservation of matter(mass)
In any closed system subjected to no external forces,the mass is constant irrespective of its
changes in different form. Matter cannot be created or destroyed in an isolated system. It only
changes from one form into another.
Solution
Law of conservation of matter(mass)
In any closed system subjected to no external forces,the mass is constant irrespective of its
changes in different form. Matter cannot be created or destroyed in an isolated system. It only
changes from one form into another..
It is a unit of measurement for the amount of substance.The mole is .pdfLalkamal2
It is a unit of measurement for the amount of substance.The mole is defined as the amount of
substance that contains as many elementary entities (e.g., atoms, molecules, ions, electrons) as
there are atoms in 12 g of the isotope carbon-12. The experimentally determined value of a mole
as adopted 6.02 × 1023.
Solution
It is a unit of measurement for the amount of substance.The mole is defined as the amount of
substance that contains as many elementary entities (e.g., atoms, molecules, ions, electrons) as
there are atoms in 12 g of the isotope carbon-12. The experimentally determined value of a mole
as adopted 6.02 × 1023..
In insurance, the term risk pooling refers to the spreading of f.pdfLalkamal2
In insurance, the term \"risk pooling\" refers to the spreading of financial risks evenly among a
large number of contributors to the program. Insurance is the transference of risks from
individuals or corporations who cannot bear a possible unplanned financial catastrophe to the
capital markets, which can bear them easily -- at least in theory.
Pure risk is a category of risk in which loss is the only possible outcome, which is the opposite of
speculative risk. There are products that can be purchased to mitigate pure risk, such as home
insurance being used to protect homeowners against their homes being destroyed. Other
examples of pure risk events include premature death, identity theft and career-ending
disabilities.1) in cases of home insurance and health insurance risk pooling can be effectively
used as of all the individuals who invest in the insurance by the law of large number a miniscule
probability of the people actually suffer the real risk. 2) Risk pooling is an important concept in
supply chain management . It suggests that demand variability is reduced if one aggregates
demand across locations because, as demand is aggregated across different locations, it becomes
more likely that high demand from one customer will be offset by low demand from another.
However,consider the 1)\"high risk pools\", which simply means separating out the sickest, most
expensive people in the country and dumping them into a separate program.With the \"bad
apples\" (ie, human beings with terrible medical problems) safely tucked out of the way, the
average cost of treating everyone else supposedly suddenly becomes less pricey.This is the exact
opposite of the entire point of health insurance in the first place...spreading the risk and hence
risk pooling fails here.
2)Liability risk includes economic losses from being held responsible for harming others or their
property. This cannot be covered by risk pooling.
Solution
In insurance, the term \"risk pooling\" refers to the spreading of financial risks evenly among a
large number of contributors to the program. Insurance is the transference of risks from
individuals or corporations who cannot bear a possible unplanned financial catastrophe to the
capital markets, which can bear them easily -- at least in theory.
Pure risk is a category of risk in which loss is the only possible outcome, which is the opposite of
speculative risk. There are products that can be purchased to mitigate pure risk, such as home
insurance being used to protect homeowners against their homes being destroyed. Other
examples of pure risk events include premature death, identity theft and career-ending
disabilities.1) in cases of home insurance and health insurance risk pooling can be effectively
used as of all the individuals who invest in the insurance by the law of large number a miniscule
probability of the people actually suffer the real risk. 2) Risk pooling is an important concept in
supply chain management . It suggests that.
Some CO is Added The Pressure of CH4 and H2O will.pdfLalkamal2
Some CO is Added The Pressure of CH4 and H2O will Increase Equilibrium will
shift to the Left Some CH4 is Removed Pressure of H2O will Increase Pressure of CO will
Decrease Equilibrium will shift to the Left The Volume of Vessel is Reduced Pressure of CH4
will Increase Pressure of H2O will Increase Equilibrium will shift to the Left
Solution
Some CO is Added The Pressure of CH4 and H2O will Increase Equilibrium will
shift to the Left Some CH4 is Removed Pressure of H2O will Increase Pressure of CO will
Decrease Equilibrium will shift to the Left The Volume of Vessel is Reduced Pressure of CH4
will Increase Pressure of H2O will Increase Equilibrium will shift to the Left.
Comments Figures are not properly numbered. Further signal of figur.pdfLalkamal2
Comments: Figures are not properly numbered. Further signal of figure 1 is not shown and hence
the above figure (assumed to figure 2) can not be simulated.
Solution
Comments: Figures are not properly numbered. Further signal of figure 1 is not shown and hence
the above figure (assumed to figure 2) can not be simulated..
Change the value of jug1 and jug 2 accordingly. 1 File WaterJugBSF.j.pdfLalkamal2
Change the value of jug1 and jug 2 accordingly. 1 File WaterJugBSF.java
import java.util.*;
import java.util.LinkedList;
class Test {
HashSet uniqueStates;
void letsRoll() {
/*
* The capacity of jug1(jug1 capacity is greater than jug2 capacity)
*/
int jug1 = 3;
/*
* The capacity of jug two
*/
int jug2 = 2;
/*
* Final Amount needed in jug1
*/
int amtNeeded = 2;
State initialState = new State(0, 0);
State finalState = new State(amtNeeded, 0);
State finalPath = null;
uniqueStates = new HashSet();
/*
* Change queue to stack to convert to DFS
*/
LinkedList queue = new LinkedList();
queue.add(initialState);
while (!queue.isEmpty()) {
State currState = queue.poll();
if (currState.equals(finalState)) {
finalPath = currState;
break;
}
// if x is zero fill it
if (currState.x == 0) {
State nextState = new State(jug1, currState.y, currState);
//System.out.println(currState);
checkUniqueStates(uniqueStates, nextState, queue);
}
// if y is empty fill it
if (currState.y == 0) {
State nextState = new State(currState.x, jug2, currState);
checkUniqueStates(uniqueStates, nextState, queue);
}
// if x is not empty , empty it
if (currState.x > 0) {
State nextState = new State(0, currState.y, currState);
checkUniqueStates(uniqueStates, nextState, queue);
}
// if y is not empty, empty it
if (currState.y > 0) {
State nextState = new State(currState.x, 0, currState);
checkUniqueStates(uniqueStates, nextState, queue);
}
// transfer from x to y, when x non empty and y is not full
if (currState.x > 0 && currState.y < jug2) {
int amtToTransfer = Math.min(currState.x, jug2 - currState.y);
State nextState = new State(currState.x - amtToTransfer, currState.y
+ amtToTransfer,
currState);
checkUniqueStates(uniqueStates, nextState, queue);
}
// transfer from y to x, when y is not empty and x is not full
if (currState.y > 0 && currState.x < jug1) {
int amtToTransfer = Math.min(currState.y, jug1 - currState.x);
State nextState = new State(currState.x + amtToTransfer, currState.y
- amtToTransfer,
currState);
checkUniqueStates(uniqueStates, nextState, queue);
}
}
if (finalPath != null) {
System.out.println(\"Final Result\");
System.out.println(\"J1 J2\");
System.out.println(finalPath);
}
else{
System.out.println(\"Not Possible\");
}
}
/*
* Checks whether State toCheck has been generated before, if not it is
* added to queue and uniqueStates Set
*/
void checkUniqueStates(HashSet uniqueStates, State toCheck,
LinkedList queue) {
if (!uniqueStates.contains(toCheck)) {
uniqueStates.add(toCheck);
queue.add(toCheck);
}
}
public static void main(String[] args) {
new Test().letsRoll();
}
}
2 State.java
class State {
/*
* Amount in jug1 for current State
*/
int x;
/*
* Amount in jug2 for current State
*/
int y;
/*
* Parent of current State
*/
State pre;
public State(int x, int y) {
super();
this.x = x;
this.y = y;
}
public State(int x, int y, State pre) {
super();
this.x = x;
this.y = y;
this.pre = pre;
System.out.println(\"(\"+x+\",\"+y+\")\");
}
@Override
public int hashCode() {
final int .
Balance sheetBalance sheet is the statement of financial position .pdfLalkamal2
Balance sheet
Balance sheet is the statement of financial position which reports all the assets, liabilities and
equity held by the company at a specific date. It helps in telling about the investments, resources,
claims and owner’s equity of the company. It revolves around the equation i.e. Assets =
Liabilities + equity.
What is shown in balance sheet:
The balance sheet has three major categories which includes Assets, liabilities and equity. All
these are calssified on the basis of their nature.
Assets can be said as the resources of the company and are classified as: Current assets, long
term investment, property, plant and equipment, intangible assets and other assets
Assets includes:
•Current assets – Cash, accounts receivables, prepaid expenses, inventories
•Long term investments – investment in stock
•Plant property and equipment – Land, building, equipment
•Intangible assets – Goodwill, patents, trademarks
Liabilities are the claims and can be classified as current liabilities, long term liabilities
Liabilities includes:
•Current liabilities: Accounts payable, income tax payable. Salaries payable, accrued expenses,
unearned revenue, current portion of long term debt due
•Long term liabilities- bonds payable, notes payable
Owner;s equity can be classified as the Capital stock which includes common stock and
preferred stock
It also includes Additional paid in capital, Retained earnings
Retained earnings are the accumulated earnings of the company. It is calculated as Beginning
balance, Add: Net income less: Dividends
Importance:
Balance sheet is important in every business. Considering the hospitality firm, it is important to
analyze different aspects of teh firm to know its financial postion. As the hospitality firm
emphasize on services, it is important to know the financial position of the company through its
financial statements. the hospitality firms like hotel needs to report their assets (building) held by
the company along with other assets, liabilities and equity.
Balance sheet is the statement which helps in analysing the financial position of the company, it
can also help in predicting the cash flows and the financial position of the company. With the
help of the balance sheet we can help in analysing the ability of the firm to pay off its short term
and long term debts.
Balance sheet reports its assets and liabilities on historical basis and uses different estimates to
analyse the amounts like uncollectibles
Solution
Balance sheet
Balance sheet is the statement of financial position which reports all the assets, liabilities and
equity held by the company at a specific date. It helps in telling about the investments, resources,
claims and owner’s equity of the company. It revolves around the equation i.e. Assets =
Liabilities + equity.
What is shown in balance sheet:
The balance sheet has three major categories which includes Assets, liabilities and equity. All
these are calssified on the basis of their nature.
Assets can be .
Answer BaSO4K+ is always soluble because it is an alkaline metal..pdfLalkamal2
Answer: BaSO4
K+ is always soluble because it is an alkaline metal. NO3- is also always soluble.
SO4 is usually soluble except when it is paired with Sr, Ba, Ca, or Pb.
Solution
Answer: BaSO4
K+ is always soluble because it is an alkaline metal. NO3- is also always soluble.
SO4 is usually soluble except when it is paired with Sr, Ba, Ca, or Pb..
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
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.
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Modifications highlighted in bold lettersDropOutStack.javaim.pdf
1. //Modifications highlighted in bold letters
//DropOutStack.java
import java.util.Arrays;
public class DropOutStack {
/**
* Defines the interface to a stack collection.
*
* @author Java Foundations
* @version 4.0
*/
public interface StackADT {
/**
* 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
*/
public T pop();
/**
* Returns without removing the top element of this stack.
*
* @return the element on top of the stack
*/
public T peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if the stack is empty
*/
2. public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size();
/**
* Returns a string representation of this stack.
*
* @return a string representation of the stack
*/
public String toString();
}
/**
* Represents the situation in which a collection is empty.
*
* @author Java Foundations
* @version 4.0
*/
public static class EmptyCollectionException extends RuntimeException {
/**
* Sets up this exception with an appropriate message.
*
* @param collection
* the name of the collection
*/
public EmptyCollectionException(String collection) {
super("The " + collection + " is empty.");
}
}
/**
* Program entry point for stack testing.
*
* @param args
* Argument list.
3. */
public static void main(String[] args) {
ArrayDropOutStack stack = new ArrayDropOutStack(4);
System.out.println("DROP-OUT STACK TESTING");
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println("Stack : "+stack.toString());
System.out.println("pushing 5 element ");
stack.push(5);
System.out.println("Now stack elements");
System.out.println(stack.toString());
System.out.println("The size of the stack is: " + stack.size());
if (!stack.isEmpty())
System.out.println("The stack contains: " + stack.toString());
stack.pop();
System.out.println("poping element 5"+stack.toString());
System.out.println("The size of the stack is: " + stack.size());
System.out.println("pushing 7 element ");
stack.push(7);
System.out.println("Now stack elements");
System.out.println(stack.toString());
System.out.println("pushing 8 element ");
stack.push(8);
System.out.println("Now stack elements");
System.out.println(stack.toString());
if (!stack.isEmpty())
System.out.println("The stack contains: " + stack.toString());
4. }
/**
* An array implementation of a stack in which the bottom of the stack is
* fixed at index 0.
*
* @author Java Foundations
* @version 4.0
*/
public static class ArrayDropOutStack implements StackADT {
private final static int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
/**
* Creates an empty stack using the default capacity.
*/
public ArrayDropOutStack() {
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty stack using the specified capacity.
*
* @param initialCapacity
* the initial size of the array
*/
@SuppressWarnings("unchecked") // see p505.
public ArrayDropOutStack(int initialCapacity) {
top = 0;
stack = (T[]) (new Object[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
*/
5. public void push(T element)
{
if(top 0) {
return false;
} else {
return true;
}
}
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size() {
int total = 0;
for (int i = 0; i < top; i++) {
if (top > 0) {
total++;
}
}
return total;
}
/**
* Returns a string representation of this stack. The string has the
* form of each element printed on its own line, with the top most
* element displayed first, and the bottom most element displayed last.
* If the list is empty, returns the word "empty".
*
* @return a string representation of the stack
*/
public String toString() {
String results = "";
for (int i = size() - 1; i >= 0; i--) {
if (top >= i) {
results += " " + stack[i];
} else {
6. results = "0";
}
}
return results;
}
}
}
------------------------------------------------------------------------------------------------------------
Sample output:
DROP-OUT STACK TESTING
Stack :
4
3
2
1
pushing 5 element
Now stack elements
5
4
3
2
The size of the stack is: 4
The stack contains:
5
4
3
2
poping element 5
4
3
2
The size of the stack is: 3
pushing 7 element
Now stack elements
7
4
7. 3
2
pushing 8 element
Now stack elements
8
7
4
3
The stack contains:
8
7
4
3
Solution
//Modifications highlighted in bold letters
//DropOutStack.java
import java.util.Arrays;
public class DropOutStack {
/**
* Defines the interface to a stack collection.
*
* @author Java Foundations
* @version 4.0
*/
public interface StackADT {
/**
* 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.
8. *
* @return the element removed from the stack
*/
public T pop();
/**
* Returns without removing the top element of this stack.
*
* @return the element on top of the stack
*/
public T peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if the stack is empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size();
/**
* Returns a string representation of this stack.
*
* @return a string representation of the stack
*/
public String toString();
}
/**
* Represents the situation in which a collection is empty.
*
* @author Java Foundations
* @version 4.0
*/
public static class EmptyCollectionException extends RuntimeException {
9. /**
* Sets up this exception with an appropriate message.
*
* @param collection
* the name of the collection
*/
public EmptyCollectionException(String collection) {
super("The " + collection + " is empty.");
}
}
/**
* Program entry point for stack testing.
*
* @param args
* Argument list.
*/
public static void main(String[] args) {
ArrayDropOutStack stack = new ArrayDropOutStack(4);
System.out.println("DROP-OUT STACK TESTING");
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println("Stack : "+stack.toString());
System.out.println("pushing 5 element ");
stack.push(5);
System.out.println("Now stack elements");
System.out.println(stack.toString());
System.out.println("The size of the stack is: " + stack.size());
if (!stack.isEmpty())
System.out.println("The stack contains: " + stack.toString());
stack.pop();
System.out.println("poping element 5"+stack.toString());
10. System.out.println("The size of the stack is: " + stack.size());
System.out.println("pushing 7 element ");
stack.push(7);
System.out.println("Now stack elements");
System.out.println(stack.toString());
System.out.println("pushing 8 element ");
stack.push(8);
System.out.println("Now stack elements");
System.out.println(stack.toString());
if (!stack.isEmpty())
System.out.println("The stack contains: " + stack.toString());
}
/**
* An array implementation of a stack in which the bottom of the stack is
* fixed at index 0.
*
* @author Java Foundations
* @version 4.0
*/
public static class ArrayDropOutStack implements StackADT {
private final static int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
/**
* Creates an empty stack using the default capacity.
*/
public ArrayDropOutStack() {
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty stack using the specified capacity.
*
11. * @param initialCapacity
* the initial size of the array
*/
@SuppressWarnings("unchecked") // see p505.
public ArrayDropOutStack(int initialCapacity) {
top = 0;
stack = (T[]) (new Object[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
*/
public void push(T element)
{
if(top 0) {
return false;
} else {
return true;
}
}
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size() {
int total = 0;
for (int i = 0; i < top; i++) {
if (top > 0) {
total++;
}
}
return total;
12. }
/**
* Returns a string representation of this stack. The string has the
* form of each element printed on its own line, with the top most
* element displayed first, and the bottom most element displayed last.
* If the list is empty, returns the word "empty".
*
* @return a string representation of the stack
*/
public String toString() {
String results = "";
for (int i = size() - 1; i >= 0; i--) {
if (top >= i) {
results += " " + stack[i];
} else {
results = "0";
}
}
return results;
}
}
}
------------------------------------------------------------------------------------------------------------
Sample output:
DROP-OUT STACK TESTING
Stack :
4
3
2
1
pushing 5 element
Now stack elements
5
4
3
2
13. The size of the stack is: 4
The stack contains:
5
4
3
2
poping element 5
4
3
2
The size of the stack is: 3
pushing 7 element
Now stack elements
7
4
3
2
pushing 8 element
Now stack elements
8
7
4
3
The stack contains:
8
7
4
3