all i need is these two filesCreate VectorContainer.hppCreat.docxjack60216
all i need is these two files
Create VectorContainer.hpp
Create SelectionSort.hpp
Test SelectionSort.hpp using the VectorContainer.hpp class you made
# Strategy Pattern
In this lab you will create a strategy pattern for sorting a collection of expression trees by their `evaluate()` value, which you will pair with different containers to see how strategies can be paired with different clients through an interface to create an easily extendable system. This lab requires a completed composite pattern from the previous lab, so you should begin by copying your or your partner's code from the previous assignment into your new repo, making sure it compiles correctly, and running your tests to make sure everything is still functioning correctly.
You will start this lab by creating two expression tree containers: one that uses a vector to hold your trees (class `VectorContainer`) and one that uses a standard list (class `ListContainer`). Each of these container classes should be able to hold any amount of different expressions each of which can be of any size. You will implement them both as subclasses of the following `Container` abstract base class, which has been provided to you in container.h. You should create each one independently, creating tests for them using the google test framework before moving on. Each container should be it’s own commit with a proper commit message. Optionally you can create each one as a branch and merge it in once it has been completed.
class Container {
protected:
Sort* sort_function;
public:
/* Constructors */
Container() : sort_function(nullptr) { };
Container(Sort* function) : sort_function(function) { };
/* Non Virtual Functions */
void set_sort_function(Sort* sort_function); // set the type of sorting algorithm
/* Pure Virtual Functions */
// push the top pointer of the tree into container
virtual void add_element(Base* element) = 0;
// iterate through trees and output the expressions (use stringify())
virtual void print() = 0;
// calls on the previously set sorting-algorithm. Checks if sort_function is not
// null, throw exception if otherwise
virtual void sort() = 0;
/* Functions Needed to Sort */
//switch tree locations
virtual void swap(int i, int j) = 0;
// get top ptr of tree at index i
virtual Base* at(int i) = 0;
// return container size
virtual int size() = 0;
};
Notice that our Container abstract base class does not have any actual STL containers because it leaves the implementation details of the container to the subclasses. You **must use the homogeneous interface above for your sort functions, and you are only allowed to manipulate the containers through this interface, not directly**. This will allow you to extend and change the underlying functionality without having to change anything t.
For problems 3 and 4, consider the following functions that implemen.pdfanjandavid
For problems 3 and 4, consider the following functions that implement the dequeue operation for
a priority queue that is implemented with a heap.
int[] pQueue;
int length;
int dequeue()
{
int node = 1;
int value = pQueue[--length];
int maxValue = pQueue[node];
int location = sift(node * 2, value);
pQueue[location] = value;
return maxValue;
}
int sift(int node, int value)
{
if (node <= length)
{
if (node < length && pQueue[node] < pQueue[node + 1]) node++;
if (value < pQueue[node])
{
pQueue[node / 2] = pQueue[node];
return sift(node * 2, value);
}
}
return node / 2;
}
3. Write the recurrence equation and initial conditions that expresses the execution time cost for
the sift function in the above algorithm. Draw the recursion tree assuming that n = 8. Assume
that n represents the number of nodes in the subtree at each step of the sifting operation.
4. Determine the critical exponent for the recurrence equation in problem 3. Apply the Little
Master Theorem to solve that equation specifically stating which part of the theorem is applied to
arrive at the solution.
Solution
using System.Collections;
using System.Collections.Generic;
namespace PriorityQueueDemo
{
///
/// Priority queue based on binary heap in program,
/// Elements with minimum priority dequeued first in program
///
/// Type of priorities
/// Type of values
public class PriorityQueues : ICollection>
{
private List> _baseHeap;
private IComparer _comparers;
#region Constructor
///
/// Initializes a new instance of priority queue with default initial capacity and default
priority comparer in program
///
public PriorityQueues()
: this(Comparers.Default)
{
}
///
/// Initializes a new instance of priority queue with specified initial capacity and default
priority comparer in program
///
/// initial capacity
public PriorityQueues(int capacity)
: this(capacity, Comparers.Default)
{
}
///
/// Initializes a new instance of priority queue with specified initial capacity and specified
priority comparer in program
///
/// initial capacity
/// priority comparer
public PriorityQueues(int capacity, IComparers comparer)
{
if (comparer == null)
throw new ArgumentNullException();
_baseHeaps = new List>(capacity);
_comparers= comparer;
}
///
/// Initializes a new instance of priority queue with default initial capacity and specified
priority comparer in program
///
/// priority comparer
public PriorityQueues(IComparer comparers)
{
if (comparers == null)
throw new ArgumentNullException();
_baseHeap = new List>();
_comparer = comparers;
}
///
/// Initializes a new instance of priority queue with specified data and default priority
comparer in program
///
/// data to be inserted into priority queue in program
public PriorityQueues(IEnumerable> data)
: this(data, Comparers.Default)
{
}
///
/// Initializes a new instance of priority queue with specified data and specified priority
comparer in program
///
/// data to be inserted into priority queue
/// priority comparer in program
public PriorityQueue(IEnumer.
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxbradburgess22840
In Class Assignmetz/CST280W13a-1.pdf
CST 280 In-Class Practice – Week 13
Manually determine the configuration of the priority queue (stored as a heap) created
by the following operations. Trace the following logic and define the output:
enqueue(7);
enqueue(17);
enqueue(2);
enqueue(5);
enqueue(22);
enqueue(19);
enqueue(6);
enqueue(11);
enqueue(13);
write the queue contents
dequeue and write front item
enqueue(15);
enqueue(8);
dequeue and write front item
dequeue and write front item
enqueue(24);
enqueue(14);
write the queue contents
Part 2
Then, verify the output by implementing the algorithm by rewriting the priority
queue demonstration program discussed in class. Files needed:
testPQueue.cpp pqType.h heap.cpp
Deliverables
• This cover sheet (with your names on it)
• Driver source code and output for verification program exectution.
In Class Assignmetz/CST280W13b.pdf
CST 280 In-Class Practice – Week 13
Use this page as a worksheet to sketch the progression of the elements up to the first
split for the QuickSort algorithm. Use the middle array element as the split value:
15 34 99 42 11 41 66 23 55 93 48
Next, access the file quickSort.cpp from the course web page. Tailor the program
by entering the array values above in place of the integer values used for an in-class
demonstration. Be sure to adjust the index range to match the size of this array.
Remember that the parameters to the QuickSort algorithm are starting and ending index
values, not the size of the array.
Next, insert code to demonstrate the state of the array after the first split. This should
verify what you did by hand above. Insert the following code at various points within
the partition function to “see” the array at various stages of processing:
for (int i = start; i <= end; i++) // <== ADD
cout << set[i] << ' ';
cout << endl;
Insert the code at these positions:
int partition(int set[], int start, int end)
{
int pivotValue, pivotIndex, mid;
mid = (start + end) / 2;
swap(set[start], set[mid]);
pivotIndex = start;
pivotValue = set[start];
ç HERE
for (int scan = start + 1; scan <= end; scan++)
{
if (set[scan] < pivotValue)
{
pivotIndex++;
swap(set[pivotIndex], set[scan]);
}
ç HERE
}
swap(set[start], set[pivotIndex]);
ç HERE
return pivotIndex;
}
Finally, identify the line that matches what you concluded above.
Deliverables:
Deliver the following for this assignment:
• This work sheet with a sketch of the array first split
• Program source code with required change
• Program output demonstrating array configuration after first split .
1. Suppose you want to implement an ADT in which you can insert valu.pdfforwardcom41
1. Suppose you want to implement an ADT in which you can insert values and retrieve or
remove the item with smallest value. (This ADT is called a priority queue). If forced to choose
between an array implementation and a linked list implementation, which would you choose and
why?
2. Write a recursive function that reads a list of integers from the console and prints them in
reverse order. The function should read until a negative number is encountered. You may only
use one local variable of type int. (So arrays or other aggregate data types are allowed.)
Example: 4 5 6 7 8 9 10 -1
10 9 8 7 6 5 4
3. Repeat question 2 using a local stack rather than recursion.
Solution
import java.util.Scanner;
class Value
{
String name;
int priority;
/** Constructor **/
public Value(String name, int priority)
{
this.name = name;
this.priority = priority;
}
/** toString() **/
public String toString()
{
return \"Value Name : \"+ name +\"\ Priority : \"+ priority;
}
}
/** Class PQ **/
class PQ
{
private Value[] SortedArray;
private int Size, Limit;
/** Constructor **/
public PQ(int Limit)
{
this.Limit = Limit + 1;
SortedArray = new Value[this.Limit];
Size = 0;
}
/** function to clear **/
public void clear()
{
SortedArray = new Value[Limit];
Size = 0;
}
/** function to check if empty **/
public boolean isEmpty()
{
return Size == 0;
}
/** function to check if full **/
public boolean isFull()
{
return Size == Limit - 1;
}
/** function to get Size **/
public int size()
{
return Size;
}
/** function to insert task **/
public void insert(String name, int priority)
{
Value Temp = new Value(name, priority);
SortedArray[++Size] = Temp;
int pos = Size;
while (pos != 1 && Temp.priority > SortedArray[pos/2].priority)
{
SortedArray[pos] = SortedArray[pos/2];
pos /=2;
}
SortedArray[pos] = Temp;
}
/** function to remove task **/
public Value remove()
{
int p, c;
Value item, temp;
if (isEmpty() )
{
System.out.println(\"array is empty\");
return null;
}
temp = SortedArray[1];
item = SortedArray[Size--];
p = 1;
c = 2;
while (c <= Size)
{
if (c < Size && SortedArray[c].priority >SortedArray[c + 1].priority)
c++;
if (temp.priority <=SortedArray[c].priority)
break;
SortedArray[p] = SortedArray[c];
p = c;
c *= 2;
}
SortedArray[p] = temp;
return item;
}
}
public class PQTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PQ pq = new PQ(4 );
pq.insert(\"A\",1);
pq.insert(\"B\",2);
pq.insert(\"C\",10);
pq.insert(\"D\",94);
System.out.println(\"Value A(32),B(2),C(1),D(94) inserted\ \");
System.out.println(\"Value removed \"+pq.remove());
}
}
====================================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ javac PQTest.java
akshay@akshay-Inspiron-3537:~/Chegg$ java PQTest
Value A(32),B(2),C(1),D(94) inserted
Value removed Value Name : A
Priority : 1
==========================================================
import java.util.*;
public class reverse {
public static void main(String[] args) {
Stack stack = new Stack();
System.
PQTimer.java A simple driver program to run timing t.docxjoyjonna282
/* PQTimer.java
A simple driver program to run timing tests on your ArrayPQ
and BinaryHeapPQ.
Programming Assignment #2
*/
import java.util.Iterator;
import java.util.ConcurrentModificationException;
import data_structures.*;
public class PQTimer {
public static void main(String [] args) {
///////////////////////////////////////////////////////////
/// Change this variable to something smaller if timing takes too long.
final int INITIAL_SIZE = 15000;
///////////////////////////////////////////////////////////
final int ITERATIONS = 10000;
final int NUMBER_OF_STEPS = 15;
final int MAX_SIZE = INITIAL_SIZE * NUMBER_OF_STEPS +1;
final int NUMBER_OF_PRIORITIES = 20;
int size = INITIAL_SIZE;
long sequence_number = 0;
long start, stop;
int priority;
PQTestObject [] array = new PQTestObject[MAX_SIZE];
for(int i=0; i < MAX_SIZE; i++)
array[i] = new PQTestObject((int) ((10000*Math.random() %
NUMBER_OF_PRIORITIES) +1), sequence_number++);
for(int j=0; j < 15; j++) {
PriorityQueue<PQTestObject> queue =
new HeapPriorityQueue<PQTestObject>(MAX_SIZE);
queue.clear();
for(int i = 0; i < size; i++)
queue.insert(array[i]);
start = System.currentTimeMillis(); // start the timer
for(int i = 0; i < ITERATIONS; i++) {
queue.insert(array[(int)(100000*Math.random() %
MAX_SIZE)]);
queue.remove();
}
stop = System.currentTimeMillis();
System.out.println("HeapPQ, Time for n=" + size + ": " +
(stop-start));
queue.clear();
queue = new ArrayPriorityQueue<PQTestObject>(MAX_SIZE);
for(int i = 0; i < size; i++)
queue.insert(array[i]);
start = System.currentTimeMillis(); // start the timer
for(int i = 0; i < ITERATIONS; i++) {
queue.insert(array[(int)(100000*Math.random() %
MAX_SIZE)]);
queue.remove();
}
stop = System.currentTimeMillis();
System.out.println("ArrayPQ, Time for n=" + size + ": " +
(stop-start)+"\n");
size += INITIAL_SIZE;
}
}
}
/* PQTestObject.java
A simple testing object that has a priority. The sequence
number in this class is NOT the insertion sequence number
you will have in the BinaryHeapPQ class. It is only used
for verification of correct behavior, and never used in
ordering objects of this class.
*/
public class PQTestObject implements Comparable<PQTestObject> {
private int priority;
private long sequence_number;
public PQTestObject(int p, long s) {
priority = p;
sequence_number = s;
}
public int compareTo(PQTestObject o) {
return priority - o.priority;
}
public String toString() {
...
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 .
all i need is these two filesCreate VectorContainer.hppCreat.docxjack60216
all i need is these two files
Create VectorContainer.hpp
Create SelectionSort.hpp
Test SelectionSort.hpp using the VectorContainer.hpp class you made
# Strategy Pattern
In this lab you will create a strategy pattern for sorting a collection of expression trees by their `evaluate()` value, which you will pair with different containers to see how strategies can be paired with different clients through an interface to create an easily extendable system. This lab requires a completed composite pattern from the previous lab, so you should begin by copying your or your partner's code from the previous assignment into your new repo, making sure it compiles correctly, and running your tests to make sure everything is still functioning correctly.
You will start this lab by creating two expression tree containers: one that uses a vector to hold your trees (class `VectorContainer`) and one that uses a standard list (class `ListContainer`). Each of these container classes should be able to hold any amount of different expressions each of which can be of any size. You will implement them both as subclasses of the following `Container` abstract base class, which has been provided to you in container.h. You should create each one independently, creating tests for them using the google test framework before moving on. Each container should be it’s own commit with a proper commit message. Optionally you can create each one as a branch and merge it in once it has been completed.
class Container {
protected:
Sort* sort_function;
public:
/* Constructors */
Container() : sort_function(nullptr) { };
Container(Sort* function) : sort_function(function) { };
/* Non Virtual Functions */
void set_sort_function(Sort* sort_function); // set the type of sorting algorithm
/* Pure Virtual Functions */
// push the top pointer of the tree into container
virtual void add_element(Base* element) = 0;
// iterate through trees and output the expressions (use stringify())
virtual void print() = 0;
// calls on the previously set sorting-algorithm. Checks if sort_function is not
// null, throw exception if otherwise
virtual void sort() = 0;
/* Functions Needed to Sort */
//switch tree locations
virtual void swap(int i, int j) = 0;
// get top ptr of tree at index i
virtual Base* at(int i) = 0;
// return container size
virtual int size() = 0;
};
Notice that our Container abstract base class does not have any actual STL containers because it leaves the implementation details of the container to the subclasses. You **must use the homogeneous interface above for your sort functions, and you are only allowed to manipulate the containers through this interface, not directly**. This will allow you to extend and change the underlying functionality without having to change anything t.
For problems 3 and 4, consider the following functions that implemen.pdfanjandavid
For problems 3 and 4, consider the following functions that implement the dequeue operation for
a priority queue that is implemented with a heap.
int[] pQueue;
int length;
int dequeue()
{
int node = 1;
int value = pQueue[--length];
int maxValue = pQueue[node];
int location = sift(node * 2, value);
pQueue[location] = value;
return maxValue;
}
int sift(int node, int value)
{
if (node <= length)
{
if (node < length && pQueue[node] < pQueue[node + 1]) node++;
if (value < pQueue[node])
{
pQueue[node / 2] = pQueue[node];
return sift(node * 2, value);
}
}
return node / 2;
}
3. Write the recurrence equation and initial conditions that expresses the execution time cost for
the sift function in the above algorithm. Draw the recursion tree assuming that n = 8. Assume
that n represents the number of nodes in the subtree at each step of the sifting operation.
4. Determine the critical exponent for the recurrence equation in problem 3. Apply the Little
Master Theorem to solve that equation specifically stating which part of the theorem is applied to
arrive at the solution.
Solution
using System.Collections;
using System.Collections.Generic;
namespace PriorityQueueDemo
{
///
/// Priority queue based on binary heap in program,
/// Elements with minimum priority dequeued first in program
///
/// Type of priorities
/// Type of values
public class PriorityQueues : ICollection>
{
private List> _baseHeap;
private IComparer _comparers;
#region Constructor
///
/// Initializes a new instance of priority queue with default initial capacity and default
priority comparer in program
///
public PriorityQueues()
: this(Comparers.Default)
{
}
///
/// Initializes a new instance of priority queue with specified initial capacity and default
priority comparer in program
///
/// initial capacity
public PriorityQueues(int capacity)
: this(capacity, Comparers.Default)
{
}
///
/// Initializes a new instance of priority queue with specified initial capacity and specified
priority comparer in program
///
/// initial capacity
/// priority comparer
public PriorityQueues(int capacity, IComparers comparer)
{
if (comparer == null)
throw new ArgumentNullException();
_baseHeaps = new List>(capacity);
_comparers= comparer;
}
///
/// Initializes a new instance of priority queue with default initial capacity and specified
priority comparer in program
///
/// priority comparer
public PriorityQueues(IComparer comparers)
{
if (comparers == null)
throw new ArgumentNullException();
_baseHeap = new List>();
_comparer = comparers;
}
///
/// Initializes a new instance of priority queue with specified data and default priority
comparer in program
///
/// data to be inserted into priority queue in program
public PriorityQueues(IEnumerable> data)
: this(data, Comparers.Default)
{
}
///
/// Initializes a new instance of priority queue with specified data and specified priority
comparer in program
///
/// data to be inserted into priority queue
/// priority comparer in program
public PriorityQueue(IEnumer.
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxbradburgess22840
In Class Assignmetz/CST280W13a-1.pdf
CST 280 In-Class Practice – Week 13
Manually determine the configuration of the priority queue (stored as a heap) created
by the following operations. Trace the following logic and define the output:
enqueue(7);
enqueue(17);
enqueue(2);
enqueue(5);
enqueue(22);
enqueue(19);
enqueue(6);
enqueue(11);
enqueue(13);
write the queue contents
dequeue and write front item
enqueue(15);
enqueue(8);
dequeue and write front item
dequeue and write front item
enqueue(24);
enqueue(14);
write the queue contents
Part 2
Then, verify the output by implementing the algorithm by rewriting the priority
queue demonstration program discussed in class. Files needed:
testPQueue.cpp pqType.h heap.cpp
Deliverables
• This cover sheet (with your names on it)
• Driver source code and output for verification program exectution.
In Class Assignmetz/CST280W13b.pdf
CST 280 In-Class Practice – Week 13
Use this page as a worksheet to sketch the progression of the elements up to the first
split for the QuickSort algorithm. Use the middle array element as the split value:
15 34 99 42 11 41 66 23 55 93 48
Next, access the file quickSort.cpp from the course web page. Tailor the program
by entering the array values above in place of the integer values used for an in-class
demonstration. Be sure to adjust the index range to match the size of this array.
Remember that the parameters to the QuickSort algorithm are starting and ending index
values, not the size of the array.
Next, insert code to demonstrate the state of the array after the first split. This should
verify what you did by hand above. Insert the following code at various points within
the partition function to “see” the array at various stages of processing:
for (int i = start; i <= end; i++) // <== ADD
cout << set[i] << ' ';
cout << endl;
Insert the code at these positions:
int partition(int set[], int start, int end)
{
int pivotValue, pivotIndex, mid;
mid = (start + end) / 2;
swap(set[start], set[mid]);
pivotIndex = start;
pivotValue = set[start];
ç HERE
for (int scan = start + 1; scan <= end; scan++)
{
if (set[scan] < pivotValue)
{
pivotIndex++;
swap(set[pivotIndex], set[scan]);
}
ç HERE
}
swap(set[start], set[pivotIndex]);
ç HERE
return pivotIndex;
}
Finally, identify the line that matches what you concluded above.
Deliverables:
Deliver the following for this assignment:
• This work sheet with a sketch of the array first split
• Program source code with required change
• Program output demonstrating array configuration after first split .
1. Suppose you want to implement an ADT in which you can insert valu.pdfforwardcom41
1. Suppose you want to implement an ADT in which you can insert values and retrieve or
remove the item with smallest value. (This ADT is called a priority queue). If forced to choose
between an array implementation and a linked list implementation, which would you choose and
why?
2. Write a recursive function that reads a list of integers from the console and prints them in
reverse order. The function should read until a negative number is encountered. You may only
use one local variable of type int. (So arrays or other aggregate data types are allowed.)
Example: 4 5 6 7 8 9 10 -1
10 9 8 7 6 5 4
3. Repeat question 2 using a local stack rather than recursion.
Solution
import java.util.Scanner;
class Value
{
String name;
int priority;
/** Constructor **/
public Value(String name, int priority)
{
this.name = name;
this.priority = priority;
}
/** toString() **/
public String toString()
{
return \"Value Name : \"+ name +\"\ Priority : \"+ priority;
}
}
/** Class PQ **/
class PQ
{
private Value[] SortedArray;
private int Size, Limit;
/** Constructor **/
public PQ(int Limit)
{
this.Limit = Limit + 1;
SortedArray = new Value[this.Limit];
Size = 0;
}
/** function to clear **/
public void clear()
{
SortedArray = new Value[Limit];
Size = 0;
}
/** function to check if empty **/
public boolean isEmpty()
{
return Size == 0;
}
/** function to check if full **/
public boolean isFull()
{
return Size == Limit - 1;
}
/** function to get Size **/
public int size()
{
return Size;
}
/** function to insert task **/
public void insert(String name, int priority)
{
Value Temp = new Value(name, priority);
SortedArray[++Size] = Temp;
int pos = Size;
while (pos != 1 && Temp.priority > SortedArray[pos/2].priority)
{
SortedArray[pos] = SortedArray[pos/2];
pos /=2;
}
SortedArray[pos] = Temp;
}
/** function to remove task **/
public Value remove()
{
int p, c;
Value item, temp;
if (isEmpty() )
{
System.out.println(\"array is empty\");
return null;
}
temp = SortedArray[1];
item = SortedArray[Size--];
p = 1;
c = 2;
while (c <= Size)
{
if (c < Size && SortedArray[c].priority >SortedArray[c + 1].priority)
c++;
if (temp.priority <=SortedArray[c].priority)
break;
SortedArray[p] = SortedArray[c];
p = c;
c *= 2;
}
SortedArray[p] = temp;
return item;
}
}
public class PQTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PQ pq = new PQ(4 );
pq.insert(\"A\",1);
pq.insert(\"B\",2);
pq.insert(\"C\",10);
pq.insert(\"D\",94);
System.out.println(\"Value A(32),B(2),C(1),D(94) inserted\ \");
System.out.println(\"Value removed \"+pq.remove());
}
}
====================================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ javac PQTest.java
akshay@akshay-Inspiron-3537:~/Chegg$ java PQTest
Value A(32),B(2),C(1),D(94) inserted
Value removed Value Name : A
Priority : 1
==========================================================
import java.util.*;
public class reverse {
public static void main(String[] args) {
Stack stack = new Stack();
System.
PQTimer.java A simple driver program to run timing t.docxjoyjonna282
/* PQTimer.java
A simple driver program to run timing tests on your ArrayPQ
and BinaryHeapPQ.
Programming Assignment #2
*/
import java.util.Iterator;
import java.util.ConcurrentModificationException;
import data_structures.*;
public class PQTimer {
public static void main(String [] args) {
///////////////////////////////////////////////////////////
/// Change this variable to something smaller if timing takes too long.
final int INITIAL_SIZE = 15000;
///////////////////////////////////////////////////////////
final int ITERATIONS = 10000;
final int NUMBER_OF_STEPS = 15;
final int MAX_SIZE = INITIAL_SIZE * NUMBER_OF_STEPS +1;
final int NUMBER_OF_PRIORITIES = 20;
int size = INITIAL_SIZE;
long sequence_number = 0;
long start, stop;
int priority;
PQTestObject [] array = new PQTestObject[MAX_SIZE];
for(int i=0; i < MAX_SIZE; i++)
array[i] = new PQTestObject((int) ((10000*Math.random() %
NUMBER_OF_PRIORITIES) +1), sequence_number++);
for(int j=0; j < 15; j++) {
PriorityQueue<PQTestObject> queue =
new HeapPriorityQueue<PQTestObject>(MAX_SIZE);
queue.clear();
for(int i = 0; i < size; i++)
queue.insert(array[i]);
start = System.currentTimeMillis(); // start the timer
for(int i = 0; i < ITERATIONS; i++) {
queue.insert(array[(int)(100000*Math.random() %
MAX_SIZE)]);
queue.remove();
}
stop = System.currentTimeMillis();
System.out.println("HeapPQ, Time for n=" + size + ": " +
(stop-start));
queue.clear();
queue = new ArrayPriorityQueue<PQTestObject>(MAX_SIZE);
for(int i = 0; i < size; i++)
queue.insert(array[i]);
start = System.currentTimeMillis(); // start the timer
for(int i = 0; i < ITERATIONS; i++) {
queue.insert(array[(int)(100000*Math.random() %
MAX_SIZE)]);
queue.remove();
}
stop = System.currentTimeMillis();
System.out.println("ArrayPQ, Time for n=" + size + ": " +
(stop-start)+"\n");
size += INITIAL_SIZE;
}
}
}
/* PQTestObject.java
A simple testing object that has a priority. The sequence
number in this class is NOT the insertion sequence number
you will have in the BinaryHeapPQ class. It is only used
for verification of correct behavior, and never used in
ordering objects of this class.
*/
public class PQTestObject implements Comparable<PQTestObject> {
private int priority;
private long sequence_number;
public PQTestObject(int p, long s) {
priority = p;
sequence_number = s;
}
public int compareTo(PQTestObject o) {
return priority - o.priority;
}
public String toString() {
...
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 .
Given the following errors and class in Java- How are these errors fix.pdfNicholasflqStewartl
Given the following errors and class in Java :
How are these errors fixed?
Errors when testing:
1) test_append3(ThreeTenDynArrayTester)
java.lang.NullPointerException: Cannot read the array length because "this.data" is null
at ThreeTenDynArray.append(ThreeTenDynArray.java:161)
at ThreeTenDynArrayTester.test_append3(ThreeTenDynArrayTester.java:146)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.junit.internal.runners.statements.FailOnTimeout$StatementThread.run(FailOnTimeout.java:74)
2) test_setCapacity1(ThreeTenDynArrayTester)
java.lang.AssertionError: Capacity failed to grow, expected capacity 8
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.assertTrue(Assert.java:41)
at ThreeTenDynArrayTester.test_setCapacity1(ThreeTenDynArrayTester.java:694)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.junit.internal.runners.statements.FailOnTimeout$StatementThread.run(FailOnTimeout.java:74)
3) test_constructor2(ThreeTenDynArrayTester)
java.lang.AssertionError: Initial capacity of the storage has incorrect initCapacity
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.assertTrue(Assert.java:41)
at ThreeTenDynArrayTester.test_constructor2(ThreeTenDynArrayTester.java:90)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.Re.
Create a Dynamic Array container with this user interface Ge.pdfsktambifortune
Create a \"Dynamic Array\" container with this user interface: // Gets the current number of
entries in container int getCurrentSize() // Returns the current capacity of the container int
capacity() // Checks whether the container is empty. boolean isEmpty() // Adds a new entry to
the container boolean insert(newEntry) // Removes an entry from the container and moves all
entries above anEntry down one boolean remove(anEntry) // Get index value int getValue(index)
// Removes all entries from the container void clear() // Resize a container by doubling current
capacity int resize() * Implement dynamic resizing using this algorithm: 1. Starting with a
dynamic size of 10, if the number of elements exceed this number: a. Reallocate the container
size to double the current size b. Move the contents of the current container to the newly sized
container c. Delete the previously sized container. Resize C++ Data* ptemp = new
Data[capacity*2 ]; for (int i=0; i
Solution
container.cpp ---
#include
#include
using namespace std;
template
class DynamicArray
{
/*
Container class DynamicArray
*/
private:
ArrayType *arr;
int entry,size;
public:
DynamicArray();
~DynamicArray();
int getCurrentSize() { return entry; };/*this function returns total number of entries in the
container*/
int capacity() { return size; };/*this function returns capacity of the container*/
bool isEmpty();
bool insert(ArrayType);
bool remove(ArrayType);
int getValue(ArrayType);
void clear() { entry = 0; };/*this function clears the whole container*/
int resize();
};
template
int DynamicArray::resize()
{
/*this function resizes the container by doubling its previous size*/
ArrayType *temp = NULL;
try
{
temp = new ArrayType [2 * size];
}catch(bad_alloc xa){
cout<<\"\ Array allocation failed\ \";
exit(1);
}
size *= 2;
for(int i = 0 , j = 0 ; i < entry ; i++)
{
temp[i] = arr[i];
j++;
}
delete [] arr;
arr = NULL;
arr = temp , temp = NULL;
return size;
}
template
int DynamicArray::getValue(ArrayType index)
{
/*this function return index of an element specified as index in the container if it presents
in the container, else it returns -1*/
int loc = -1;
for(int i = 0 ; i < entry ; i++)
{
if(arr[i] == index)
{
loc = i;
break;
}
}
return loc;
}
template
bool DynamicArray::remove(ArrayType anEntry)
{
/*this function removes an element specified as anEntry from the container and returns true
and
decrements total number of entries by one else returns false*/
bool flag = false;
int index = -1;
for(int i = 0 ; i < entry ; i++)
{
if(arr[i] == anEntry)
{
index = i , flag = true;
break;
}
}
for(int i = index ; i < (entry - 1) && flag == true ; i++)
{
arr[i] = arr[i+1];
}
if(flag == true)
entry -= 1;
return flag;
}
template
bool DynamicArray::insert(ArrayType newEntry)
{
/*this function inserts an element specified as newEntry in the container,
if it successfully inserts an element then it returns true and increments total
number of entries by one, else it returns false*/
entry += 1;
if(entry <= size)
{
ar.
public class DoubleArraySeq implements Cloneable { Priva.pdfannaimobiles
public class DoubleArraySeq implements Cloneable
{
// Private Instance Variables
private double[] data;
private int manyItems;
private int currentIndex;
//Constructor Methods
/**
* Initialize an empty sequence with an initial capacity of 10.
**/
public DoubleArraySeq()
{
try{
//Set a default capacity for new DoubleArraySeq\'s.
int INITAL_CAPACITY = 10;
//Set each instance variable to its initial value.
data = new double[INITAL_CAPACITY];
manyItems = 0;
currentIndex = 0;
}//end try
catch (OutOfMemoryError e){
throw new OutOfMemoryError (\"There is not enough memory to create a new
sequence!\");
}//end catch
}//end DoubleArraySeq() method
/**
* Initialize an empty sequence with a specified initial capacity. Note that the addAfter and
addBefore methods work
* efficiently (without needing more memory) until this capacity is reached.
**/
public DoubleArraySeq(int initialCapacity)
{
try{
//Set each instance variable to its initial value.
data = new double[initialCapacity];
currentIndex = 0;
manyItems = 0;
}//end try
catch (OutOfMemoryError e){
throw new OutOfMemoryError (\"There is not enough memory to create a new sequence
of capacity \" + initialCapacity + \"!\");
}//end catch
}//end DoubleArraySeq(int initialCapacity) method
// Accessor Methods
/**
**/
public boolean isCurrent()
{
return (currentIndex < manyItems);
}//end isCurrent() method
/**
* Accessor method to get the current element of this sequence.
**/
public double getCurrent()
{
//Confirm that there is a current element first.
if (isCurrent())
return data[currentIndex];
else
throw new IllegalStateException(\"There is no current element! Please specify a current
element first.\");
}//end getCurrent() method
/**
* Accessor method to get the current capacity of this sequence.
**/
public int getCapacity()
{
//Returns the number of indexes in the array.
return data.length;
}//end getCapacity() method
/**
* Accessor method to get the available capacity (number of empty indexes) of this sequence.
* The available capacity (number of empty indexes) of this sequence.
**/
public int getAvailCapacity()
{
//Returns the number of empty indexes in the array.
return data.length - manyItems;
}//end getAvailCapacity() method
/**
**/
public int size()
{
//Returns the number of elements in the sequence.
return manyItems;
}//end size() method
// Setter Methods
/**
* A method to move forward, so the current element is now the next element in this sequence.
**/
public void advance()
{
if (isCurrent())
currentIndex++;
else
throw new IllegalStateException (\"There is no current element! Advance may not be
called.\");
}//end advance() method
/**
* A method to set the current element at the front of this sequence.
**/
public void start()
{
if (manyItems > 0)
currentIndex = 0;
else
throw new IllegalStateException(\"This sequence is empty!\");
}//end start() method
/**
* A method that makes the last element of the sequence the current element.
**/
public void setCurrentLast()
{
if (manyItems > 0)
currentIndex = ma.
Given the following class in Java- public class ThreeTenDynArray-T- {.pdfNicholasflqStewartl
Given the following class in Java :
public class ThreeTenDynArray<T> {
//default initial capacity / minimum capacity
private static final int MIN_CAPACITY = 2;
//underlying array for storage -- you MUST use this for credit!
//Do NOT change the name or type
private T[] data;
private int size = 0;
private int capacity = 0;
// ADD MORE PRIVATE MEMBERS HERE IF NEEDED!
/**
*
*/
@SuppressWarnings("unchecked")
public ThreeTenDynArray() {
// Constructor
// Initial capacity of the storage should be MIN_CAPACITY
// Hint: Can't remember how to make an array of generic Ts? It's in the textbook...
data = (T[])(new Object[MIN_CAPACITY]);
size = 0;
capacity = MIN_CAPACITY;
}
/**
* @param initCapacity
*/
@SuppressWarnings("unchecked")
public ThreeTenDynArray(int initCapacity) {
// Constructor
// Initial capacity of the storage should be initCapacity.
// - Throw IllegalArgumentException if initCapacity is smaller than
// MIN_CAPACITY 2
// - Use this _exact_ error message for the exception
// (quotes are not part of the message):
// "Capacity must be at least 2!"
if (initCapacity < MIN_CAPACITY) {
throw new IllegalArgumentException("Capacity must be at least 2!");
}
}
/**
* @return
*/
public int size() {
// Report the current number of elements
// O(1)
return size; //default return, remove/change as needed
}
/**
* @return
*/
public int capacity() {
// Report max number of elements of the current storage
// (subject to change since this is a _dynamic_ )
// O(1)
return capacity; //default return, remove/change as needed
}
/**
* @param index index you're changing
* @param value what you're adding
* @return the old item at the index
*/
public T set(int index, T value) {
// Replace the item at the given index to be the given value.
// Return the old item at that index.
// Note: You cannot add new items (i.e. cannot increase size) with this method.
// O(1)
//return firstIndexOf(value);
// - Throw IndexOutOfBoundsException if index is not valid
// - Use this code to produce the correct error message for
// the exception (do not use a different message):
// "Index: " + index + " out of bounds!"
if (index < 0 && index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + " out of bounds!");
}
// - Throw IllegalArgumentException if value is null.
// - Use this _exact_ error message for the exception
// (quotes are not part of the message):
// "Cannot include null values!"
if (value==null) {
throw new IllegalArgumentException("Cannot include null values!");
}
T oldValue = data[index];
data[index] = value;
return oldValue; //default return, remove/change as needed
}
/**
* @param index
* @return
*/
public T get(int index) {
// Return the item at the given index
if (index < 0 && index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + " out of bounds!");
}
// O(1)
// Use the exception (and error message) described in set()
// for invalid indicies.
return data[index]; //default return, remove/change as needed
}
/**
* @param value
*/
@SuppressWarn.
JAVAneed help with public IteratorItem iterator()import java.u.pdffcsondhiindia
JAVA
need help with public Iterator iterator()
import java.util.Iterator;
/*
* GroupsQueue class supporting addition and removal of items
* with respect to a given number of priorities and with
* respect to the FIFO (first-in first-out) order for items
* with the same priority.
*
* An example, where GroupsQueue would be useful is the airline
* boarding process: every passenger gets assigned a priority,
* usually a number, e.g., group 1, group 2, group 3, etc. and
* the passengers line up at the end of the queue of their groups
* in a FIFO fashion; and, when removing from the GroupsQueue,
* i.e., when the passengers are boarding the plane, they get
* removed first by their group priorities and then by their FIFO
* ordering within that particular priority group.
*
* Your homework is to implement the below GroupsQueue data
* structure, so that it functions in the way described above.
*
* You may use the provided Queue class for implementing the
* GroupsQueue class.
*/
public class GroupsQueue implements Iterable {
private Node first;
private Node last;
private int n;
private static class Node {
private Item item;
private Node next;
}
public void Queue() {
first = null;
last = null;
n = 0;
}
// TODO : implement the data structure (20 points)
/**
* Initializes an empty GroupsQueue with g groups
* @return
*/
public GroupsQueue(int g) {
first = new Node<>();
last = first;
for(int i=1; i<=19; i++){
last.next = new Node<>();
last = last.next;
}
}
// TODO : implement the constructor (20 points)
/**
* Is this GroupsQueue empty?
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Returns the number of items in the GroupsQueue.
*/
public int size() {
return n; // TODO (20 points)
}
/**
* Adds the item to this GroupsQueue with group id = gId.
*/
public void add(Item item, int gId) {
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else{
oldlast.next = last;
}
n++;
}
// TODO (20 points)
/**
* Removes and returns the item with the lowest group id
*/
public Item remove() {
Node temp = first;
Node prev = first;
Item minGid;
if (! isEmpty())
{
minGid = first.item;
}
else
{
return null;
}
while(temp!= null)
{
prev = temp;
temp = temp.next;
if (temp.item == minGid)
{
minGid = (Item) temp.item;
}
}
if (minGid == first.item)
{
first = first.next;
}
else
{
prev.next = prev.next.next;
}
n--;
return minGid;
}// TODO (20 points)
/**
* Returns an iterator that iterates over the items in this GroupsQueue
* in group id order (lowest id first) and in FIFO order in each group.
*/
public Iterator iterator() {
// TODO
// BONUS (20 points)
return null;
}
}
Solution
Implementation given here seems to have many logical errors.
Here is the code given for GroupQueue:
package groupqueue;
public class GroupQueue{
/**
* n is number of queues maintained. and queues is array of all queues maintained by
GroupQueue.
* here there are n groups . so maintain n queues and each queue represent one group.
*/
public int n;
public Que.
package algs13;
import stdlib.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
/* ***********************************************************************
* Compilation: javac Queue.java
* Execution: java Queue < input.txt
* Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic queue, implemented using a linked list.
*
* % java Queue < tobe.txt
* to be or not to be (2 left on queue)
*
*************************************************************************/
/**
* The <tt>Queue</tt> class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the top item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* All queue operations except iteration are constant time.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*/
public class Queue<T> implements Iterable<T> {
private int N; // number of elements on queue
private Node<T> first; // beginning of queue
private Node<T> last; // end of queue
// helper linked list class
private static class Node<T> {
public Node() { }
public T item;
public Node<T> next;
}
/**
* Create an empty queue.
*/
public Queue() {
first = null;
last = null;
N = 0;
}
/**
* Is the queue empty?
*/
public boolean isEmpty() {
return first == null;
}
/**
* Return the number of items in the queue.
*/
public int size() {
return N;
}
/**
* Return the item least recently added to the queue.
* @throws java.util.NoSuchElementException if queue is empty.
*/
public T peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return first.item;
}
/**
* Add the item to the queue.
*/
public void enqueue(T item) {
Node<T> oldlast = last;
last = new Node<>();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
}
/**
* Remove and return the item on the queue least recently added.
* @throws java.util.NoSuchElementException if queue is empty.
*/
public T dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
T item = first.item;
first = first.next;
N--;
if (isEmpty()) last = null;
return item;
}
/**
* Return string representation.
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (T item : this)
s.append(item + " ");
return s.toString();
}
// check internal invariants
private static <T> boolean check(Queue<T> that) {
int N = that.N;
Queue.Node<T> first = that.first;
Queue.Node<T> last = that.last;
if (N == 0) {
if (first != null) return false;
if (last != null) return false;
}
else if (N == 1) {
if (f.
We're taking a closer look into a new utility class from Android Support Library. It enables you to calculate the difference between two lists and output a list of update operations swiftly and with style. Presented by Željko Plesac from Infinum.
This file contains a complete array-based MultiSet, but not the code.pdfdeepaksatrker
This file contains a complete array-based MultiSet, but not the code needed to support its
Iterator. Complete the Iterator\'s next() and hasNext() methods.
Solution
Hi, I have implemented both required methods.
Please let me know in case of any issue.
import java.util.Collection;
import java.util.Iterator;
public class ArrayMultiSet implements Collection {
/** Array in which the elements in this multiset are stored. */
private E[] _store;
/**
* Array indices below this amount contain the active elements in this collection.
*/
private int _size;
/**
* Modification counter used to preserve the fail-fast nature of its iterators.
*/
private long _modCount;
/**
* Create a new empty multiset.
*/
public ArrayMultiSet() {
_modCount = 0;
clear();
}
/**
* Remove all of the elements within the instance and invalidate any current iterators.
*/
@SuppressWarnings(\"unchecked\")
@Override
public void clear() {
_store = (E[]) (new Object[16]);
_size = 0;
// maintains the class invariant
}
/**
* Update the multiset so that it includes all of the elements from before the call AND the given
element.
*
* @param e Item to be added to this collection.
*/
@SuppressWarnings(\"unchecked\")
@Override
public boolean add(E e) {
// Check if we do not have enough space in the underlying array to store the
// new element
if (_size == _store.length) {
// We do not have space, so create a new larger space (doubling the size
// is the most time efficient)
E[] newStore = (E[]) new Object[_store.length * 2];
// Copy all of the references into the new array
for (int i = 0; i < _store.length; i++ ) {
newStore[i] = _store[i];
}
_store = newStore;
// An easier, more efficient way of coding this (but less useful for
// teaching) would instead be:
// _store = Arrays.copyOf(_store, _store.length * 2);
}
// Add the element to the store
_store[_size] = e;
// Finally, we can increase _size, since this change will no longer violate
// any class invariants.
_size += 1;
return true;
}
/**
* Return true if at least one element in the multiset is equal to the given object. When {@code
obj} is null, it must
* use the {@code ==} operator to perform these checks, but when {@code obj} is not null, the
{@link Object#equals}
* method is used.
*
* @param obj Object (or null) for which we will search
* @return {@code true} if {@code obj} was found; {@code false} if a match could not be
found.
*/
@Override
public boolean contains(Object obj) {
// Only scan through _size, since those are the only \"real\" entries for the
// multiset.
for (int i = 0; i < _size; i++ ) {
// When obj is null, we need to use ==
if ((obj == null) && (_store[i] == null)) {
return true;
}
// Otherwise, we use .equals() to find a match
else if ((obj != null) && obj.equals(_store[i])) {
return true;
}
// No else clause, since the match could be at a higher index!
}
// Checked all VALID indices, so the result must be:
return false;
}
@Override
public int size() {
return _size;
}
/**
* Remove the element found at the given index. .
this file has a complete array-based MultiSet, but not the code need.pdfflashfashioncasualwe
this file has a complete array-based MultiSet, but not the code needed to support its Iterator.
Complete the Iterator\'s next() and hasNext() methods.
Solution
Hi, I have implemented required methods.
Please let me know in case of any issue.
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ArrayMultiSet implements Collection {
/** Array in which the elements in this multiset are stored. */
private E[] _store;
/**
* Array indices below this amount contain the active elements in this collection.
*/
private int _size;
/**
* Modification counter used to preserve the fail-fast nature of its iterators.
*/
private long _modCount;
/**
* Create a new empty multiset.
*/
public ArrayMultiSet() {
_modCount = 0;
clear();
}
/**
* Remove all of the elements within the instance and invalidate any current iterators.
*/
@SuppressWarnings(\"unchecked\")
@Override
public void clear() {
_store = (E[]) (new Object[16]);
_size = 0;
// maintains the class invariant
}
/**
* Update the multiset so that it includes all of the elements from before the call AND the given
element.
*
* @param e Item to be added to this collection.
*/
@SuppressWarnings(\"unchecked\")
@Override
public boolean add(E e) {
// Check if we do not have enough space in the underlying array to store the
// new element
if (_size == _store.length) {
// We do not have space, so create a new larger space (doubling the size
// is the most time efficient)
E[] newStore = (E[]) new Object[_store.length * 2];
// Copy all of the references into the new array
for (int i = 0; i < _store.length; i++ ) {
newStore[i] = _store[i];
}
_store = newStore;
// An easier, more efficient way of coding this (but less useful for
// teaching) would instead be:
// _store = Arrays.copyOf(_store, _store.length * 2);
}
// Add the element to the store
_store[_size] = e;
// Finally, we can increase _size, since this change will no longer violate
// any class invariants.
_size += 1;
return true;
}
/**
* Return true if at least one element in the multiset is equal to the given object. When {@code
obj} is null, it must
* use the {@code ==} operator to perform these checks, but when {@code obj} is not null, the
{@link Object#equals}
* method is used.
*
* @param obj Object (or null) for which we will search
* @return {@code true} if {@code obj} was found; {@code false} if a match could not be
found.
*/
@Override
public boolean contains(Object obj) {
// Only scan through _size, since those are the only \"real\" entries for the
// multiset.
for (int i = 0; i < _size; i++ ) {
// When obj is null, we need to use ==
if ((obj == null) && (_store[i] == null)) {
return true;
}
// Otherwise, we use .equals() to find a match
else if ((obj != null) && obj.equals(_store[i])) {
return true;
}
// No else clause, since the match could be at a higher index!
}
// Checked all VALID indices, so the result must be:
return false;
}
@Override
public int size() {
return _size;
}
/**
* Remove the ele.
Refactoring, Agile Entwicklung, Continuous Integration – all diese für nachhaltigen Erfolg wichtigen Vorgehensweisen setzen Erfahrung mit Unit Testing voraus. Abseits von den üblichen "Bowling"-Beispielen möchten wir gerne einen Crashkurs inkl. Best Practices für das erfolgreiche Unit Testing durchführen. Anhand eines Beispielprojekts auf Basis des Zend Frameworks werden wir nach der Installation von PHPUnit auf allen Notebooks gemeinsam eine kleine Applikation aufbauen, die durchgehend Test-driven entwickelt wird.
Using c++Im also using a the ide editor called CodeLiteThe hea.pdffashiongallery1
Typed out please In a short and simple response comment on this persons answer for masonry
work Additives combined with concrete to achieve certain properties are called what? Name a
few that would benefit the Engineer and Customer.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Typed out please In a short and simple response comment on this persons answer for masonry
work Additives combined with concrete to achieve certain properties are called what? Name a
few that would benefit the Engineer and Customer.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Solution
The response of the person is good. He/she explained the admixtures and their applications pretty
well and also explained accelators, retarders and air entertainment in a simple straight forward
fashion.Overall i would say that the answer is satisfactory.
I will like to add \"PLASTICIZERS\" in the list of admixtures that would benefit the engineer
and customer. Plasticizers are water reducing admixtures and are added to the concrete mix for
making it more plastic without any further addition of water. In other words, they reduce the
quantity of water required to make concrete mixture of better plasticity.
PLEASE HIT LIKE BUTTON IF YOU FIND MY ANSWER SATISFACTORY.
THANK YOU..
In this lab, you will be given a simple code for a min Heap, and you.pdfcharanjit1717
In this lab, you will be given a simple code for a min Heap, and youre going to complete some of
the methods to handle some edge cases. Tasks for today: There are mainly two tasks, and the
logic of both of them is provided in their bodies: 1) Fully implement AddItem(). 2) Fully
implement HeapUp() Use the following start-up code. The main code and a demo class are
provided as .cs files. Use them to test your code. Once you complete the above two tasks, upload
the source code for your MinHeap class to Blackboard. class BinaryHeap : IEnumerable where T
: IComparable { private T[] array; private int count; // Number of elements (nodes) public
BinaryHeap(int size) { array = new T[size]; count = 0; } public T GetItem(int index) { return
array[index]; } private void SetItem(int index, T value) { while (index >= array.Length)
Grow(array.Length * 2); array[index] = value; } private void Grow(int newsize) {
Array.Resize(ref array, newsize); } // Indices of left and right children private int
LeftChildIndex(int pos) { return 2 * pos + 1; } private int RightChildIndex(int pos) { return 2 *
pos + 2; } private int GetParentIndex(int pos) => (pos - 1) / 2; private T GetRightChild(int pos)
=> array[RightChildIndex(pos)]; private T GetLeftChild(int pos) => array[LeftChildIndex(pos)];
private T GetParent(int pos) => array[GetParentIndex(pos)]; // "Has" methods to determine if the
indices exist private bool HasLeftChild(int pos) { if (LeftChildIndex(pos) < count) return true;
else return false; } private bool HasRightChild(int pos) { if (RightChildIndex(pos) < count)
return true; else return false; } private bool IsRoot(int pos) => pos == 0; // (true if element is
root) // Swap, uh, swaps two values given two indicies. This should be private but I originally
had it public for some reason. private void Swap(int position1, int position2) { T first =
array[position1]; array[position1] = array[position2]; array[position2] = first; } public void
AddItem(T value) { // This is part of la //Insert Logic // If the tree is empty, insert at the bottom
(it does that already) // if not, insert at the end, // From the end you either need to swap to the
root, and keep minheapify (Heapdown) // or, you should probably implement move up (for lab 6,
you need to implement // for that you run a while loop, check if the current position both isn't the
root, and is higher priority than a parent (in this case that probably means it's a lower value) // if
it is, swap with parent, and keep doing that until it's its in the array[count] = value; count++;
ReCalculateUp(); } private void HeapDown() { //CompareTo //this.CompareTo(value) returns <
0 if this < value //this.CompareTo(value) returns >0 if this > value int index = 0; while
(HasLeftChild(index)) { var smallerIndex = LeftChildIndex(index); if (HasRightChild(index)
&& (GetRightChild(index).CompareTo(GetLeftChild(index))<0) ) //there's a set of ( ) around the
right expression that are redundant but hopefully easier to read { smallerI.
Given the following errors and class in Java- How are these errors fix.pdfNicholasflqStewartl
Given the following errors and class in Java :
How are these errors fixed?
Errors when testing:
1) test_append3(ThreeTenDynArrayTester)
java.lang.NullPointerException: Cannot read the array length because "this.data" is null
at ThreeTenDynArray.append(ThreeTenDynArray.java:161)
at ThreeTenDynArrayTester.test_append3(ThreeTenDynArrayTester.java:146)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.junit.internal.runners.statements.FailOnTimeout$StatementThread.run(FailOnTimeout.java:74)
2) test_setCapacity1(ThreeTenDynArrayTester)
java.lang.AssertionError: Capacity failed to grow, expected capacity 8
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.assertTrue(Assert.java:41)
at ThreeTenDynArrayTester.test_setCapacity1(ThreeTenDynArrayTester.java:694)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.junit.internal.runners.statements.FailOnTimeout$StatementThread.run(FailOnTimeout.java:74)
3) test_constructor2(ThreeTenDynArrayTester)
java.lang.AssertionError: Initial capacity of the storage has incorrect initCapacity
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.assertTrue(Assert.java:41)
at ThreeTenDynArrayTester.test_constructor2(ThreeTenDynArrayTester.java:90)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.Re.
Create a Dynamic Array container with this user interface Ge.pdfsktambifortune
Create a \"Dynamic Array\" container with this user interface: // Gets the current number of
entries in container int getCurrentSize() // Returns the current capacity of the container int
capacity() // Checks whether the container is empty. boolean isEmpty() // Adds a new entry to
the container boolean insert(newEntry) // Removes an entry from the container and moves all
entries above anEntry down one boolean remove(anEntry) // Get index value int getValue(index)
// Removes all entries from the container void clear() // Resize a container by doubling current
capacity int resize() * Implement dynamic resizing using this algorithm: 1. Starting with a
dynamic size of 10, if the number of elements exceed this number: a. Reallocate the container
size to double the current size b. Move the contents of the current container to the newly sized
container c. Delete the previously sized container. Resize C++ Data* ptemp = new
Data[capacity*2 ]; for (int i=0; i
Solution
container.cpp ---
#include
#include
using namespace std;
template
class DynamicArray
{
/*
Container class DynamicArray
*/
private:
ArrayType *arr;
int entry,size;
public:
DynamicArray();
~DynamicArray();
int getCurrentSize() { return entry; };/*this function returns total number of entries in the
container*/
int capacity() { return size; };/*this function returns capacity of the container*/
bool isEmpty();
bool insert(ArrayType);
bool remove(ArrayType);
int getValue(ArrayType);
void clear() { entry = 0; };/*this function clears the whole container*/
int resize();
};
template
int DynamicArray::resize()
{
/*this function resizes the container by doubling its previous size*/
ArrayType *temp = NULL;
try
{
temp = new ArrayType [2 * size];
}catch(bad_alloc xa){
cout<<\"\ Array allocation failed\ \";
exit(1);
}
size *= 2;
for(int i = 0 , j = 0 ; i < entry ; i++)
{
temp[i] = arr[i];
j++;
}
delete [] arr;
arr = NULL;
arr = temp , temp = NULL;
return size;
}
template
int DynamicArray::getValue(ArrayType index)
{
/*this function return index of an element specified as index in the container if it presents
in the container, else it returns -1*/
int loc = -1;
for(int i = 0 ; i < entry ; i++)
{
if(arr[i] == index)
{
loc = i;
break;
}
}
return loc;
}
template
bool DynamicArray::remove(ArrayType anEntry)
{
/*this function removes an element specified as anEntry from the container and returns true
and
decrements total number of entries by one else returns false*/
bool flag = false;
int index = -1;
for(int i = 0 ; i < entry ; i++)
{
if(arr[i] == anEntry)
{
index = i , flag = true;
break;
}
}
for(int i = index ; i < (entry - 1) && flag == true ; i++)
{
arr[i] = arr[i+1];
}
if(flag == true)
entry -= 1;
return flag;
}
template
bool DynamicArray::insert(ArrayType newEntry)
{
/*this function inserts an element specified as newEntry in the container,
if it successfully inserts an element then it returns true and increments total
number of entries by one, else it returns false*/
entry += 1;
if(entry <= size)
{
ar.
public class DoubleArraySeq implements Cloneable { Priva.pdfannaimobiles
public class DoubleArraySeq implements Cloneable
{
// Private Instance Variables
private double[] data;
private int manyItems;
private int currentIndex;
//Constructor Methods
/**
* Initialize an empty sequence with an initial capacity of 10.
**/
public DoubleArraySeq()
{
try{
//Set a default capacity for new DoubleArraySeq\'s.
int INITAL_CAPACITY = 10;
//Set each instance variable to its initial value.
data = new double[INITAL_CAPACITY];
manyItems = 0;
currentIndex = 0;
}//end try
catch (OutOfMemoryError e){
throw new OutOfMemoryError (\"There is not enough memory to create a new
sequence!\");
}//end catch
}//end DoubleArraySeq() method
/**
* Initialize an empty sequence with a specified initial capacity. Note that the addAfter and
addBefore methods work
* efficiently (without needing more memory) until this capacity is reached.
**/
public DoubleArraySeq(int initialCapacity)
{
try{
//Set each instance variable to its initial value.
data = new double[initialCapacity];
currentIndex = 0;
manyItems = 0;
}//end try
catch (OutOfMemoryError e){
throw new OutOfMemoryError (\"There is not enough memory to create a new sequence
of capacity \" + initialCapacity + \"!\");
}//end catch
}//end DoubleArraySeq(int initialCapacity) method
// Accessor Methods
/**
**/
public boolean isCurrent()
{
return (currentIndex < manyItems);
}//end isCurrent() method
/**
* Accessor method to get the current element of this sequence.
**/
public double getCurrent()
{
//Confirm that there is a current element first.
if (isCurrent())
return data[currentIndex];
else
throw new IllegalStateException(\"There is no current element! Please specify a current
element first.\");
}//end getCurrent() method
/**
* Accessor method to get the current capacity of this sequence.
**/
public int getCapacity()
{
//Returns the number of indexes in the array.
return data.length;
}//end getCapacity() method
/**
* Accessor method to get the available capacity (number of empty indexes) of this sequence.
* The available capacity (number of empty indexes) of this sequence.
**/
public int getAvailCapacity()
{
//Returns the number of empty indexes in the array.
return data.length - manyItems;
}//end getAvailCapacity() method
/**
**/
public int size()
{
//Returns the number of elements in the sequence.
return manyItems;
}//end size() method
// Setter Methods
/**
* A method to move forward, so the current element is now the next element in this sequence.
**/
public void advance()
{
if (isCurrent())
currentIndex++;
else
throw new IllegalStateException (\"There is no current element! Advance may not be
called.\");
}//end advance() method
/**
* A method to set the current element at the front of this sequence.
**/
public void start()
{
if (manyItems > 0)
currentIndex = 0;
else
throw new IllegalStateException(\"This sequence is empty!\");
}//end start() method
/**
* A method that makes the last element of the sequence the current element.
**/
public void setCurrentLast()
{
if (manyItems > 0)
currentIndex = ma.
Given the following class in Java- public class ThreeTenDynArray-T- {.pdfNicholasflqStewartl
Given the following class in Java :
public class ThreeTenDynArray<T> {
//default initial capacity / minimum capacity
private static final int MIN_CAPACITY = 2;
//underlying array for storage -- you MUST use this for credit!
//Do NOT change the name or type
private T[] data;
private int size = 0;
private int capacity = 0;
// ADD MORE PRIVATE MEMBERS HERE IF NEEDED!
/**
*
*/
@SuppressWarnings("unchecked")
public ThreeTenDynArray() {
// Constructor
// Initial capacity of the storage should be MIN_CAPACITY
// Hint: Can't remember how to make an array of generic Ts? It's in the textbook...
data = (T[])(new Object[MIN_CAPACITY]);
size = 0;
capacity = MIN_CAPACITY;
}
/**
* @param initCapacity
*/
@SuppressWarnings("unchecked")
public ThreeTenDynArray(int initCapacity) {
// Constructor
// Initial capacity of the storage should be initCapacity.
// - Throw IllegalArgumentException if initCapacity is smaller than
// MIN_CAPACITY 2
// - Use this _exact_ error message for the exception
// (quotes are not part of the message):
// "Capacity must be at least 2!"
if (initCapacity < MIN_CAPACITY) {
throw new IllegalArgumentException("Capacity must be at least 2!");
}
}
/**
* @return
*/
public int size() {
// Report the current number of elements
// O(1)
return size; //default return, remove/change as needed
}
/**
* @return
*/
public int capacity() {
// Report max number of elements of the current storage
// (subject to change since this is a _dynamic_ )
// O(1)
return capacity; //default return, remove/change as needed
}
/**
* @param index index you're changing
* @param value what you're adding
* @return the old item at the index
*/
public T set(int index, T value) {
// Replace the item at the given index to be the given value.
// Return the old item at that index.
// Note: You cannot add new items (i.e. cannot increase size) with this method.
// O(1)
//return firstIndexOf(value);
// - Throw IndexOutOfBoundsException if index is not valid
// - Use this code to produce the correct error message for
// the exception (do not use a different message):
// "Index: " + index + " out of bounds!"
if (index < 0 && index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + " out of bounds!");
}
// - Throw IllegalArgumentException if value is null.
// - Use this _exact_ error message for the exception
// (quotes are not part of the message):
// "Cannot include null values!"
if (value==null) {
throw new IllegalArgumentException("Cannot include null values!");
}
T oldValue = data[index];
data[index] = value;
return oldValue; //default return, remove/change as needed
}
/**
* @param index
* @return
*/
public T get(int index) {
// Return the item at the given index
if (index < 0 && index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + " out of bounds!");
}
// O(1)
// Use the exception (and error message) described in set()
// for invalid indicies.
return data[index]; //default return, remove/change as needed
}
/**
* @param value
*/
@SuppressWarn.
JAVAneed help with public IteratorItem iterator()import java.u.pdffcsondhiindia
JAVA
need help with public Iterator iterator()
import java.util.Iterator;
/*
* GroupsQueue class supporting addition and removal of items
* with respect to a given number of priorities and with
* respect to the FIFO (first-in first-out) order for items
* with the same priority.
*
* An example, where GroupsQueue would be useful is the airline
* boarding process: every passenger gets assigned a priority,
* usually a number, e.g., group 1, group 2, group 3, etc. and
* the passengers line up at the end of the queue of their groups
* in a FIFO fashion; and, when removing from the GroupsQueue,
* i.e., when the passengers are boarding the plane, they get
* removed first by their group priorities and then by their FIFO
* ordering within that particular priority group.
*
* Your homework is to implement the below GroupsQueue data
* structure, so that it functions in the way described above.
*
* You may use the provided Queue class for implementing the
* GroupsQueue class.
*/
public class GroupsQueue implements Iterable {
private Node first;
private Node last;
private int n;
private static class Node {
private Item item;
private Node next;
}
public void Queue() {
first = null;
last = null;
n = 0;
}
// TODO : implement the data structure (20 points)
/**
* Initializes an empty GroupsQueue with g groups
* @return
*/
public GroupsQueue(int g) {
first = new Node<>();
last = first;
for(int i=1; i<=19; i++){
last.next = new Node<>();
last = last.next;
}
}
// TODO : implement the constructor (20 points)
/**
* Is this GroupsQueue empty?
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Returns the number of items in the GroupsQueue.
*/
public int size() {
return n; // TODO (20 points)
}
/**
* Adds the item to this GroupsQueue with group id = gId.
*/
public void add(Item item, int gId) {
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else{
oldlast.next = last;
}
n++;
}
// TODO (20 points)
/**
* Removes and returns the item with the lowest group id
*/
public Item remove() {
Node temp = first;
Node prev = first;
Item minGid;
if (! isEmpty())
{
minGid = first.item;
}
else
{
return null;
}
while(temp!= null)
{
prev = temp;
temp = temp.next;
if (temp.item == minGid)
{
minGid = (Item) temp.item;
}
}
if (minGid == first.item)
{
first = first.next;
}
else
{
prev.next = prev.next.next;
}
n--;
return minGid;
}// TODO (20 points)
/**
* Returns an iterator that iterates over the items in this GroupsQueue
* in group id order (lowest id first) and in FIFO order in each group.
*/
public Iterator iterator() {
// TODO
// BONUS (20 points)
return null;
}
}
Solution
Implementation given here seems to have many logical errors.
Here is the code given for GroupQueue:
package groupqueue;
public class GroupQueue{
/**
* n is number of queues maintained. and queues is array of all queues maintained by
GroupQueue.
* here there are n groups . so maintain n queues and each queue represent one group.
*/
public int n;
public Que.
package algs13;
import stdlib.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
/* ***********************************************************************
* Compilation: javac Queue.java
* Execution: java Queue < input.txt
* Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic queue, implemented using a linked list.
*
* % java Queue < tobe.txt
* to be or not to be (2 left on queue)
*
*************************************************************************/
/**
* The <tt>Queue</tt> class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the top item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* All queue operations except iteration are constant time.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*/
public class Queue<T> implements Iterable<T> {
private int N; // number of elements on queue
private Node<T> first; // beginning of queue
private Node<T> last; // end of queue
// helper linked list class
private static class Node<T> {
public Node() { }
public T item;
public Node<T> next;
}
/**
* Create an empty queue.
*/
public Queue() {
first = null;
last = null;
N = 0;
}
/**
* Is the queue empty?
*/
public boolean isEmpty() {
return first == null;
}
/**
* Return the number of items in the queue.
*/
public int size() {
return N;
}
/**
* Return the item least recently added to the queue.
* @throws java.util.NoSuchElementException if queue is empty.
*/
public T peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return first.item;
}
/**
* Add the item to the queue.
*/
public void enqueue(T item) {
Node<T> oldlast = last;
last = new Node<>();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
}
/**
* Remove and return the item on the queue least recently added.
* @throws java.util.NoSuchElementException if queue is empty.
*/
public T dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
T item = first.item;
first = first.next;
N--;
if (isEmpty()) last = null;
return item;
}
/**
* Return string representation.
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (T item : this)
s.append(item + " ");
return s.toString();
}
// check internal invariants
private static <T> boolean check(Queue<T> that) {
int N = that.N;
Queue.Node<T> first = that.first;
Queue.Node<T> last = that.last;
if (N == 0) {
if (first != null) return false;
if (last != null) return false;
}
else if (N == 1) {
if (f.
We're taking a closer look into a new utility class from Android Support Library. It enables you to calculate the difference between two lists and output a list of update operations swiftly and with style. Presented by Željko Plesac from Infinum.
This file contains a complete array-based MultiSet, but not the code.pdfdeepaksatrker
This file contains a complete array-based MultiSet, but not the code needed to support its
Iterator. Complete the Iterator\'s next() and hasNext() methods.
Solution
Hi, I have implemented both required methods.
Please let me know in case of any issue.
import java.util.Collection;
import java.util.Iterator;
public class ArrayMultiSet implements Collection {
/** Array in which the elements in this multiset are stored. */
private E[] _store;
/**
* Array indices below this amount contain the active elements in this collection.
*/
private int _size;
/**
* Modification counter used to preserve the fail-fast nature of its iterators.
*/
private long _modCount;
/**
* Create a new empty multiset.
*/
public ArrayMultiSet() {
_modCount = 0;
clear();
}
/**
* Remove all of the elements within the instance and invalidate any current iterators.
*/
@SuppressWarnings(\"unchecked\")
@Override
public void clear() {
_store = (E[]) (new Object[16]);
_size = 0;
// maintains the class invariant
}
/**
* Update the multiset so that it includes all of the elements from before the call AND the given
element.
*
* @param e Item to be added to this collection.
*/
@SuppressWarnings(\"unchecked\")
@Override
public boolean add(E e) {
// Check if we do not have enough space in the underlying array to store the
// new element
if (_size == _store.length) {
// We do not have space, so create a new larger space (doubling the size
// is the most time efficient)
E[] newStore = (E[]) new Object[_store.length * 2];
// Copy all of the references into the new array
for (int i = 0; i < _store.length; i++ ) {
newStore[i] = _store[i];
}
_store = newStore;
// An easier, more efficient way of coding this (but less useful for
// teaching) would instead be:
// _store = Arrays.copyOf(_store, _store.length * 2);
}
// Add the element to the store
_store[_size] = e;
// Finally, we can increase _size, since this change will no longer violate
// any class invariants.
_size += 1;
return true;
}
/**
* Return true if at least one element in the multiset is equal to the given object. When {@code
obj} is null, it must
* use the {@code ==} operator to perform these checks, but when {@code obj} is not null, the
{@link Object#equals}
* method is used.
*
* @param obj Object (or null) for which we will search
* @return {@code true} if {@code obj} was found; {@code false} if a match could not be
found.
*/
@Override
public boolean contains(Object obj) {
// Only scan through _size, since those are the only \"real\" entries for the
// multiset.
for (int i = 0; i < _size; i++ ) {
// When obj is null, we need to use ==
if ((obj == null) && (_store[i] == null)) {
return true;
}
// Otherwise, we use .equals() to find a match
else if ((obj != null) && obj.equals(_store[i])) {
return true;
}
// No else clause, since the match could be at a higher index!
}
// Checked all VALID indices, so the result must be:
return false;
}
@Override
public int size() {
return _size;
}
/**
* Remove the element found at the given index. .
this file has a complete array-based MultiSet, but not the code need.pdfflashfashioncasualwe
this file has a complete array-based MultiSet, but not the code needed to support its Iterator.
Complete the Iterator\'s next() and hasNext() methods.
Solution
Hi, I have implemented required methods.
Please let me know in case of any issue.
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ArrayMultiSet implements Collection {
/** Array in which the elements in this multiset are stored. */
private E[] _store;
/**
* Array indices below this amount contain the active elements in this collection.
*/
private int _size;
/**
* Modification counter used to preserve the fail-fast nature of its iterators.
*/
private long _modCount;
/**
* Create a new empty multiset.
*/
public ArrayMultiSet() {
_modCount = 0;
clear();
}
/**
* Remove all of the elements within the instance and invalidate any current iterators.
*/
@SuppressWarnings(\"unchecked\")
@Override
public void clear() {
_store = (E[]) (new Object[16]);
_size = 0;
// maintains the class invariant
}
/**
* Update the multiset so that it includes all of the elements from before the call AND the given
element.
*
* @param e Item to be added to this collection.
*/
@SuppressWarnings(\"unchecked\")
@Override
public boolean add(E e) {
// Check if we do not have enough space in the underlying array to store the
// new element
if (_size == _store.length) {
// We do not have space, so create a new larger space (doubling the size
// is the most time efficient)
E[] newStore = (E[]) new Object[_store.length * 2];
// Copy all of the references into the new array
for (int i = 0; i < _store.length; i++ ) {
newStore[i] = _store[i];
}
_store = newStore;
// An easier, more efficient way of coding this (but less useful for
// teaching) would instead be:
// _store = Arrays.copyOf(_store, _store.length * 2);
}
// Add the element to the store
_store[_size] = e;
// Finally, we can increase _size, since this change will no longer violate
// any class invariants.
_size += 1;
return true;
}
/**
* Return true if at least one element in the multiset is equal to the given object. When {@code
obj} is null, it must
* use the {@code ==} operator to perform these checks, but when {@code obj} is not null, the
{@link Object#equals}
* method is used.
*
* @param obj Object (or null) for which we will search
* @return {@code true} if {@code obj} was found; {@code false} if a match could not be
found.
*/
@Override
public boolean contains(Object obj) {
// Only scan through _size, since those are the only \"real\" entries for the
// multiset.
for (int i = 0; i < _size; i++ ) {
// When obj is null, we need to use ==
if ((obj == null) && (_store[i] == null)) {
return true;
}
// Otherwise, we use .equals() to find a match
else if ((obj != null) && obj.equals(_store[i])) {
return true;
}
// No else clause, since the match could be at a higher index!
}
// Checked all VALID indices, so the result must be:
return false;
}
@Override
public int size() {
return _size;
}
/**
* Remove the ele.
Refactoring, Agile Entwicklung, Continuous Integration – all diese für nachhaltigen Erfolg wichtigen Vorgehensweisen setzen Erfahrung mit Unit Testing voraus. Abseits von den üblichen "Bowling"-Beispielen möchten wir gerne einen Crashkurs inkl. Best Practices für das erfolgreiche Unit Testing durchführen. Anhand eines Beispielprojekts auf Basis des Zend Frameworks werden wir nach der Installation von PHPUnit auf allen Notebooks gemeinsam eine kleine Applikation aufbauen, die durchgehend Test-driven entwickelt wird.
Using c++Im also using a the ide editor called CodeLiteThe hea.pdffashiongallery1
Typed out please In a short and simple response comment on this persons answer for masonry
work Additives combined with concrete to achieve certain properties are called what? Name a
few that would benefit the Engineer and Customer.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Typed out please In a short and simple response comment on this persons answer for masonry
work Additives combined with concrete to achieve certain properties are called what? Name a
few that would benefit the Engineer and Customer.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Solution
The response of the person is good. He/she explained the admixtures and their applications pretty
well and also explained accelators, retarders and air entertainment in a simple straight forward
fashion.Overall i would say that the answer is satisfactory.
I will like to add \"PLASTICIZERS\" in the list of admixtures that would benefit the engineer
and customer. Plasticizers are water reducing admixtures and are added to the concrete mix for
making it more plastic without any further addition of water. In other words, they reduce the
quantity of water required to make concrete mixture of better plasticity.
PLEASE HIT LIKE BUTTON IF YOU FIND MY ANSWER SATISFACTORY.
THANK YOU..
In this lab, you will be given a simple code for a min Heap, and you.pdfcharanjit1717
In this lab, you will be given a simple code for a min Heap, and youre going to complete some of
the methods to handle some edge cases. Tasks for today: There are mainly two tasks, and the
logic of both of them is provided in their bodies: 1) Fully implement AddItem(). 2) Fully
implement HeapUp() Use the following start-up code. The main code and a demo class are
provided as .cs files. Use them to test your code. Once you complete the above two tasks, upload
the source code for your MinHeap class to Blackboard. class BinaryHeap : IEnumerable where T
: IComparable { private T[] array; private int count; // Number of elements (nodes) public
BinaryHeap(int size) { array = new T[size]; count = 0; } public T GetItem(int index) { return
array[index]; } private void SetItem(int index, T value) { while (index >= array.Length)
Grow(array.Length * 2); array[index] = value; } private void Grow(int newsize) {
Array.Resize(ref array, newsize); } // Indices of left and right children private int
LeftChildIndex(int pos) { return 2 * pos + 1; } private int RightChildIndex(int pos) { return 2 *
pos + 2; } private int GetParentIndex(int pos) => (pos - 1) / 2; private T GetRightChild(int pos)
=> array[RightChildIndex(pos)]; private T GetLeftChild(int pos) => array[LeftChildIndex(pos)];
private T GetParent(int pos) => array[GetParentIndex(pos)]; // "Has" methods to determine if the
indices exist private bool HasLeftChild(int pos) { if (LeftChildIndex(pos) < count) return true;
else return false; } private bool HasRightChild(int pos) { if (RightChildIndex(pos) < count)
return true; else return false; } private bool IsRoot(int pos) => pos == 0; // (true if element is
root) // Swap, uh, swaps two values given two indicies. This should be private but I originally
had it public for some reason. private void Swap(int position1, int position2) { T first =
array[position1]; array[position1] = array[position2]; array[position2] = first; } public void
AddItem(T value) { // This is part of la //Insert Logic // If the tree is empty, insert at the bottom
(it does that already) // if not, insert at the end, // From the end you either need to swap to the
root, and keep minheapify (Heapdown) // or, you should probably implement move up (for lab 6,
you need to implement // for that you run a while loop, check if the current position both isn't the
root, and is higher priority than a parent (in this case that probably means it's a lower value) // if
it is, swap with parent, and keep doing that until it's its in the array[count] = value; count++;
ReCalculateUp(); } private void HeapDown() { //CompareTo //this.CompareTo(value) returns <
0 if this < value //this.CompareTo(value) returns >0 if this > value int index = 0; while
(HasLeftChild(index)) { var smallerIndex = LeftChildIndex(index); if (HasRightChild(index)
&& (GetRightChild(index).CompareTo(GetLeftChild(index))<0) ) //there's a set of ( ) around the
right expression that are redundant but hopefully easier to read { smallerI.
VSEPR is easy if you follow the right steps. 1. .pdfrajat630669
VSEPR is easy if you follow the right steps. 1. Find the number of valence (outer)
electrons around the central atom (remember the charge) 2. Work out how many of these are
involved in bonding (remember you may have single or double bonds) 3. Remember the lone
pairs. 4. Work out the shape from the number of atoms bonded to the central atom and the
number of lone pairs. So for SeO2, Se is in group 6, and has 6 valence electrons. Se=O is a
double bond, so there are 2 of Se\'s electrons in a double bond There are two Se=O bonds, so 4
electrons are involved in Se=O bonds. This leaves another 2 electrons which are a lone pair. So
overall you have three groups around the central atom (2 Se=O bonds and a lone pair) so it is
trigonal planar if you drew in the lone pair. Removing the lone pair gives you a bent molecule.
For PF4+: P has 5 valence electrons, but it is a positive ion, so you knock off an electron to get 4
P-F bonds are single bonds, and there are 4 of them, which accounts for all the electrons.
Therefore PF4+ is a tetrahedral shape. Finally, ICl3: I has 7 valence electrons. I-Cl bonds are
single bonds, so the I uses one electron in each bond. Therefore 3 of the 7 electrons are involved
in I-Cl bonds, the other 4 must be in 2 lone pairs. This gives 5 electron groups around the central
ion, so the shape is trigonal bipyramid if you draw in the lone pairs (trigonal plane with 2 groups
above and below the plane. You can determine that these two groups must be the lone pairs since
they repel more than the I-Cl bonds). Removing the lone pairs gives you a trigonal planar
molecule. The number of groups around the central ion determines the shape. 2 is linear 3 is
trigonal planar
Solution
VSEPR is easy if you follow the right steps. 1. Find the number of valence (outer)
electrons around the central atom (remember the charge) 2. Work out how many of these are
involved in bonding (remember you may have single or double bonds) 3. Remember the lone
pairs. 4. Work out the shape from the number of atoms bonded to the central atom and the
number of lone pairs. So for SeO2, Se is in group 6, and has 6 valence electrons. Se=O is a
double bond, so there are 2 of Se\'s electrons in a double bond There are two Se=O bonds, so 4
electrons are involved in Se=O bonds. This leaves another 2 electrons which are a lone pair. So
overall you have three groups around the central atom (2 Se=O bonds and a lone pair) so it is
trigonal planar if you drew in the lone pair. Removing the lone pair gives you a bent molecule.
For PF4+: P has 5 valence electrons, but it is a positive ion, so you knock off an electron to get 4
P-F bonds are single bonds, and there are 4 of them, which accounts for all the electrons.
Therefore PF4+ is a tetrahedral shape. Finally, ICl3: I has 7 valence electrons. I-Cl bonds are
single bonds, so the I uses one electron in each bond. Therefore 3 of the 7 electrons are involved
in I-Cl bonds, the other 4 must be in 2 lone pairs. This gives 5 electro.
This is quite a broad question. I will try to acc.pdfrajat630669
This is quite a broad question. I will try to account all the important observations. 1.
Metal ions which do not have d-orbital electrons do not have color. (alkali, alkali-earth, Sc3+)
This is because of energy separation of s and p orbitals are not in the range of visible colors. 2.
Metal with fully-filled d orbitals do not have color. (Zn2+) This is because electrons in d-orbitals
cannot be excited to higher energy d-orbitals (all d-orbitals have the same energies, but when
influenced by other atom in complex, d-orbitals can split into different energy levels) 3. For ions
of the same metal, the ion with larger charge has a color of lower energy than the ion with
smaller charge. Example: Cr2+ (blue) and Cr3+ (green). This is because larger charge
contributes to larger split of the d-orbital. The more the orbitals split, the higher energy of light it
traps, allowing low-energy photon to enter our eyes. Note that you cannot be sure that the color
you see is a single color, not a combination of many colors. 4. For metals in the same column, a
metal ion which is below has a color of lower energy than an ion above. This can be explained
like no.3, larger ion causes more orbitals splitting. 5. Color of metal ions also depends on
\"ligands\" (complexing molecule/ion). e.g. Co2+ in water is pink [Co(H2O)6]2+, while Co2+ in
NH3 is blue [Co(NH3)4]2+. See \"spectrochemical series\" for more detail about this. 6. To find
\"exact\" color of metal ions, you need a supercomputer to do so. (I\'m not sure whether today
computer can calculate it). So, it\'s better to memorize the colors. Personally, I think you\'ll
understand about metal\'s color when you study transition metals, like Crystal Field Theory, and
Ligand Field Theory.
Solution
This is quite a broad question. I will try to account all the important observations. 1.
Metal ions which do not have d-orbital electrons do not have color. (alkali, alkali-earth, Sc3+)
This is because of energy separation of s and p orbitals are not in the range of visible colors. 2.
Metal with fully-filled d orbitals do not have color. (Zn2+) This is because electrons in d-orbitals
cannot be excited to higher energy d-orbitals (all d-orbitals have the same energies, but when
influenced by other atom in complex, d-orbitals can split into different energy levels) 3. For ions
of the same metal, the ion with larger charge has a color of lower energy than the ion with
smaller charge. Example: Cr2+ (blue) and Cr3+ (green). This is because larger charge
contributes to larger split of the d-orbital. The more the orbitals split, the higher energy of light it
traps, allowing low-energy photon to enter our eyes. Note that you cannot be sure that the color
you see is a single color, not a combination of many colors. 4. For metals in the same column, a
metal ion which is below has a color of lower energy than an ion above. This can be explained
like no.3, larger ion causes more orbitals splitting. 5. Color of metal ions also depends .
What is an example of big data either from your personal experience .pdfrajat630669
What is an example of big data either from your personal experience or outside research?
Answer:
Big Data: Big data means really a big data, it is a collection of large datasets that cannot be
processed using traditional computing techniques. Big data is not merely a data, rather it has
become a complete subject, which involves various tools, technqiues and frameworks.
Big data involves the data produced by different devices and applications. Given below are some
of the fields that come under the Big Data.
Black Box Data : It is a component of helicopter, airplanes, and jets, etc. It captures voices of the
flight crew, recordings of microphones and earphones, and the performance information of the
aircraft.
Social Media Data : Social media such as Facebook and Twitter hold information and the views
posted by millions of people across the globe.
Stock Exchange Data : The stock exchange data holds information about the ‘buy’ and ‘sell’
decisions made on a share of different companies made by the customers.
Power Grid Data : The power grid data holds information consumed by a particular node with
respect to a base station.
Transport Data : Transport data includes model, capacity, distance and availability of a vehicle.
Search Engine Data : Search engines retrieve lots of data from different databases.
How is it similar or different to the example in the case? In response to your peers’ posts, discuss
how big data in the examples provided impact an organization in terms of the advantages and
disadvantages?
Big data is really critical to our life and its emerging as one of the most important technologies in
modern world. Follow are just few benefits which are very much known to all of us:
Using the information kept in the social network like Facebook, the marketing agencies are
learning about the response for their campaigns, promotions, and other advertising mediums.
Using the information in the social media like preferences and product perception of their
consumers, product companies and retail organizations are planning their production.
Disadvantages of Big Data:
- Unknown population representation
- Issues of data quality
- Typically not very multivariate (at the person level)
- Privacy and confidentiality issues
- Difficult to assess accuracy and uncertainty
Solution
What is an example of big data either from your personal experience or outside research?
Answer:
Big Data: Big data means really a big data, it is a collection of large datasets that cannot be
processed using traditional computing techniques. Big data is not merely a data, rather it has
become a complete subject, which involves various tools, technqiues and frameworks.
Big data involves the data produced by different devices and applications. Given below are some
of the fields that come under the Big Data.
Black Box Data : It is a component of helicopter, airplanes, and jets, etc. It captures voices of the
flight crew, recordings of microphones and earphones, and the performance.
S-Se=S with 3 lone pairs on the first S, 1 lone.pdfrajat630669
S-Se=S with 3 lone pairs on the first S, 1 lone pair on the Se, and 2 lone pairs on
the second S
Solution
S-Se=S with 3 lone pairs on the first S, 1 lone pair on the Se, and 2 lone pairs on
the second S.
The sample program for above series in JAVA will be like belowimpo.pdfrajat630669
The sample program for above series in JAVA will be like below
import java.util.Scan;
public class PIVALUE {
public static void main(String[] args) {
// Scan object creation
Scan input = new Scan (System.in);
// ask user for input
System.out.println(\"Enter num.\");
double j = input.nextDouble(); // user entered value of j
double Tot = 0;
for(j=0; j<10000; j++){
if(j%2 == 0) // check remainder of `j/2` is 0
Tot += -1 / ( 2 * j - 1);
else
Tot += 1 / (2 * j - 1);
}
System.out.println(Tot);
}
}
Solution
The sample program for above series in JAVA will be like below
import java.util.Scan;
public class PIVALUE {
public static void main(String[] args) {
// Scan object creation
Scan input = new Scan (System.in);
// ask user for input
System.out.println(\"Enter num.\");
double j = input.nextDouble(); // user entered value of j
double Tot = 0;
for(j=0; j<10000; j++){
if(j%2 == 0) // check remainder of `j/2` is 0
Tot += -1 / ( 2 * j - 1);
else
Tot += 1 / (2 * j - 1);
}
System.out.println(Tot);
}
}.
D. This element can only have a -2 oxidation stat.pdfrajat630669
D. This element can only have a -2 oxidation state in covalent compounds. is false.
note: such as S can be +4 in SO2
Solution
D. This element can only have a -2 oxidation state in covalent compounds. is false.
note: such as S can be +4 in SO2.
solAn object will allocated statically when that object is needed.pdfrajat630669
sol:
An object will allocated statically when that object is needed for entire life time of that program
1)if object needs recusrion and storage of object conservly then it is stored in stack
2)f object needs dynamic storage then it should be allocated in heap
Solution
sol:
An object will allocated statically when that object is needed for entire life time of that program
1)if object needs recusrion and storage of object conservly then it is stored in stack
2)f object needs dynamic storage then it should be allocated in heap.
CO2 is non polar because C has no lone pairs, so .pdfrajat630669
CO2 is non polar because C has no lone pairs, so the structure is linear and hence
dipole cancell each other SO2 has lone pair, so the structure is bent due to the repulsion and
hence the structure has a net dipole moment, so polar.
Solution
CO2 is non polar because C has no lone pairs, so the structure is linear and hence
dipole cancell each other SO2 has lone pair, so the structure is bent due to the repulsion and
hence the structure has a net dipole moment, so polar..
As more halide ions are added, it loses its color.pdfrajat630669
As more halide ions are added, it loses its color and becomes more white due to the
ion concentration.
Solution
As more halide ions are added, it loses its color and becomes more white due to the
ion concentration..
AppointmentDemo.java
import java.util.Scanner;
/**
Demonstration of the appointment classes
*/
public class AppointmentDemo
{
public static void main(String[] args)
{
Appointment[] appointments = new Appointment[4];
appointments[0] = new Daily(\"Brush your teeth.\");
appointments[1] = new Monthly(1, \"Visit grandma.\");
appointments[2] = new Onetime(2015, 11, 1, \"Dentist appointment.\");
appointments[3] = new Onetime(2015, 10, 31, \"Trick or Treat.\");
Scanner in = new Scanner(System.in);
int year = in.nextInt();
int month = in.nextInt();
int day = in.nextInt();
for (Appointment a : appointments)
{
if (a.occursOn(year, month, day))
{
System.out.println(a);
}
}
}
}
Appointment.java
/**
A class to keep track of an appointment.
*/
public abstract class Appointment
{
private String description;
/**
Constructs an appointment without a description.
*/
public Appointment()
{
description = \"\";
}
/**
Sets the description of this appointment.
*/
public void setDescription(String description)
{
this.description = description;
}
/**
Determines if this appointment occurs on the given date.
*/
public abstract boolean occursOn(int year, int month, int day);
/**
Converts appointment to string description.
*/
public String toString()
{
return description;
}
}
Daily.java
public class Daily extends Appointment
{
public Daily (String description)
{
setDescription(description);
}
public boolean occursOn(int year, int month, int day)
{
return true;
}
}
Onetime.java
public class Onetime extends Appointment
{
private int monthApp;
private int yearApp;
private int dayApp;
public Onetime(int yearAppInput, int monthAppInput, int dayAppInput, String description)
{
yearApp = yearAppInput;
monthApp = monthAppInput;
dayApp = dayAppInput;
setDescription(description);
}
public boolean occursOn(int year, int month, int day)
{
if ((year == yearApp) && (month == monthApp) && (day == dayApp))
{
return true;
}
else
{
return false;
}
}
}
Monthly.java
public class Monthly extends Appointment
{
private int dayApp;
public Monthly (int dayAppInput, String description)
{
dayApp = dayAppInput;
setDescription(description);
}
public boolean occursOn(int year, int month, int day)
{
if (day == dayApp)
{
return true;
}
else
{
return false;
}
}
}
Solution
AppointmentDemo.java
import java.util.Scanner;
/**
Demonstration of the appointment classes
*/
public class AppointmentDemo
{
public static void main(String[] args)
{
Appointment[] appointments = new Appointment[4];
appointments[0] = new Daily(\"Brush your teeth.\");
appointments[1] = new Monthly(1, \"Visit grandma.\");
appointments[2] = new Onetime(2015, 11, 1, \"Dentist appointment.\");
appointments[3] = new Onetime(2015, 10, 31, \"Trick or Treat.\");
Scanner in = new Scanner(System.in);
int year = in.nextInt();
int month = in.nextInt();
int day = in.nextInt();
for (Appointment a : appointments)
{
if (a.occursOn(year, month, day))
{
System.out.println(a);
}
}
}
}
Appointment.java
/**
A class to keep track of an appointment.
*/
public ab.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
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.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
PriorityQueue.cs Jim Mischel using System; using Sy.pdf
1. // PriorityQueue.cs
//
// Jim Mischel
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Mischel.Collections
{
[Serializable]
[ComVisible(false)]
public struct PriorityQueueItem
{
private TValue _value;
public TValue Value
{
get { return _value; }
}
private TPriority _priority;
public TPriority Priority
{
get { return _priority; }
}
internal PriorityQueueItem(TValue val, TPriority pri)
{
this._value = val;
this._priority = pri;
}
}
[Serializable]
[ComVisible(false)]
public class PriorityQueue : ICollection,
IEnumerable>
{
private PriorityQueueItem[] items;
2. private const Int32 DefaultCapacity = 16;
private Int32 capacity;
private Int32 numItems;
private Comparison compareFunc;
///
/// Initializes a new instance of the PriorityQueue class that is empty,
/// has the default initial capacity, and uses the default IComparer.
///
public PriorityQueue()
: this(DefaultCapacity, Comparer.Default)
{
}
public PriorityQueue(Int32 initialCapacity)
: this(initialCapacity, Comparer.Default)
{
}
public PriorityQueue(IComparer comparer)
: this(DefaultCapacity, comparer)
{
}
public PriorityQueue(int initialCapacity, IComparer comparer)
{
Init(initialCapacity, new Comparison(comparer.Compare));
}
public PriorityQueue(Comparison comparison)
: this(DefaultCapacity, comparison)
{
}
public PriorityQueue(int initialCapacity, Comparison comparison)
{
Init(initialCapacity, comparison);
}
private void Init(int initialCapacity, Comparison comparison)
{
numItems = 0;
compareFunc = comparison;
3. SetCapacity(initialCapacity);
}
public int Count
{
get { return numItems; }
}
public int Capacity
{
get { return items.Length; }
set { SetCapacity(value); }
}
private void SetCapacity(int newCapacity)
{
int newCap = newCapacity;
if (newCap < DefaultCapacity)
newCap = DefaultCapacity;
// throw exception if newCapacity < NumItems
if (newCap < numItems)
throw new ArgumentOutOfRangeException("newCapacity", "New capacity is less
than Count");
this.capacity = newCap;
if (items == null)
{
items = new PriorityQueueItem[newCap];
return;
}
// Resize the array.
Array.Resize>(ref items, newCap);
}
public void Enqueue(PriorityQueueItem newItem)
{
if (numItems == capacity)
{
// need to increase capacity
// grow by 50 percent
SetCapacity((3 * Capacity) / 2);
4. }
int i = numItems;
++numItems;
while ((i > 0) && (compareFunc(items[(i - 1) / 2].Priority, newItem.Priority) < 0))
{
items[i] = items[(i - 1) / 2];
i = (i - 1) / 2;
}
items[i] = newItem;
//if (!VerifyQueue())
//{
// Console.WriteLine("ERROR: Queue out of order!");
//}
}
public void Enqueue(TValue value, TPriority priority)
{
Enqueue(new PriorityQueueItem(value, priority));
}
private PriorityQueueItem RemoveAt(Int32 index)
{
PriorityQueueItem o = items[index];
--numItems;
// move the last item to fill the hole
PriorityQueueItem tmp = items[numItems];
// If you forget to clear this, you have a potential memory leak.
items[numItems] = default(PriorityQueueItem);
if (numItems > 0 && index != numItems)
{
// If the new item is greater than its parent, bubble up.
int i = index;
int parent = (i - 1) / 2;
while (compareFunc(tmp.Priority, items[parent].Priority) > 0)
{
items[i] = items[parent];
i = parent;
parent = (i - 1) / 2;
5. }
// if i == index, then we didn't move the item up
if (i == index)
{
// bubble down ...
while (i < (numItems) / 2)
{
int j = (2 * i) + 1;
if ((j < numItems - 1) && (compareFunc(items[j].Priority, items[j + 1].Priority) < 0))
{
++j;
}
if (compareFunc(items[j].Priority, tmp.Priority) <= 0)
{
break;
}
items[i] = items[j];
i = j;
}
}
// Be sure to store the item in its place.
items[i] = tmp;
}
//if (!VerifyQueue())
//{
// Console.WriteLine("ERROR: Queue out of order!");
//}
return o;
}
// Function to check that the queue is coherent.
public bool VerifyQueue()
{
int i = 0;
while (i < numItems / 2)
{
int leftChild = (2 * i) + 1;
6. int rightChild = leftChild + 1;
if (compareFunc(items[i].Priority, items[leftChild].Priority) < 0)
{
return false;
}
if (rightChild < numItems && compareFunc(items[i].Priority, items[rightChild].Priority) < 0)
{
return false;
}
++i;
}
return true;
}
public PriorityQueueItem Dequeue()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return RemoveAt(0);
}
///
/// Removes the item with the specified value from the queue.
/// The passed equality comparison is used.
///
/// The item to be removed.
/// An object that implements the IEqualityComparer interface
/// for the type of item in the collection.
public void Remove(TValue item, IEqualityComparer comparer)
{
// need to find the PriorityQueueItem that has the Data value of o
for (int index = 0; index < numItems; ++index)
{
if (comparer.Equals(item, items[index].Value))
{
RemoveAt(index);
return;
}
7. }
throw new ApplicationException("The specified itemm is not in the queue.");
}
///
/// Removes the item with the specified value from the queue.
/// The default type comparison function is used.
///
/// The item to be removed.
public void Remove(TValue item)
{
Remove(item, EqualityComparer.Default);
}
public PriorityQueueItem Peek()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return items[0];
}
// Clear
public void Clear()
{
for (int i = 0; i < numItems; ++i)
{
items[i] = default(PriorityQueueItem);
}
numItems = 0;
TrimExcess();
}
///
/// Set the capacity to the actual number of items, if the current
/// number of items is less than 90 percent of the current capacity.
///
public void TrimExcess()
{
if (numItems < (float)0.9 * capacity)
{
8. SetCapacity(numItems);
}
}
// Contains
public bool Contains(TValue o)
{
foreach (PriorityQueueItem x in items)
{
if (x.Value.Equals(o))
return true;
}
return false;
}
public void CopyTo(PriorityQueueItem[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
if (array.Rank > 1)
throw new ArgumentException("array is multidimensional.");
if (numItems == 0)
return;
if (arrayIndex >= array.Length)
throw new ArgumentException("arrayIndex is equal to or greater than the length of the
array.");
if (numItems > (array.Length - arrayIndex))
throw new ArgumentException("The number of elements in the source ICollection is greater
than the available space from arrayIndex to the end of the destination array.");
for (int i = 0; i < numItems; i++)
{
array[arrayIndex + i] = items[i];
}
}
#region ICollection Members
public void CopyTo(Array array, int index)
9. {
this.CopyTo((PriorityQueueItem[])array, index);
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { return items.SyncRoot; }
}
#endregion
#region IEnumerable> Members
public IEnumerator> GetEnumerator()
{
for (int i = 0; i < numItems; i++)
{
yield return items[i];
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
Solution
// PriorityQueue.cs
//
// Jim Mischel
using System;
10. using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Mischel.Collections
{
[Serializable]
[ComVisible(false)]
public struct PriorityQueueItem
{
private TValue _value;
public TValue Value
{
get { return _value; }
}
private TPriority _priority;
public TPriority Priority
{
get { return _priority; }
}
internal PriorityQueueItem(TValue val, TPriority pri)
{
this._value = val;
this._priority = pri;
}
}
[Serializable]
[ComVisible(false)]
public class PriorityQueue : ICollection,
IEnumerable>
{
private PriorityQueueItem[] items;
private const Int32 DefaultCapacity = 16;
private Int32 capacity;
private Int32 numItems;
private Comparison compareFunc;
///
11. /// Initializes a new instance of the PriorityQueue class that is empty,
/// has the default initial capacity, and uses the default IComparer.
///
public PriorityQueue()
: this(DefaultCapacity, Comparer.Default)
{
}
public PriorityQueue(Int32 initialCapacity)
: this(initialCapacity, Comparer.Default)
{
}
public PriorityQueue(IComparer comparer)
: this(DefaultCapacity, comparer)
{
}
public PriorityQueue(int initialCapacity, IComparer comparer)
{
Init(initialCapacity, new Comparison(comparer.Compare));
}
public PriorityQueue(Comparison comparison)
: this(DefaultCapacity, comparison)
{
}
public PriorityQueue(int initialCapacity, Comparison comparison)
{
Init(initialCapacity, comparison);
}
private void Init(int initialCapacity, Comparison comparison)
{
numItems = 0;
compareFunc = comparison;
SetCapacity(initialCapacity);
}
public int Count
{
get { return numItems; }
12. }
public int Capacity
{
get { return items.Length; }
set { SetCapacity(value); }
}
private void SetCapacity(int newCapacity)
{
int newCap = newCapacity;
if (newCap < DefaultCapacity)
newCap = DefaultCapacity;
// throw exception if newCapacity < NumItems
if (newCap < numItems)
throw new ArgumentOutOfRangeException("newCapacity", "New capacity is less
than Count");
this.capacity = newCap;
if (items == null)
{
items = new PriorityQueueItem[newCap];
return;
}
// Resize the array.
Array.Resize>(ref items, newCap);
}
public void Enqueue(PriorityQueueItem newItem)
{
if (numItems == capacity)
{
// need to increase capacity
// grow by 50 percent
SetCapacity((3 * Capacity) / 2);
}
int i = numItems;
++numItems;
while ((i > 0) && (compareFunc(items[(i - 1) / 2].Priority, newItem.Priority) < 0))
{
13. items[i] = items[(i - 1) / 2];
i = (i - 1) / 2;
}
items[i] = newItem;
//if (!VerifyQueue())
//{
// Console.WriteLine("ERROR: Queue out of order!");
//}
}
public void Enqueue(TValue value, TPriority priority)
{
Enqueue(new PriorityQueueItem(value, priority));
}
private PriorityQueueItem RemoveAt(Int32 index)
{
PriorityQueueItem o = items[index];
--numItems;
// move the last item to fill the hole
PriorityQueueItem tmp = items[numItems];
// If you forget to clear this, you have a potential memory leak.
items[numItems] = default(PriorityQueueItem);
if (numItems > 0 && index != numItems)
{
// If the new item is greater than its parent, bubble up.
int i = index;
int parent = (i - 1) / 2;
while (compareFunc(tmp.Priority, items[parent].Priority) > 0)
{
items[i] = items[parent];
i = parent;
parent = (i - 1) / 2;
}
// if i == index, then we didn't move the item up
if (i == index)
{
// bubble down ...
14. while (i < (numItems) / 2)
{
int j = (2 * i) + 1;
if ((j < numItems - 1) && (compareFunc(items[j].Priority, items[j + 1].Priority) < 0))
{
++j;
}
if (compareFunc(items[j].Priority, tmp.Priority) <= 0)
{
break;
}
items[i] = items[j];
i = j;
}
}
// Be sure to store the item in its place.
items[i] = tmp;
}
//if (!VerifyQueue())
//{
// Console.WriteLine("ERROR: Queue out of order!");
//}
return o;
}
// Function to check that the queue is coherent.
public bool VerifyQueue()
{
int i = 0;
while (i < numItems / 2)
{
int leftChild = (2 * i) + 1;
int rightChild = leftChild + 1;
if (compareFunc(items[i].Priority, items[leftChild].Priority) < 0)
{
return false;
}
15. if (rightChild < numItems && compareFunc(items[i].Priority, items[rightChild].Priority) < 0)
{
return false;
}
++i;
}
return true;
}
public PriorityQueueItem Dequeue()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return RemoveAt(0);
}
///
/// Removes the item with the specified value from the queue.
/// The passed equality comparison is used.
///
/// The item to be removed.
/// An object that implements the IEqualityComparer interface
/// for the type of item in the collection.
public void Remove(TValue item, IEqualityComparer comparer)
{
// need to find the PriorityQueueItem that has the Data value of o
for (int index = 0; index < numItems; ++index)
{
if (comparer.Equals(item, items[index].Value))
{
RemoveAt(index);
return;
}
}
throw new ApplicationException("The specified itemm is not in the queue.");
}
///
/// Removes the item with the specified value from the queue.
16. /// The default type comparison function is used.
///
/// The item to be removed.
public void Remove(TValue item)
{
Remove(item, EqualityComparer.Default);
}
public PriorityQueueItem Peek()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return items[0];
}
// Clear
public void Clear()
{
for (int i = 0; i < numItems; ++i)
{
items[i] = default(PriorityQueueItem);
}
numItems = 0;
TrimExcess();
}
///
/// Set the capacity to the actual number of items, if the current
/// number of items is less than 90 percent of the current capacity.
///
public void TrimExcess()
{
if (numItems < (float)0.9 * capacity)
{
SetCapacity(numItems);
}
}
// Contains
public bool Contains(TValue o)
17. {
foreach (PriorityQueueItem x in items)
{
if (x.Value.Equals(o))
return true;
}
return false;
}
public void CopyTo(PriorityQueueItem[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
if (array.Rank > 1)
throw new ArgumentException("array is multidimensional.");
if (numItems == 0)
return;
if (arrayIndex >= array.Length)
throw new ArgumentException("arrayIndex is equal to or greater than the length of the
array.");
if (numItems > (array.Length - arrayIndex))
throw new ArgumentException("The number of elements in the source ICollection is greater
than the available space from arrayIndex to the end of the destination array.");
for (int i = 0; i < numItems; i++)
{
array[arrayIndex + i] = items[i];
}
}
#region ICollection Members
public void CopyTo(Array array, int index)
{
this.CopyTo((PriorityQueueItem[])array, index);
}
public bool IsSynchronized
{
18. get { return false; }
}
public object SyncRoot
{
get { return items.SyncRoot; }
}
#endregion
#region IEnumerable> Members
public IEnumerator> GetEnumerator()
{
for (int i = 0; i < numItems; i++)
{
yield return items[i];
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}