This document provides information about stacks, queues, and hashing. It describes stacks as data structures where the last item inserted is the first item accessed. Common stack operations like push(), pop(), and peek() are discussed. Array and linked list implementations of stacks are presented. Examples of stack applications in compiler design, expression evaluation, and spell checking are given. Queues are defined as structures where the first item inserted is the first item accessed (FIFO). Circular queue implementations are described to avoid overflow issues. Deques, which allow insertion and removal from both ends, are also introduced. Implementation of queues using arrays is demonstrated with methods like enqueue(), dequeue(), and isEmpty().
Download for better quality.
Monads do not Compose. Not in a generic way - There is no general way of composing monads.
A comment from Rúnar Bjarnason, coauthor of FP in Scala: "They do compose in a different generic way. For any two monads F and G we can take the coproduct which is roughly Free of Either F or G (up to normalization)".
Another comment from Sergei Winitzki (which caused me to upload https://www.slideshare.net/pjschwarz/addendum-to-monads-do-not-compose): "It is a mistake to think that a traversable monad can be composed with another monad. It is true that, given `Traversable`, you can implement the monad's methods (pure and flatMap) for the composition with another monad (as in your slides 21 to 26), but this is a deceptive appearance. The laws of the `Traversable` typeclass are far insufficient to guarantee the laws of the resulting composed monad. The only traversable monads that work correctly are Option, Either, and Writer. It is true that you can implement the type signature of the `swap` function for any `Traversable` monad. However, the `swap` function for monads needs to satisfy very different and stronger laws than the `sequence` function from the `Traversable` type class. I'll have to look at the "Book of Monads"; but, if my memory serves, the FPiS book does not derive any of these laws." See https://www.linkedin.com/feed/update/urn:li:groupPost:41001-6523141414614814720?commentUrn=urn%3Ali%3Acomment%3A%28groupPost%3A41001-6523141414614814720%2C6532108273053761536%29
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
Quicksort - a whistle-stop tour of the algorithm in five languages and four paradigms.
Programming Paradigms: Functional, Logic, Imperative, Imperative Functional
Languages: Haskell, Scala, Java, Clojure, Prolog
Download for better quality.
Monads do not Compose. Not in a generic way - There is no general way of composing monads.
A comment from Rúnar Bjarnason, coauthor of FP in Scala: "They do compose in a different generic way. For any two monads F and G we can take the coproduct which is roughly Free of Either F or G (up to normalization)".
Another comment from Sergei Winitzki (which caused me to upload https://www.slideshare.net/pjschwarz/addendum-to-monads-do-not-compose): "It is a mistake to think that a traversable monad can be composed with another monad. It is true that, given `Traversable`, you can implement the monad's methods (pure and flatMap) for the composition with another monad (as in your slides 21 to 26), but this is a deceptive appearance. The laws of the `Traversable` typeclass are far insufficient to guarantee the laws of the resulting composed monad. The only traversable monads that work correctly are Option, Either, and Writer. It is true that you can implement the type signature of the `swap` function for any `Traversable` monad. However, the `swap` function for monads needs to satisfy very different and stronger laws than the `sequence` function from the `Traversable` type class. I'll have to look at the "Book of Monads"; but, if my memory serves, the FPiS book does not derive any of these laws." See https://www.linkedin.com/feed/update/urn:li:groupPost:41001-6523141414614814720?commentUrn=urn%3Ali%3Acomment%3A%28groupPost%3A41001-6523141414614814720%2C6532108273053761536%29
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
Quicksort - a whistle-stop tour of the algorithm in five languages and four paradigms.
Programming Paradigms: Functional, Logic, Imperative, Imperative Functional
Languages: Haskell, Scala, Java, Clojure, Prolog
Java collection classes and their usage.how to use java collections in a program and different types of collections. difference between the map list set, volatile keyword.
Platone nella rete: cura dei contenuti e apprendimentoGianfranco Marini
cura dei contenuti e apprendimento nell'era del sovraccarico informativo e cognitivo. Teoria, risorse, applicazioni educative per la cura dei contenuti vista come: ermeneutica del web, strumento per l'aggiornamento e competenza di base nella comunicazione digitale
Trattazione sul tema dello storytelling e delle sue valenze creative e manipolatorie. Tavola periodica dello storytelling, viaggio dell'eroe, regole per una buona storia, Platone e la condanna dei poeti e della poesia, narrazione digitale (e non) nella didattica, valutazione e rubriche di valutazione.
Realizzata da Gianfranco Marini per il festival della didattica digitale di Lucca, 2017
Data structuresUsing java language and develop a prot.pdfarmyshoes
Data structures:
****Using java language and develop a prototype for a demo program that reads in strings that
look like:
Using the infix to postfix code below:
A = 3; // your code should store A and 3 as a key-value pair
B = 4; // your code should store B and 4 as a key-value pair
A; // your code should now look-up A and then display its value
later we (you) will add the ability to write
Y = A * B + 3;
Y; // your code should show 16
Using this code
// infix.java
// converts infix arithmetic expressions to postfix
// to run this program: C>java InfixApp
import java.io.*; // for I/O
////////////////////////////////////////////////////////////////
class StackX {
private int maxSize;
private char[] stackArray;
private int top;
// --------------------------------------------------------------
public StackX(int s) // constructor
{
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}
// --------------------------------------------------------------
public void push(char j) // put item on top of stack
{
stackArray[++top] = j;
}
// --------------------------------------------------------------
public char pop() // take item from top of stack
{
return stackArray[top--];
}
// --------------------------------------------------------------
public char peek() // peek at top of stack
{
return stackArray[top];
}
// --------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return (top == -1);
}
// -------------------------------------------------------------
public int size() // return size
{
return top + 1;
}
// --------------------------------------------------------------
public char peekN(int n) // return item at index n
{
return stackArray[n];
}
// --------------------------------------------------------------
public void displayStack(String s) {
System.out.print(s);
System.out.print(\"Stack (bottom-->top): \");
for (int j = 0; j < size(); j++) {
System.out.print(peekN(j));
System.out.print(\' \');
}
System.out.println(\" \");
}
// --------------------------------------------------------------
} // end class StackX
////////////////////////////////////////////////////////////////
class InToPost // infix to postfix conversion
{
private StackX theStack;
private String input;
private String output = \"\";
// --------------------------------------------------------------
public InToPost(String in) // constructor
{
input = in;
int stackSize = input.length();
theStack = new StackX(stackSize);
}
// --------------------------------------------------------------
public String doTrans() // do translation to postfix
{
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
theStack.displayStack(\"For \" + ch + \" \"); // *diagnostic*
switch (ch) {
case \'+\': // it’s + or -
case \'-\':
gotOper(ch, 1); // go pop operators
break; // (precedence 1)
case \'*\': // it’s * or /
case \'/\':
gotOper(ch, 2); // go pop operators
break; // (precedence 2)
case \'(\': // it’s a left paren
theStack.push(.
6Modify the bfs.java program (Listing A) to find the minimu.docxevonnehoggarth79783
6
Modify the bfs.java program (Listing A) to find the minimum spanning tree using a breadth-first search, rather than the depth-first search shown in
mst.java (Listing B). In main(), create a graph with 9 vertices and 12 edges,
and find its minimum spanning tree.
Listing A: The bfs.java Program
// bfs.java
// demonstrates breadth-first search
// to run this program: C>java BFSApp
////////////////////////////////////////////////////////////////
class Queue
{
private final int SIZE = 20;
private int[] queArray;
private int front;
private int rear;
// -------------------------------------------------------------
public Queue() // constructor
{
queArray = new int[SIZE];
front = 0;
rear = -1;
}
// -------------------------------------------------------------
public void insert(int j) // put item at rear of queue
{
if(rear == SIZE-1)
rear = -1;
queArray[++rear] = j;
}
// -------------------------------------------------------------
public int remove() // take item from front of queue
{
int temp = queArray[front++];
if(front == SIZE)
front = 0;
return temp;
}
// -------------------------------------------------------------
public boolean isEmpty() // true if queue is empty
{
return ( rear+1==front || (front+SIZE-1==rear) );
}
// -------------------------------------------------------------
} // end class Queue
////////////////////////////////////////////////////////////////
class Vertex
{
public char label; // label (e.g. ‘A’)
public boolean wasVisited;
// -------------------------------------------------------------
public Vertex(char lab) // constructor
{
label = lab;
wasVisited = false;
}
// -------------------------------------------------------------
} // end class Vertex
////////////////////////////////////////////////////////////////
class Graph
{
private final int MAX_VERTS = 20;
private Vertex vertexList[]; // list of vertices
private int adjMat[][]; // adjacency matrix
private int nVerts; // current number of vertices
private Queue theQueue;
// ------------------
public Graph() // constructor
{
vertexList = new Vertex[MAX_VERTS];
// adjacency matrix
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int j=0; j<MAX_VERTS; j++) // set adjacency
for(int k=0; k<MAX_VERTS; k++) // matrix to 0
adjMat[j][k] = 0;
theQueue = new Queue();
} // end constructor
// -------------------------------------------------------------
public void addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}
// -------------------------------------------------------------
public void addEdge(int start, int end)
{
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}
// -------------------------------------------------------------
public void displayVertex(int v)
{
System.out.print(vertexList[v].label);
}
// -------------------------------------------------------------
public void bfs() // breadth-first search
{ // begin at vertex 0
vertexList[0].wasVisited = true; // mark it
displayVertex(0); // display it
theQueue.insert(0); // insert at tail
int v2;.
For each task, submit your source java code file.(1) Objective Im.pdfdhavalbl38
For each task, submit your source java code file.
(1) Objective: Implement Link List
Write a class that maintains the scores for a game application. Implement the addition and
removal function to update the database. The gamescore.txt contains player’ name and score data
record fields separated by comma. For Removal function, uses the name field to select record to
remove the game score record.
Download – List.java, LList.java, Dlink.java, GameEntry.java, gamescore.txt
(a)Read gamescore.txt to initialize the Linked list in sorted order. (1 point)
(b)Provide Remove and Add function for user to update the sorted linked list. (1 point)
(2)Add a reverse function to the LList.java class to reverse the order of the linked list. (2 points).
---------------------------------------------------------------------------------------------------------------------
-----------------------------------------
//gamescore.txt
Mike,1105
Rob,750
Paul,720
Anna,660
Rose,590
Jack,510
--------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------
//DLink.java
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** Doubly linked list node */
class DLink {
private E element; // Value for this node
private DLink next; // Pointer to next node in list
private DLink prev; // Pointer to previous node
/** Constructors */
DLink(E it, DLink p, DLink n)
{ element = it; prev = p; next = n; }
DLink(DLink p, DLink n) { prev = p; next = n; }
/** Get and set methods for the data members */
DLink next() { return next; }
DLink setNext(DLink nextval)
{ return next = nextval; }
DLink prev() { return prev; }
DLink setPrev(DLink prevval)
{ return prev = prevval; }
E element() { return element; }
E setElement(E it) { return element = it; }
}
--------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------
//GameEntry.java
public class GameEntry {
protected String name;
protected int score;
public GameEntry(String n, int s) {
name = n;
score = s;
}
public String getName() {return name;}
public int getScore() {return score;}
public String toString() {
return \"(\"+name+\",\"+score+\")\";
}
}
--------------------------------------------------------------------------------------------------------------------
----------------------------------
//List.java
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** List ADT */
public interface List {
/** Remove all contents from the list, so it is once again
empty. Client is responsible for reclaiming storage
used by the list elements. */
p.
Write a program that converts an infix expression into an equivalent.pdfmohdjakirfb
Write a program that converts an infix expression into an equivalent postfix expression. The
rules to convert an infix expression into an equivalent postfix expression are as follows (C++):
Initialize pfx to an empty expression and also initialize the stack.
Get the next symbol, sym, from infx.
If sym is an operand, append sym to pfx.
If sym is (, push sym into the stack.
If sym is ), pop and append all of the symbols from the stack until the most recent left
parentheses. Pop and discard the left parentheses.
If sym is an operator:
Pop and append all of the operators from the stack to pfx that are above the most recent left
parentheses and have precedence greater than or equal to sym.
Push sym onto the stack.
After processing infx, some operators might be left in the stack. Pop and append to pfx
everything from the stack.
In this program, you will consider the following (binary) arithmetic operators: +, -, *, and /.
You may assume that the expressions you will process are error free. Design a class that stores
the infix and postfix strings. The class must include the following operations:
getInfix: Stores the infix expression.
showInfix: Outputs the infix expression.
showPostfix: Outputs the postfix expression.
convertToPostfix: Converts the infix expression into a postfix expression. The resulting postfix
expression is stored in pfx.
precedence: Determines the precedence between two operators. If the first operator is of higher
or equal precedence than the second operator, it returns the value true; otherwise, it returns the
value false.
A + B - C;
(A + B ) * C;
(A + B) * (C - D);
A + ((B + C) * (E - F) - G) / (H - I);
A + B * (C + D ) - E / F * G + H;
Infix Expression: A+B-C;
Postfix Expression: AB+C-
Infix Expression: (A+B)*C;
Postfix Expression: AB+C*
Infix Expression: (A+B)*(C-D);
Postfix Expression: AB+CD-*
Infix Expression: A+((B+C)*(E-F)-G)/(H-I);
Postfix Expression: ABC+EF-*G-HI-/+
Infix Expression: A+B*(C+D)-E/F*G+H;
Postfix Expression: ABCD+*+EF/G*-H+
Turn in:
A UML diagram for your class.
The header file for your class.
The implementation file for your class.
The source code for your test program. (C++)
(Below already done code.)
//Header file: myStack.h
#ifndef H_StackType
#define H_StackType
#include
#include
#include \"stackADT.h\"
using namespace std;
template
class stackType: public stackADT
{
public:
const stackType& operator=(const stackType&);
//Overload the assignment operator.
void initializeStack();
//Function to initialize the stack to an empty state.
//Postcondition: stackTop = 0
bool isEmptyStack() const;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty,
// otherwise returns false.
bool isFullStack() const;
//Function to determine whether the stack is full.
//Postcondition: Returns true if the stack is full,
// otherwise returns false.
void push(const Type& newItem);
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postc.
/**
* @author Derek Harter
* @cwid 123 45 678
* @class
* @ide Visual Studio Community 2017
* @date
* @assg C++ Stacks videos
*
* @description A Stack ADT with two concrete impelementation
* examples: an array based stack implementaiton (AStack), and
* a linked list based implementation (LStack).
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//-------------------------------------------------------------------------
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*/
virtual int size() const = 0;
/** tostring
* Represent stack as a string
*/
virtual string tostring() const = 0;
// operload operators, mostly to support boolean comparison between
// two stacks for testing
bool operator==(const Stack<T>& rhs) const;
virtual const T& operator[](int index) const = 0;
// overload output stream operator for all stacks using tostring()
template <typename U>
friend ostream& operator<<(ostream& out, const Stack<U>& aStack);
};
/** Stack equivalence
* Compare two given stacks to determine if they are equal or not.
* stacks are equal if they are both of the same size, and each corresponding
* item on each stack is equal at the same position on the stack.
* This function relies on overloaded operator[] to access items on stack
* by index for the comparis.
Frequency .java Word frequency counter package frequ.pdfarshiartpalace
Frequency .java
/**
* Word frequency counter
*/
package frequency;
import java.util.Iterator;
/**
*
* @author UMD CS
*/
public class Frequency implements Iterable{
private Node first;
private int N;
Frequency(){
N = 0;
first = null;
}
@Override
public Iterator iterator() {
return new ListIterator();
}
/**
*
* List iterator
*
*/
private class ListIterator implements Iterator{
private Node current;
private int index ;
ListIterator(){
current = first;
index = 0;
}
@Override
public boolean hasNext() {
return current != null;
}
public String next() {
if(!hasNext()){
return null;
}
String word = current.key;
int count = current.count;
String r = \"(\"+word + \",\" + Integer.toString(count)+\")\";
current = current.next;
return r;
}
@Override
public void remove() {
}
}
/**
*
* Node class
*
*/
private class Node {
private String key;
private int count;
private Node next;
Node(String item){
key = item;
count = 1;
next = null;
}
@Override
public String toString(){
return \"(\"+key +\",\"+count+\")\";
}
}
/*
* Inserts a word into the linked list. If the word exists, increment the
* count by q.
*/
public void insert(String word){
if(word.equals(\"\")){
return;
}
//TODO
/*
* implement here
*/
}
/**
*
* @param str input string
* This method splits a string into words and pass the words to insert method
*
*/
public void insertWords(String str){
String delims = \"[ .,?!\'\\\"()}{;/<>&=#-:\\\\ _]+\";
String[] words = str.split(delims);
for(String s: words){
s = s.toLowerCase();
insert(s);
}
}
/**
* prints the word frequency list
*/
public void print(){
Node c = first;
while(c != null){
System.out.print(\"(\"+c.key + \",\" + c.count+\")\");
c = c.next;
}
System.out.print(\"\ \");
}
}
--------------------------------------------------------------------------------------------------------------------
------------------------------------------------------
WordFrequency.java
package frequency;
import utils.In;
import utils.Stopwatch;
/**
*
* @author UMD CS
*/
public class WordFrequency {
/**
* @param input source
* @param
* This method receives input resource and return the word frequency string
* DO NOT CHANGE THIS METHOD.
*/
public static String freq(String inputSource, int maxLines){
In in;
// Frequency class can only count the frequency of strings. DO NOT CHANGE THIS.
Frequency freq = new Frequency();
int MAX = 100;
String inputSourceName = inputSource;
try {
in = new In(inputSourceName);
while (!in.isEmpty()) {
String s = in.readLine();
//System.out.println(s);
freq.insertWords(s);
}
}
catch (Exception e) {
e.printStackTrace();
}
StringBuilder strFrequency = new StringBuilder();
int cnt = 0;
for(String s: freq){
strFrequency.append(s);
strFrequency.append(\",\");
cnt++;
if(cnt >= maxLines){break;}
}
return strFrequency.toString();
}
/**
*
*/
public static void main(String[] args) {
In in;
Frequency freq = new Frequency();
int MAX = 100;
// String inputSourceName =
\"http://www.cs.umd.edu/class/summer2015/cmsc132/projects/P3_WordFrequency/test1.html\";
String .
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
StackInterface
/**
An interface for the ADT stack.
Do not modify this file
*/
package PJ2;
public interface StackInterface
{
/** Gets the current number of data in this stack.
@return the integer number of entries currently in the stack*/
public int size();
/** Adds a new data to the top of this stack.
@param aData an object to be added to the stack */
public void push(T aData);
/** Removes and returns this stack\'s top data.
@return either the object at the top of the stack or,
if the stack is empty before the operation, null */
public T pop();
/** Retrieves this stack\'s top data.
@return either the data at the top of the stack or
null if the stack is empty */
public T peek();
/** Detects whether this stack is empty.
@return true if the stack is empty */
public boolean empty();
/** Removes all data from this stack */
public void clear();
} // end StackInterface
SimpleLinkedStack.java
/**
A class of stacks whose entries are stored in a chain of nodes.
Implement all methods in SimpleLinkedStack class using
the inner Node class.
Main Reference : text book or class notes
Do not change or add data fields
Do not add new methods
You may access Node object fields directly, i.e. data and next
*/
package PJ2;
public class SimpleLinkedStack implements StackInterface
{
// Data fields
private Node topNode; // references the first node in the chain
private int count; // number of data in this stack
public SimpleLinkedStack()
{
// add stataments
} // end default constructor
public void push(T newData)
{
// add stataments
} // end push
public T peek()
{
// add stataments
return null;
} // end peek
public T pop()
{
// add stataments
return null;
} // end pop
public boolean empty()
{
// add stataments
return false;
} // end empty
public int size()
{
// add stataments
return -1;
} // end isEmpty
public void clear()
{
// add stataments
} // end clear
public String toString()
{
// add stataments
// note: data class in stack must implement toString() method
// return a list of data in Stack, separate them with \',\'
return \"\";
}
/****************************************************
private inner node class
Do not modify this class!!
you may access data and next directly
***************************************************/
private class Node
{
private T data; // entry in list
private Node next; // link to next node
private Node (T dataPortion)
{
data = dataPortion;
next = null; // set next to NULL
} // end constructor
private Node (T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode; // set next to refer to nextNode
} // end constructor
} // end Node
/****************************************************
Do not modify: Stack test
****************************************************/
public static void main (String args[])
{
System.out.println(\"\ \"+
\"*******************************************************\ \"+
\"Sample Expected output:\ \"+
\"\ \"+
\"OK: stack is empty\ \"+
\"Push 3 data: 10, 30, 50\ \"+
\"Print stack [50,30,10,]\ \"+
\"OK: sta.
Implementing Software Machines in Go and CEleanor McHugh
Early draft of a tutorial on techniques for implementing virtual machines and language interpreters. Contains example programs for functional stacks and despatch loops.
2Part I1. Answer questions for the following graph, if .docxgilbertkpeters11344
2
Part I:
1. Answer questions for the following graph, if a new vertex is visited and there is more than one possibility to select, following the alphabet order. (
B
A
D
C
E
H
G
F
I
J
K
)
a. Depth-first traversal starting at vertex A.
b. Depth-first traversal starting at vertex F.
c. Breadth-first traversal starting at vertex A.
d. Breadth-first traversal starting at vertex F.
e. Shortest path from vertex A to vertex E using breadth-first search.
f. Shortest path from vertex G to vertex C using breadth-first search.
g. Shortest path from vertex F to vertex A using breadth-first search.
2. Answer questions for the following graph. For the same edge length, you could order the edges using the alphabet order. (For example, for length 2, the order is AB, AE, CD, CE)
(
B
A
D
C
E
H
G
F
I
3
2
5
3
2
4
1
7
5
2
2
1
3
6
1
)
a. Construct the minimal spanning tree using Kruskal's Algorithm
b. Construct the minimal spanning tree using Prim's Algorithm, using A as the root.
c. Construct the shortest path using Dijkstra's Algorithm, using A as the source node. Using a table to describe the status of each step
Part II: programming exercise
Modify the bfs.java program (Listing A) to find the minimum spanning tree using a breadth-first search, rather than the depth-first search shown in
mst.java (Listing B). In main(), create a graph with 9 vertices and 12 edges,
and find its minimum spanning tree.
Listing A: The bfs.java Program
// bfs.java
// demonstrates breadth-first search
// to run this program: C>java BFSApp
////////////////////////////////////////////////////////////////
class Queue
{
private final int SIZE = 20;
private int[] queArray;
private int front;
private int rear;
// -------------------------------------------------------------
public Queue() // constructor
{
queArray = new int[SIZE];
front = 0;
rear = -1;
}
// -------------------------------------------------------------
public void insert(int j) // put item at rear of queue
{
if(rear == SIZE-1)
rear = -1;
queArray[++rear] = j;
}
// -------------------------------------------------------------
public int remove() // take item from front of queue
{
int temp = queArray[front++];
if(front == SIZE)
front = 0;
return temp;
}
// -------------------------------------------------------------
public boolean isEmpty() // true if queue is empty
{
return ( rear+1==front || (front+SIZE-1==rear) );
}
// -------------------------------------------------------------
} // end class Queue
////////////////////////////////////////////////////////////////
class Vertex
{
public char label; // label (e.g. ‘A’)
public boolean wasVisited;
// -------------------------------------------------------------
public Vertex(char lab) // constructor
{
label = lab;
wasVisited = false;
}
// -------------------------------------------------------------
} // end class Vertex
////////////////////////////////////////////////////////////////
class Graph
{
private final int MAX_VERTS = 20;
private Vertex vertex.
Implementing Software Machines in C and GoEleanor McHugh
The next iteration of the talk I gave at Progscon, this introduces examples of Map implementation (useful for caches etc.) and outlines for addition of processor core code in a later talk.
Lab08/Lab08.cppLab08/Lab08.cpp//**************************************************************************************************************
// FILE: Lab08.cpp
//
// DESCRIPTION: Contains the main() function. Instantiates a PointTest object which tests the Point class.
//
// AUTHORS: your-name (your-email-address)
// your-partner's-name (your-partners-email-address)
//
// COURSE: CSE100 Principles of Programming with C++, Fall 2015
//
// LAB INFO: Lab 8 Date/Time: your-lab-date-and-time TA: your-lab-ta
//--------------------------------------------------------------------------------------------------------------
// TESTING:
//
// TEST CASE 1:
// ------------
// TEST CASE INPUT DATA:
// Point p1 x = 11
// Point p1 y = 22
// Point p2 x = -33
// Point p2 y = -44
//
// EXPECTED OUTPUT GIVEN THE INPUT:
// The point p1 is (11, 22)
// The point p2 is (-33, -44)
// The distance between the points is 79.322
// Moving point p1...The point p1 is now at (100, 200)
// The distance between the points is 277.894
// Moving point p2...The point p2 is now at (300, 400)
// The distance between the points is 282.843
//
// OBSERVED OUTPUT:
// Document the output from your program when you perform this test case
//
// TEST CASE RESULT: Document PASS or FAIL
//
// TEST CASE 2:
// ------------
// TEST CASE INPUT DATA:
// Point p1 x = ???
// Point p1 y = ???
// Point p2 x = ???
// Point p2 y = ???
//
// EXPECTED OUTPUT GIVEN THE INPUT:
// ??? Document the expected output ???
//
// OBSERVED OUTPUT:
// ??? Document the output from your program when you perform this test case ???
//
// TEST CASE RESULT: ??? Document PASS or FAIL ???
//**************************************************************************************************************
#include"PointTest.hpp"
//--------------------------------------------------------------------------------------------------------------
// FUNCTION: main()
//
// DESCRIPTION
// Starting point for the program.
//
// PSEUDOCODE
// Define a PointTest object named pointTest calling the default ctor.
// Call run() on the pointTest object.
// Return 0.
//--------------------------------------------------------------------------------------------------------------
???
Lab08/Point.cppLab08/Point.cpp//**************************************************************************************************************
// FILE: Point.cpp
//
// DESCRIPTION: Implementation of the Point class. See Point.hpp for the class declaration.
//
// AUTHORS: your-name (your-email-address)
// your-partner's-name (your-partners-email-address)
//
// COURSE: CSE100 Principles of Programming with C++, Fall 2015
//
// LAB INFO: Lab 8 Date/Time: your-lab-date-and-time TA: your-lab-ta
//**************************************************************************************************************
#include<cmath>// For sqrt()
#include<sstream>// For stringstre ...
Create a JAVA program that performs file IO and database interaction.pdfmalavshah9013
Create a JAVA program that performs file IO and database interaction via SQL. The program
needs to read data from the provided file: \"Project.csv\" and insert the data into a database. Then
the program needs to create a report from the database sorted by price descending. The report
should be in the format demonstrated below.
id (primary key - generated by the database)
cpuname
performance
price
Project.csv contents:CPU NamePerformancePrice (USD)Intel Core i7-3770K @
3.50GHz9,556$560.50Intel Core i7-3770 @ 3.40GHz9,327$335.55Intel Core i7-3820 @
3.60GHz8,990$404.38AMD FX-8350 Eight-Core8,940$149.99Intel Core i7-2600K @
3.40GHz8,501$379.97Intel Core i7-2600 @ 3.40GHz8,242$214.99Intel Core i7-4720HQ @
2.60GHz8,046NAAMD FX-8320 Eight-Core8,008$145.99Intel Core i7-6700HQ @
2.60GHz7,997$1509Intel Core i7-4710HQ @ 2.50GHz7,826NAIntel Core i5-6600K @
3.50GHz7,762$239.99Intel Core i7-4700HQ @ 2.40GHz7,754$383.00Intel Core i7-4700MQ
@ 2.40GHz7,736$467.40Intel Core i5-4690K @ 3.50GHz7,690$239.99AMD FX-8150 Eight-
Core7,619$165.99Intel Core i7-3630QM @ 2.40GHz7,604$304.49Intel Core i5-4670K @
3.40GHz7,598$249.99Intel Core i5-4690 @ 3.50GHz7,542$224.99Intel Core i7-3610QM @
2.30GHz7,460$399.99Intel Core i5-4670 @ 3.40GHz7,342$226.99Intel Core i5-4590 @
3.30GHz7,174$199.99Intel Core i7-4702MQ @ 2.20GHz7,146NAIntel Core i5-3570K @
3.40GHz7,130$477.23
Solution
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class Main
{
/**
* This the main function that runs at the start
* param args - input arguments from the command line
*/
static public void main(String[] args)
{
CPUList cpuList = new CPUList(); //The CPUList used to retrieve data from the
fiile and store in the db
CPUList cpuListRetrieved = new CPUList(); //The CPUList used to retrieve data from the
database
CpuDb cpuDb = new CpuDb(); //The database object used to move data to and
from the CPU Lists
try
{
//Read in the file and store each line into the CPU objects in a list
Files.lines(Paths.get(\"Project04Data.csv\"))
.map(line -> line.split(\"\ \ \")) // Stream
.flatMap(Arrays::stream) // Stream
.forEach(line -> cpuList.AddCpu(line));
//Clear the list table for the new listing
cpuDb.Clear();
//Insert the Cpu List into the database
cpuDb.SetCpuList(cpuList);
//Retrieve the Cpu List into a different CPU List object from the database
cpuDb.GetCpuList(cpuListRetrieved);
//Show the report from the new list that was retrieved from the database
cpuListRetrieved.ShowReport();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
CPUList.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class CPUList
{
ArrayList theList = new ArrayList<>();
/**
* Default constructor for the CPU
*/
public void CPUList()
{
}
/**
* param strInputLine Input line to be used in creating the CPU object
*/
public void AddCpu(String strInputLine)
{
theList.add(new CPU(strInputLine));
}
/**
* param tempCPU - A CPU object to.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
2. StacksStacks
A stack is a data structure in which all the
access is restricted to the most recently
inserted items.
If we remove this item, then we can access the
next-to-last item inserted, and etc.
A stack is also a handy aid for algorithms
applied to certain complex data structures.
3. Stack Model
Input to a stack is by push
Access is by top
Deletion is by pop
5. The stack operations
push() –push() – Insert element on top of stack.Insert element on top of stack.
pop() -pop() - Removes and returns the top mostRemoves and returns the top most
element of the stack.element of the stack.
peek() –peek() – Read the top value on the stackRead the top value on the stack
without removing.without removing.
isEmpty –isEmpty – Checks the stack is empty or not.Checks the stack is empty or not.
isFull –isFull – Checks the stack is full or not.Checks the stack is full or not.
6. Implementation Of StacksImplementation Of Stacks
There are two basic ways to arrange for
constant time operations.
The first is to store the items contiguously in an
array.
And the second is to store items non contiguously
in a linked list
7. Array Implementation
import java.io.*;import java.io.*;
class StackXclass StackX
{{
private int maxSize;private int maxSize;
private double[] stackArray;private double[] stackArray;
private int top;private int top;
//---------------------------------//---------------------------------
public StackX(int s)public StackX(int s)
{{
maxSize=s;maxSize=s;
stackArray=new double[maxSize];stackArray=new double[maxSize];
top=-1;top=-1;
}}
//---------------------------------//---------------------------------
public void push(double j)public void push(double j)
{{
stackArray[++top]=j;stackArray[++top]=j;
}}
//---------------------------------//---------------------------------
12. class ReverseAppclass ReverseApp
{{
public static void main(String[] args) throws IOExceptionpublic static void main(String[] args) throws IOException
{{
String input, output;String input, output;
while(true)while(true)
{{
System.out.print("Enter a string: ");System.out.print("Enter a string: ");
System.out.flush();System.out.flush();
input = getString(); // read a string from kbdinput = getString(); // read a string from kbd
if( input.equals("") ) // quit if [Enter]if( input.equals("") ) // quit if [Enter]
break;break;
// make a Reverser// make a Reverser
Reverser theReverser = new Reverser(input);Reverser theReverser = new Reverser(input);
output = theReverser.doRev(); // use itoutput = theReverser.doRev(); // use it
System.out.println("Reversed: " + output);System.out.println("Reversed: " + output);
} // end while} // end while
} // end main()} // end main()
//--------------------------------------------------------------//--------------------------------------------------------------
public static String getString() throws IOExceptionpublic static String getString() throws IOException
{{
InputStreamReader isr = new InputStreamReader(System.in);InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);BufferedReader br = new BufferedReader(isr);
String s = br.readLine();String s = br.readLine();
return s;return s;
}}
} // end class ReverseApp} // end class ReverseApp
13. class Reverserclass Reverser
{{
private String input; // input stringprivate String input; // input string
private String output; // output stringprivate String output; // output string
//--------------------------------------------------------------//--------------------------------------------------------------
public Reverser(String in) // constructorpublic Reverser(String in) // constructor
{{
input = in;input = in;
}}
//--------------------------------------------------------------//--------------------------------------------------------------
public String doRev() // reverse the stringpublic String doRev() // reverse the string
{{
int stackSize = input.length(); // get max stack sizeint stackSize = input.length(); // get max stack size
StackX theStack = new StackX(stackSize); // make stackStackX theStack = new StackX(stackSize); // make stack
for(int j=0; j<input.length(); j++)for(int j=0; j<input.length(); j++)
{{
char ch = input.charAt(j); // get a char from inputchar ch = input.charAt(j); // get a char from input
theStack.push(ch); // push ittheStack.push(ch); // push it
}}
output = "";output = "";
while( !theStack.isEmpty() )while( !theStack.isEmpty() )
{{
char ch = theStack.pop(); // pop a char,char ch = theStack.pop(); // pop a char,
output = output + ch; // append to outputoutput = output + ch; // append to output
}}
return output;return output;
} // end doRev()} // end doRev()
} // end class Reverser} // end class Reverser
14. Delimiter ExampleDelimiter Example
class BracketCheckerclass BracketChecker
{{
private String input; // input stringprivate String input; // input string
//-------------------------//-------------------------
public BracketChecker(String in) // constructorpublic BracketChecker(String in) // constructor
{ input = in; }{ input = in; }
//------------------------------------------------------//------------------------------------------------------
public void check()public void check()
{{
int stackSize = input.length(); // get max stack sizeint stackSize = input.length(); // get max stack size
StackX theStack = new StackX(stackSize); // make stackStackX theStack = new StackX(stackSize); // make stack
for(int j=0; j<input.length(); j++) // get chars in turnfor(int j=0; j<input.length(); j++) // get chars in turn
{{
char ch = input.charAt(j); // get charchar ch = input.charAt(j); // get char
switch(ch)switch(ch)
{{
case '{': case '[': case '(': // the opening symbolscase '{': case '[': case '(': // the opening symbols
theStack.push(ch); // push themtheStack.push(ch); // push them
break;break;
case '}': case ']': case ')': // closing symbolscase '}': case ']': case ')': // closing symbols
if( !theStack.isEmpty() ) // if stack not empty,if( !theStack.isEmpty() ) // if stack not empty,
{{
char chx = theStack.pop(); // pop and checkchar chx = theStack.pop(); // pop and check
if( (ch=='}' && chx!='{') || (ch==']' && chx!='[') ||if( (ch=='}' && chx!='{') || (ch==']' && chx!='[') ||
(ch==')' && chx!='(') )(ch==')' && chx!='(') )
System.out.println("Error: "+ch+" at "+j);System.out.println("Error: "+ch+" at "+j);
}}
else // prematurely emptyelse // prematurely empty
System.out.println("Error: "+ch+" at "+j);System.out.println("Error: "+ch+" at "+j);
break;break;
} // end switch} // end switch
} // end for} // end for
// at this point, all characters have been processed// at this point, all characters have been processed
if( !theStack.isEmpty() )if( !theStack.isEmpty() )
System.out.println("Error: missing right delimiter");System.out.println("Error: missing right delimiter");
} // end check()} // end check()
//------------------------------------------------------------’//------------------------------------------------------------’
} // end class BracketChecker} // end class BracketChecker
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
15. class BracketsAppclass BracketsApp
{{
public static void main(String[] args) throws IOExceptionpublic static void main(String[] args) throws IOException
{{
String input;String input;
while(true)while(true)
{{
System.out.print("Enter string containing delimiters: ");System.out.print("Enter string containing delimiters: ");
System.out.flush();System.out.flush();
input = getString(); // read a string from kbdinput = getString(); // read a string from kbd
if( input.equals("") ) // quit if [Enter]if( input.equals("") ) // quit if [Enter]
break;break;
BracketChecker theChecker = new BracketChecker(input);BracketChecker theChecker = new BracketChecker(input);
theChecker.check(); // check bracketstheChecker.check(); // check brackets
} // end while} // end while
} // end main()} // end main()
//--------------------------------------------------//--------------------------------------------------
public static String getString() throws IOExceptionpublic static String getString() throws IOException
{{
InputStreamReader isr = new InputStreamReader(System.in);InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);BufferedReader br = new BufferedReader(isr);
String s = br.readLine();String s = br.readLine();
return s;return s;
} //---------------------------------} //---------------------------------
} //} //
16. Error HandlingError Handling
There are different philosophies about how to handle stack
errors. What happens if you try to push an item onto a stack
that's already full, or pop an item from a stack that's empty?
We've left the responsibility for handling such errors up to the
class user. The user should always check to be sure the stack
is not full before inserting an item:
if( !theStack.isFull() )
insert(item);
else
System.out.print("Can't insert, stack is full");
17. Efficiency of StacksEfficiency of Stacks
Items can be both pushed and popped from the
stack implemented in the StackX class in
constant O(1) time.
That is, the time is not dependent on how many
items are in the stack, and is therefore very
quick.
No comparisons or moves are necessary.
18. QueueQueue
Queue is simply a waiting line that grows by adding elements to its end and shrinks by
taking elements from its front. Unlike a stack , a queue is a structure in which both ends
are used : one for adding new elements and one for removing them. Therefore , the last
element has to wait until all element has to wait until all elements preceding it on the
queue are removed . A queue is an FIFO structure.
clear() – clear the queue
isEmpty() – check to see if the queue is empty
enqueue(el) – Put the element el at the end of the queue
dequeue() – Take first element from the queue
firstEl() - - return the first element or peek()
19.
20.
21. There are various queues quietly doing their job in ourThere are various queues quietly doing their job in our
computer's (or the network's) operating system.computer's (or the network's) operating system.
There's a printer queue where print jobs wait for theThere's a printer queue where print jobs wait for the
printer to be available.printer to be available.
A queue also stores keystroke data as we type at theA queue also stores keystroke data as we type at the
keyboard.keyboard.
This way, if we are using a word processor but theThis way, if we are using a word processor but the
computer is briefly doing something else when we hitcomputer is briefly doing something else when we hit
a key, the keystroke won't be lost; it waits in the queuea key, the keystroke won't be lost; it waits in the queue
until the word processor has time to read it.until the word processor has time to read it.
Using a queue guarantees the keystrokes stay inUsing a queue guarantees the keystrokes stay in
order until they can be processed.order until they can be processed.
22. A Circular QueueA Circular Queue
When we insert a new item in the queue in the WorkshopWhen we insert a new item in the queue in the Workshop
applet, the Front arrow moves upward, toward higher numbers in theapplet, the Front arrow moves upward, toward higher numbers in the
array.array.
When we remove an item, Front also moves upward.When we remove an item, Front also moves upward.
we may find the arrangement counter-intuitive, because the peoplewe may find the arrangement counter-intuitive, because the people
in a line at the movies all move forward, toward the front, whenin a line at the movies all move forward, toward the front, when
a person leaves the line.a person leaves the line.
We could move all the items in a queue whenever we deletedWe could move all the items in a queue whenever we deleted
one, but that wouldn't be very efficient.one, but that wouldn't be very efficient.
Instead we keep all the items in the same place and move theInstead we keep all the items in the same place and move the
front and rear of the queue.front and rear of the queue.
To avoid the problem of not being able to insert more items into theTo avoid the problem of not being able to insert more items into the
queue even when it's not full, the Front and Rear arrows wrap aroundqueue even when it's not full, the Front and Rear arrows wrap around
to the beginning of the array. The result is a circular queueto the beginning of the array. The result is a circular queue
23. Array implementation of queueArray implementation of queue
public class ArrayQueue
{
private int first,last,size;
private Object[] storage;
public ArrayQueue()
{
this(100);
}
public ArrayQueue(int n)
{
size=n;
storage=new Object[size];
first=last=-1;
}
public boolean isFull()
{
return first==0 && last==size-1 || first==last+1;
}
public boolean isEmpty()
{
return first==-1;
}
26. DequesDeques
A deque is a double-ended queue.A deque is a double-ended queue.
We can insert items at either end and delete them fromWe can insert items at either end and delete them from
either end.either end.
The methods might be called insertLeft() and insertRight(),The methods might be called insertLeft() and insertRight(),
and removeLeft() and removeRight().and removeLeft() and removeRight().
If we restrict ourself to insertLeft() and removeLeft() (orIf we restrict ourself to insertLeft() and removeLeft() (or
their equivalents on the right), then the deque acts like atheir equivalents on the right), then the deque acts like a
stack.stack.
If we restrict ourself to insertLeft() and removeRight() (orIf we restrict ourself to insertLeft() and removeRight() (or
the opposite pair), then it acts like a queue.the opposite pair), then it acts like a queue.
A deque provides a more versatile data structure thanA deque provides a more versatile data structure than
either a stack or a queue, and is sometimes used ineither a stack or a queue, and is sometimes used in
container class libraries to serve both purposes.container class libraries to serve both purposes.
27. Priority QueuesPriority Queues
A priority queue is a more specialized data structureA priority queue is a more specialized data structure
than a stack or a queue.than a stack or a queue.
However, it's a useful tool in a surprising number ofHowever, it's a useful tool in a surprising number of
situations.situations.
Like an ordinary queue, a priority queue has a frontLike an ordinary queue, a priority queue has a front
and a rear, and items are removed from the front.and a rear, and items are removed from the front.
However, in a priority queue, items are ordered by keyHowever, in a priority queue, items are ordered by key
value, so that the item with the lowest key (or in somevalue, so that the item with the lowest key (or in some
implementations the highest key) is always at theimplementations the highest key) is always at the
front.front.
Items are inserted in the proper position to maintainItems are inserted in the proper position to maintain
the order.the order.
28. Here’s how the mail sorting analogy applies to a
priority queue. Every time the postman hands
you a letter, you insert it into your pile of
pending letters according to its priority. If it
must be answered immediately (the phone
company is about to disconnect your modem
line), it goes on top, while if it can wait for a
leisurely answer (a letter from your Aunt
Mabel), it goes on the bottom.
29. Java Implementation of Priority QueueJava Implementation of Priority Queue
import java.io.*; // for I/O
////////////////////////////////////////////////////////////////
class PriorityQ
{
// array in sorted order, from max at 0 to min at size-1
private int maxSize;
private double[] queArray;
private int nItems;
//-------------------------------------------------------------
public PriorityQ(int s) // constructor
{
maxSize = s;
queArray = new double[maxSize];
nItems = 0;
}
30. public void insert(double item) // insert item
{
int j;
if(nItems==0) // if no items,
queArray[nItems++] = item; // insert at 0
else // if any items,
{
for(j=nItems-1; j>=0; j--) // start at end,
{
if( item > queArray[j] ) // if new item larger,
queArray[j+1] = queArray[j]; // shift upward
else // if smaller,
break; // done shifting
} // end for
queArray[j+1] = item; // insert it
nItems++;
} // end else (nItems > 0)
} // end insert()
31. public double remove() // remove minimum item
{
return queArray[--nItems];
}
public double peekMin() // peek at minimum item
{ return queArray[nItems-1]; }
public boolean isEmpty() // true if queue is empty
{ return (nItems==0); }
public boolean isFull() // true if queue is full
{ return (nItems == maxSize); }
} // end class PriorityQ
32. class PriorityQApp
{
public static void main(String[] args) throws IOException
{
PriorityQ thePQ = new PriorityQ(5);
thePQ.insert(30);
thePQ.insert(50);
thePQ.insert(10);
thePQ.insert(40);
thePQ.insert(20);
while( !thePQ.isEmpty() )
{
double item = thePQ.remove();
System.out.print(item + " "); // 10, 20, 30, 40, 50
} // end while
System.out.println(" ");
} // end main()
//-------------------------------------------------------------
} // end class PriorityQApp
33. Efficiency of Priority QueuesEfficiency of Priority Queues
In the priority-queue implementation we showIn the priority-queue implementation we show
here, insertion runs in O(N) time, while deletionhere, insertion runs in O(N) time, while deletion
takes O(1) time.takes O(1) time.
34. Introduction to HashingIntroduction to Hashing
A different approach to searching calculates the
position of the key in the table based on the value of
the key.
The value of the key is the only indication of the
position.
When the key is known, the position in the table can
be accessed directly without making any test as in
sequential binary search.
We need to find a function h that can transform a
particular key K be it a string, number or record into an
index in the table used for storing items of the same
type as K. the function h is called hash function.
36. Hash FunctionsHash Functions
Perfect hash functionPerfect hash function - if- if hh transformstransforms
different keys into different numbers.different keys into different numbers.
- enables us to trivially build an- enables us to trivially build an O(1)O(1) search timesearch time
table.table.
- the table should contain the same number of- the table should contain the same number of
positions as the number of elements being hashed.positions as the number of elements being hashed.
37. Hash FunctionsHash Functions
Some specific types of hash functions are:Some specific types of hash functions are:
DivisionDivision
h(k) = K mod TSizeh(k) = K mod TSize Tsize = sizeof(table)Tsize = sizeof(table)
Usually the preferred choice for the hash functionUsually the preferred choice for the hash function
if very little is known about the keys.if very little is known about the keys.
38. FoldingFolding
In this number is divided into number of parts, andIn this number is divided into number of parts, and
these parts are sometimes reversed and thenthese parts are sometimes reversed and then
added together. Finally the last three digit of theadded together. Finally the last three digit of the
sum or sum mod TableSize is used as the key.sum or sum mod TableSize is used as the key.
Ex:Ex:
SSN : 123-45-6789 can be divide into 123 456 789SSN : 123-45-6789 can be divide into 123 456 789
Mid part can be reversedMid part can be reversed
123+654+789 = 1566123+654+789 = 1566
Last three digits = 566Last three digits = 566
h(k) = 566h(k) = 566
39. Mid-Square FunctionMid-Square Function
The key is squared and the middle or mid part ofThe key is squared and the middle or mid part of
the result is used as the address. If the key is athe result is used as the address. If the key is a
string, it has to be pre-processed to produce astring, it has to be pre-processed to produce a
number.number.
e.g. if the key is 3121 then 3121e.g. if the key is 3121 then 31212 =2 =
9740641 and9740641 and
h(3121) = 406.h(3121) = 406.
40. ExtractionExtraction
Only a part of the key is used to compute theOnly a part of the key is used to compute the
address. For the key 123-45-6789 this methodaddress. For the key 123-45-6789 this method
might use themight use the
first four digits 1234first four digits 1234
last four digits 6789last four digits 6789
the first two combined with last two 1289 orthe first two combined with last two 1289 or
some other combinationsome other combination
41. Radix TransformationRadix Transformation
The key is transformed into another numberThe key is transformed into another number
base.base.
e.g. If K is the decimal number 345, then itse.g. If K is the decimal number 345, then its
value in base 9 is 423. This value is thenvalue in base 9 is 423. This value is then
divided modulo TSize, and the resultingdivided modulo TSize, and the resulting
number is used as the address of the locationnumber is used as the address of the location
to which K should be hashed.to which K should be hashed.