This document describes a C++ class called SharedMemoryHashTable that implements a hash table using shared memory rather than heap memory. Two blocks of shared memory are used to store the hash table buckets and linked list nodes for collisions. The class allows processes to insert, find, and delete items in the shared hash table. It was tested on Linux using g++ and allows storing arbitrary data types that provide a default constructor and string conversion operator.
Where's My SQL? Designing Databases with ActiveRecord MigrationsEleanor McHugh
A presentation given at RoReXchange in February 2007. Covers some abuses of the ActiveRecord Migrations mechanism along with examples of simple Rails plug-in design.
Elixir has a powerful and rapidly growing web development framework Phoenix and a part of this framework is an Ecto, a DSL library for data access. This talk will be an introduction into Ecto revealing the basic concepts and some of its more advanced features.
Elixir Meetup 4 Lviv
A class that automates conversion from a C++ recursive function to an iterative function. It allow the recursive function to preserve its structure by reproducing the "call stack" on an std::stack. The examples use combinatorics to illustrate usage.
Google interviewer asked for an algorithm to extract the k smallest elements from a set of ordered arrays. I suggested a vectorised bucket sort and merge sort approach. I took the problem offline and produced this analysis and C++.
InterTech provide international construction services - www.ooo-intertech.com...Maxim Gavrik
InterTech provide international construction services - design, construction, installation, commissioning and start-up of the MEP systems in the buildings and structures under industrial, commercial and civil construction.
Where's My SQL? Designing Databases with ActiveRecord MigrationsEleanor McHugh
A presentation given at RoReXchange in February 2007. Covers some abuses of the ActiveRecord Migrations mechanism along with examples of simple Rails plug-in design.
Elixir has a powerful and rapidly growing web development framework Phoenix and a part of this framework is an Ecto, a DSL library for data access. This talk will be an introduction into Ecto revealing the basic concepts and some of its more advanced features.
Elixir Meetup 4 Lviv
A class that automates conversion from a C++ recursive function to an iterative function. It allow the recursive function to preserve its structure by reproducing the "call stack" on an std::stack. The examples use combinatorics to illustrate usage.
Google interviewer asked for an algorithm to extract the k smallest elements from a set of ordered arrays. I suggested a vectorised bucket sort and merge sort approach. I took the problem offline and produced this analysis and C++.
InterTech provide international construction services - www.ooo-intertech.com...Maxim Gavrik
InterTech provide international construction services - design, construction, installation, commissioning and start-up of the MEP systems in the buildings and structures under industrial, commercial and civil construction.
Randy Kerns, CIC, ChFC • Voya Financial Advisors Inc.
- Why passive investors get hammered by Mike Posey
- Can it really be earnings season already?
- What oil's plunge and the strong Dollar may mean for 2015 by Jeanette Schwarz Young
- Active management as a practice differentiator (John McGonagle, CFP, CRPC, Asset Architects LLC)
Jerry Ganz • Packerland Brokerage Services
- Can lower returns lead to more money in retirement? The impact of sequencing and volatility on portfolio value by David Witkin
- Jump in Swiss franc triggers short-term losses and long-term uncertainty
- Crude oil’s message for the stock market by Tom McClellan
- Growing a referral network (Trish Beine, The Strategic Financial Alliance)
Jeff Pesta • LPL Financial
- Is it time to retire your strategy, manager, fund, or ETF? by Dave Moenning
- Dollar strength has uncertain implications
- The Anchored Momentum Indicator by Ron Rowland
- Converting positive feedback into new business (Steve Molesky, Kalos Capital Inc.)
Johnathon Davis • Retirement Tax Advisory Group Inc.
- Profiling ultra-high-net-worth clients by Katie Kuehner-Hebert
- Will weak jobs numbers delay Fed rate hike?
- Why you have way too much invested in U.S. stocks by Meb Faber
- Building a “niche” into a practice focus (Phylyp Wagner, Matt Quattlebaum, H. Beck)
Chris Gurnee • Foresters Equity Services Inc.
- 85,000 on the Dow: Pipedream or realistic possibility? Book review by David Wismer
- European stocks continue on torrid pace
- Risk on, until it isn’t by Jeanette Schwarz Young
- Managing 403(b) referrals in a tight-knit academic setting (Johnathon Davis, Retirement Tax Advisory Group)
Bob Pearson • Transamerica Financial Advisors Inc.
- Experts need experts: 10 questions to ask third-party money managers by Kellye Whitney
- Do record margins pose market threat?
- “Rule of 240” compounding by Ron Rowland
- Hot-button topics drive seminar attendance (Matthew Gaude, FSC Securities)
Ryan Finnell • Retirement Tax Advisory Group
- A "living in the moment" guide to investing by Jerry Wagner
- Sell in June and go away?
- Market “truths” subject to change by Rob Hanna
- Client appreciation: A sound investment (Jim Bowen, LPL Financial)
Don Meredith • Lincoln Financial Advisors Corp.
- The Millennial obsession by David Wismer
- Global decline in oil prices leads to “Fracklog”
- VIX ETFs not right for investors by Tom McClellan
- A generational shift in target marketing (Bryce Winkel, Transamerica Financial Advisors Inc.)
Phylyp Wagner & Matt Quattlebaum • H. Beck
- How often should you review your investment returns? The results may surprise you by Jerry Wagner
- The most scrutinized Fed rate hike ever?
- Recent Q1 highs lacked “oomph” by Tony Dwyer
- Expanding the family business tradition (Jeff Pesta, LPL Financial)
Trish Beine • The Strategic Financial Alliance
- Dissing the investor by Linda Ferentchak
- Ratio of gold to oil hits levels of the 1990s
- What will the next bear market look like: Grizzly or Teddy? by Marshall Schield
- Frequency of client touches leads to referrals (Randy Kerns, Voya Financial Advisors, Inc.)
yyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood good sdfesfedfdfdfdfdfdsf it is amazing how much magic you can makr
Brian Glaze & Larry Ware, CRPC, CLTC – Proactive Advisor Magazine – Volume 5 ...Proactive Advisor Magazine
Brian Glaze & Larry Ware • LPL Financial
- Why hasn’t the Efficient Market Hypothesis disappeared? by Linda Ferentchak
- Climbing U.S. dollar makes exports less competitive
- The seasons of the stock market by Paul Desmond
- Selling proposition: "Plan-based investing" (Jerry Ganz, Packerland Brokerage Services)
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Russell Childs
Simple demo of a framework I wrote for doing quantum mechanics in C++. It uses Dirac bras, kets, inner & tensor products, operators and so forth for the linear algebra of QM.
Describe a data structure that supports both removeMin() and rem.pdfarihantstoneart
Describe a data structure that supports both removeMin() and removeMax() with O(log(n))
complexity. You need to show the implementation of insert(), removeMin(), and removeMax(),
and prove their complexity. Hint: one can build on top of the heap.
/*IF YOU WRITE CODE, PLEASE PROVIDE COMMENTS*/
I need to understand
Describe a data structure that supports both removeMin() and removeMax() with O(log(n))
complexity. You need to show the implementation of insert(), removeMin(), and removeMax(),
and prove their complexity. Hint: one can build on top of the heap.
/*IF YOU WRITE CODE, PLEASE PROVIDE COMMENTS*/
I need to understand
Describe a data structure that supports both removeMin() and removeMax() with O(log(n))
complexity. You need to show the implementation of insert(), removeMin(), and removeMax(),
and prove their complexity. Hint: one can build on top of the heap.
/*IF YOU WRITE CODE, PLEASE PROVIDE COMMENTS*/
I need to understand
Solution
The idea here is to use the concept of two binary heaps along with the concept of list(doubly
linked list).
The doubly linked list contains all input items and indexes of corresponding min and max heap
nodes. The nodes of min and max heaps store addresses of nodes of doubly linked list. The root
node of min heap stores the address of minimum item in doubly linked list. Similarly, root of
max heap stores address of maximum item in doubly linked list. Following are the details of
operations.
1) findMax(): We get the address of maximum value node from root of Max Heap. So this is a
O(1) operation.
1) findMin(): We get the address of minimum value node from root of Min Heap. So this is a
O(1) operation.
3) removeMin(): We get the address of minimum value node from root of Min Heap. We use this
address to find the node in doubly linked list. From the doubly linked list, we get node of Max
Heap. We delete node from all three. We can delete a node from doubly linked list in O(1) time.
delete() operations for max and min heaps take O(Logn) time.
4) removeMax(): is similar to deleteMin()
5) Insert() We always insert at the beginning of linked list in O(1) time. Inserting the address in
Max and Min Heaps take O(Logn) time. So overall complexity is O(Logn)
#include
#include
#include
// A node of doubly linked list
struct LNode
{
int data;
int minHeapIndex;
int maxHeapIndex;
struct LNode *next, *prev;
};
// Structure for a doubly linked list
struct List
{
struct LNode *head;
};
// Structure for min heap
struct MinHeap
{
int size;
int capacity;
struct LNode* *array;
};
// Structure for max heap
struct MaxHeap
{
int size;
int capacity;
struct LNode* *array;
};
// The required data structure
struct CDS
{
struct MinHeap* minHeap;
struct MaxHeap* maxHeap;
struct List* list;
};
// A utility function to create a new List node
struct LNode* newLNode(int data)
{
struct LNode* node =
(struct LNode*) malloc(sizeof(struct LNode));
node->minHeapIndex = node->maxHeapIndex = -1;
node->data = data;
node->prev = node->next = NULL;
retu.
This project will implement a simple usernamepassword lookup system.pdfezhilvizhiyan
This project will implement a simple username/password lookup system using hash tables. You
should create the Hash Table from scratch. It may be helpful to create a separate class called
HashEntry, in which you can store a String username and String password. The Hash Table will
store these entries using the username as the key and the password as the value.
Create a hash code using the key to determine where the value is stored in the Hash Table. Here
is a sample hash method. Feel free to borrow it for your program:
privateint calcHashCode(String key) {
int mod = key.hashCode() % size;
return mod < 0 ? mod + size : mod;
}
You will be provided with a data file containing comma separated usernames and passwords.
Read the data in from the file and put it into the table. Once the table is populated, ask the user to
log into the system. If their username and password match the data in the table, alert the user that
access has been granted:
Login: trevor
User trevor not found.
Login: mary
Password: test
Authentication Failure
Login: mary
Password: contrary
Authentication Successful
Welcome mary
Provided Data File (containing comma separated usernames and passwords):
jack,broken.crown
jill,tumblin\'down
mary,contrary
bopeep,sheep!lost
Solution
//main.cpp
#include
#include
#include
#include
#include
#include \"HashTable.cpp\"
using namespace std;
/// the struct for the login and password
struct Account
{
/// variables
string login;
string password;
/// hash function
static unsigned int hash(const string& str)
{
unsigned int val = 0;
for (int i = 0; i < str.length(); ++i) {
val += str[i];
}
return val;
}
/// get key function
string getKey() const
{
return login;
}
};
int main()
{
string loginI;
string passwordI;
string temp;
/// open file
ifstream fin (\"password.dat\");
fin.clear();
/// make new account to read into
Account acct;
/// make the hash table
HashTable data (8);
/// read in
while (fin.good())
{
fin >> acct.login >> acct.password;
//cout << acct.login << \" \" << acct.password << endl;
data.insert(acct);
//data.showStructure();
}
data.showStructure();
/// read in
cout << \"Login: \";
cin >> loginI;
do
{
cout << \"Password: \";
cin >> passwordI;
/// check for login
if (data.retrieve(loginI, acct))
{
/// check if passwords are the same
if ((acct.password == passwordI))
{
/// same password, print success
cout << \"Authentication successful\" << endl;
}
else
{
/// different password, print failure
cout << \"Authentication failure\" << endl;
}
}
else
{
/// if the data login is not saved print failure
cout << \"Authentication failure\" << endl;
}
cout << \"Login: \";
cin >> loginI;
}
while(!cin.eof());
return 0;
}
=====================================================================
=====
#include
#include
#include
#include
#include \"HashTable.h\"
#include \"show10.cpp\"
using namespace std;
template
HashTable::HashTable(int initTableSize)
{
/// save size
tableSize = initTableSize;
/// initialize the array
dataTable = new BSTree[tableSize];
}
t.
Program 4You are to write an efficient program that will read a di.pdfezzi552
Lab Exercise — 2-D Arrays in C++
In this lab exercise, you are required to write a C++ program to add two 4 * 5 matrices and then
output the results to the screen.
Prompt the user to enter the name of two files with matrices
Compute the sum of the two matrices and output the results
A sample run is as follows:
Further requirements:
Create three functions:
readArray with void return and one 2D array argument and one string argument
printArray with void return and one 2D array argument
sumArray with void return and three 2D array arguments
Separate your code into three files as described in the lab:
main.cpp
myFunction.cpp
myFunction.h
If you can correct this and then saparete it to three files
#include
#include
#include
using namespace std;
const unsigned int R_SIZE=4;
const unsigned int C_SIZE=5;
void readArray(int p_Array[][C_SIZE], string fName); // function prototype
int main()
{
int i, j;
int Nums1[R_SIZE][C_SIZE];
string filename;
cout << \"Please enter the name of the file containing data for Array 1: \";
cin >>filename;
readArray(Nums1, filename);
for ( i=0; i < R_SIZE; i++)
{
for ( j=0; j< C_SIZE; j++)
{
cout<< Nums1[i][j] << \" \";
}
cout << endl;
}
}
// Function: readArray
// Purpose: To read values into an array.
// Parameters: Base address of an array.
// Returns: void
// --------------------------------------------------------
void readArray(int p_Array[R_SIZE][C_SIZE], string fName)
{
ifstream inF;
int i, j;
inF.open(fName.c_str());
if(inF.fail())
{
cout << fName << \"does not enist\" << endl;
}
else
{
cout << fName << \"exists\" << endl;
}
while(!inF.eof())
{
for ( i=0; i < R_SIZE; i++)
{
for ( j=0; j< C_SIZE; i++)
{
inF >> p_Array[i][j];
}
}
}
} // end InitArray function
Someone help me with this and I modified it a little bit but still can\'t read from the file!!!
This is the code
/*..............myFunction.h ...........*/
#include
#include
using namespace std;
const unsigned int R_SIZE=4;
const unsigned int C_SIZE=5;
void readArray(int p_Array[][C_SIZE], string fName); // function read prototype
void printArray(int p_Array[][C_SIZE]); // function print prototype
void sumArray (int p_Array1[][C_SIZE],int p_Array2[][C_SIZE],int p_Array3[][C_SIZE]);
/*..............myFunction.cpp ...........*/
#include \"myfunction.h\"
// Function: printArray
// Purpose: To print values of an array.
// Parameters: Base address of an array.
// Returns: void
// --------------------------------------------------------
void printArray(int p_Array[R_SIZE][C_SIZE]){
for (int i=0; i < R_SIZE; i++)
{
for (int j=0; j< C_SIZE; j++)
{
cout<< p_Array[i][j] << \" \";
}
cout << endl;
}
}
// Function: readArray
// Purpose: To read values into an array.
// Parameters: Base address of an array.
// Returns: void
// --------------------------------------------------------
void readArray(int p_Array[R_SIZE][C_SIZE], string fName)
{
ifstream inF;
int i, j;
inF.open(fName.c_str());
if(inF.fail())
{
cout << fName << \"does not enist\" << endl;
}
else
{
cout << fName .
Randy Kerns, CIC, ChFC • Voya Financial Advisors Inc.
- Why passive investors get hammered by Mike Posey
- Can it really be earnings season already?
- What oil's plunge and the strong Dollar may mean for 2015 by Jeanette Schwarz Young
- Active management as a practice differentiator (John McGonagle, CFP, CRPC, Asset Architects LLC)
Jerry Ganz • Packerland Brokerage Services
- Can lower returns lead to more money in retirement? The impact of sequencing and volatility on portfolio value by David Witkin
- Jump in Swiss franc triggers short-term losses and long-term uncertainty
- Crude oil’s message for the stock market by Tom McClellan
- Growing a referral network (Trish Beine, The Strategic Financial Alliance)
Jeff Pesta • LPL Financial
- Is it time to retire your strategy, manager, fund, or ETF? by Dave Moenning
- Dollar strength has uncertain implications
- The Anchored Momentum Indicator by Ron Rowland
- Converting positive feedback into new business (Steve Molesky, Kalos Capital Inc.)
Johnathon Davis • Retirement Tax Advisory Group Inc.
- Profiling ultra-high-net-worth clients by Katie Kuehner-Hebert
- Will weak jobs numbers delay Fed rate hike?
- Why you have way too much invested in U.S. stocks by Meb Faber
- Building a “niche” into a practice focus (Phylyp Wagner, Matt Quattlebaum, H. Beck)
Chris Gurnee • Foresters Equity Services Inc.
- 85,000 on the Dow: Pipedream or realistic possibility? Book review by David Wismer
- European stocks continue on torrid pace
- Risk on, until it isn’t by Jeanette Schwarz Young
- Managing 403(b) referrals in a tight-knit academic setting (Johnathon Davis, Retirement Tax Advisory Group)
Bob Pearson • Transamerica Financial Advisors Inc.
- Experts need experts: 10 questions to ask third-party money managers by Kellye Whitney
- Do record margins pose market threat?
- “Rule of 240” compounding by Ron Rowland
- Hot-button topics drive seminar attendance (Matthew Gaude, FSC Securities)
Ryan Finnell • Retirement Tax Advisory Group
- A "living in the moment" guide to investing by Jerry Wagner
- Sell in June and go away?
- Market “truths” subject to change by Rob Hanna
- Client appreciation: A sound investment (Jim Bowen, LPL Financial)
Don Meredith • Lincoln Financial Advisors Corp.
- The Millennial obsession by David Wismer
- Global decline in oil prices leads to “Fracklog”
- VIX ETFs not right for investors by Tom McClellan
- A generational shift in target marketing (Bryce Winkel, Transamerica Financial Advisors Inc.)
Phylyp Wagner & Matt Quattlebaum • H. Beck
- How often should you review your investment returns? The results may surprise you by Jerry Wagner
- The most scrutinized Fed rate hike ever?
- Recent Q1 highs lacked “oomph” by Tony Dwyer
- Expanding the family business tradition (Jeff Pesta, LPL Financial)
Trish Beine • The Strategic Financial Alliance
- Dissing the investor by Linda Ferentchak
- Ratio of gold to oil hits levels of the 1990s
- What will the next bear market look like: Grizzly or Teddy? by Marshall Schield
- Frequency of client touches leads to referrals (Randy Kerns, Voya Financial Advisors, Inc.)
yyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood goodyyeyeyeyeyey gang gang gang this is that gooooood crip it fgone make you explode you know you want to see tjat goood good sdfesfedfdfdfdfdfdsf it is amazing how much magic you can makr
Brian Glaze & Larry Ware, CRPC, CLTC – Proactive Advisor Magazine – Volume 5 ...Proactive Advisor Magazine
Brian Glaze & Larry Ware • LPL Financial
- Why hasn’t the Efficient Market Hypothesis disappeared? by Linda Ferentchak
- Climbing U.S. dollar makes exports less competitive
- The seasons of the stock market by Paul Desmond
- Selling proposition: "Plan-based investing" (Jerry Ganz, Packerland Brokerage Services)
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Russell Childs
Simple demo of a framework I wrote for doing quantum mechanics in C++. It uses Dirac bras, kets, inner & tensor products, operators and so forth for the linear algebra of QM.
Describe a data structure that supports both removeMin() and rem.pdfarihantstoneart
Describe a data structure that supports both removeMin() and removeMax() with O(log(n))
complexity. You need to show the implementation of insert(), removeMin(), and removeMax(),
and prove their complexity. Hint: one can build on top of the heap.
/*IF YOU WRITE CODE, PLEASE PROVIDE COMMENTS*/
I need to understand
Describe a data structure that supports both removeMin() and removeMax() with O(log(n))
complexity. You need to show the implementation of insert(), removeMin(), and removeMax(),
and prove their complexity. Hint: one can build on top of the heap.
/*IF YOU WRITE CODE, PLEASE PROVIDE COMMENTS*/
I need to understand
Describe a data structure that supports both removeMin() and removeMax() with O(log(n))
complexity. You need to show the implementation of insert(), removeMin(), and removeMax(),
and prove their complexity. Hint: one can build on top of the heap.
/*IF YOU WRITE CODE, PLEASE PROVIDE COMMENTS*/
I need to understand
Solution
The idea here is to use the concept of two binary heaps along with the concept of list(doubly
linked list).
The doubly linked list contains all input items and indexes of corresponding min and max heap
nodes. The nodes of min and max heaps store addresses of nodes of doubly linked list. The root
node of min heap stores the address of minimum item in doubly linked list. Similarly, root of
max heap stores address of maximum item in doubly linked list. Following are the details of
operations.
1) findMax(): We get the address of maximum value node from root of Max Heap. So this is a
O(1) operation.
1) findMin(): We get the address of minimum value node from root of Min Heap. So this is a
O(1) operation.
3) removeMin(): We get the address of minimum value node from root of Min Heap. We use this
address to find the node in doubly linked list. From the doubly linked list, we get node of Max
Heap. We delete node from all three. We can delete a node from doubly linked list in O(1) time.
delete() operations for max and min heaps take O(Logn) time.
4) removeMax(): is similar to deleteMin()
5) Insert() We always insert at the beginning of linked list in O(1) time. Inserting the address in
Max and Min Heaps take O(Logn) time. So overall complexity is O(Logn)
#include
#include
#include
// A node of doubly linked list
struct LNode
{
int data;
int minHeapIndex;
int maxHeapIndex;
struct LNode *next, *prev;
};
// Structure for a doubly linked list
struct List
{
struct LNode *head;
};
// Structure for min heap
struct MinHeap
{
int size;
int capacity;
struct LNode* *array;
};
// Structure for max heap
struct MaxHeap
{
int size;
int capacity;
struct LNode* *array;
};
// The required data structure
struct CDS
{
struct MinHeap* minHeap;
struct MaxHeap* maxHeap;
struct List* list;
};
// A utility function to create a new List node
struct LNode* newLNode(int data)
{
struct LNode* node =
(struct LNode*) malloc(sizeof(struct LNode));
node->minHeapIndex = node->maxHeapIndex = -1;
node->data = data;
node->prev = node->next = NULL;
retu.
This project will implement a simple usernamepassword lookup system.pdfezhilvizhiyan
This project will implement a simple username/password lookup system using hash tables. You
should create the Hash Table from scratch. It may be helpful to create a separate class called
HashEntry, in which you can store a String username and String password. The Hash Table will
store these entries using the username as the key and the password as the value.
Create a hash code using the key to determine where the value is stored in the Hash Table. Here
is a sample hash method. Feel free to borrow it for your program:
privateint calcHashCode(String key) {
int mod = key.hashCode() % size;
return mod < 0 ? mod + size : mod;
}
You will be provided with a data file containing comma separated usernames and passwords.
Read the data in from the file and put it into the table. Once the table is populated, ask the user to
log into the system. If their username and password match the data in the table, alert the user that
access has been granted:
Login: trevor
User trevor not found.
Login: mary
Password: test
Authentication Failure
Login: mary
Password: contrary
Authentication Successful
Welcome mary
Provided Data File (containing comma separated usernames and passwords):
jack,broken.crown
jill,tumblin\'down
mary,contrary
bopeep,sheep!lost
Solution
//main.cpp
#include
#include
#include
#include
#include
#include \"HashTable.cpp\"
using namespace std;
/// the struct for the login and password
struct Account
{
/// variables
string login;
string password;
/// hash function
static unsigned int hash(const string& str)
{
unsigned int val = 0;
for (int i = 0; i < str.length(); ++i) {
val += str[i];
}
return val;
}
/// get key function
string getKey() const
{
return login;
}
};
int main()
{
string loginI;
string passwordI;
string temp;
/// open file
ifstream fin (\"password.dat\");
fin.clear();
/// make new account to read into
Account acct;
/// make the hash table
HashTable data (8);
/// read in
while (fin.good())
{
fin >> acct.login >> acct.password;
//cout << acct.login << \" \" << acct.password << endl;
data.insert(acct);
//data.showStructure();
}
data.showStructure();
/// read in
cout << \"Login: \";
cin >> loginI;
do
{
cout << \"Password: \";
cin >> passwordI;
/// check for login
if (data.retrieve(loginI, acct))
{
/// check if passwords are the same
if ((acct.password == passwordI))
{
/// same password, print success
cout << \"Authentication successful\" << endl;
}
else
{
/// different password, print failure
cout << \"Authentication failure\" << endl;
}
}
else
{
/// if the data login is not saved print failure
cout << \"Authentication failure\" << endl;
}
cout << \"Login: \";
cin >> loginI;
}
while(!cin.eof());
return 0;
}
=====================================================================
=====
#include
#include
#include
#include
#include \"HashTable.h\"
#include \"show10.cpp\"
using namespace std;
template
HashTable::HashTable(int initTableSize)
{
/// save size
tableSize = initTableSize;
/// initialize the array
dataTable = new BSTree[tableSize];
}
t.
Program 4You are to write an efficient program that will read a di.pdfezzi552
Lab Exercise — 2-D Arrays in C++
In this lab exercise, you are required to write a C++ program to add two 4 * 5 matrices and then
output the results to the screen.
Prompt the user to enter the name of two files with matrices
Compute the sum of the two matrices and output the results
A sample run is as follows:
Further requirements:
Create three functions:
readArray with void return and one 2D array argument and one string argument
printArray with void return and one 2D array argument
sumArray with void return and three 2D array arguments
Separate your code into three files as described in the lab:
main.cpp
myFunction.cpp
myFunction.h
If you can correct this and then saparete it to three files
#include
#include
#include
using namespace std;
const unsigned int R_SIZE=4;
const unsigned int C_SIZE=5;
void readArray(int p_Array[][C_SIZE], string fName); // function prototype
int main()
{
int i, j;
int Nums1[R_SIZE][C_SIZE];
string filename;
cout << \"Please enter the name of the file containing data for Array 1: \";
cin >>filename;
readArray(Nums1, filename);
for ( i=0; i < R_SIZE; i++)
{
for ( j=0; j< C_SIZE; j++)
{
cout<< Nums1[i][j] << \" \";
}
cout << endl;
}
}
// Function: readArray
// Purpose: To read values into an array.
// Parameters: Base address of an array.
// Returns: void
// --------------------------------------------------------
void readArray(int p_Array[R_SIZE][C_SIZE], string fName)
{
ifstream inF;
int i, j;
inF.open(fName.c_str());
if(inF.fail())
{
cout << fName << \"does not enist\" << endl;
}
else
{
cout << fName << \"exists\" << endl;
}
while(!inF.eof())
{
for ( i=0; i < R_SIZE; i++)
{
for ( j=0; j< C_SIZE; i++)
{
inF >> p_Array[i][j];
}
}
}
} // end InitArray function
Someone help me with this and I modified it a little bit but still can\'t read from the file!!!
This is the code
/*..............myFunction.h ...........*/
#include
#include
using namespace std;
const unsigned int R_SIZE=4;
const unsigned int C_SIZE=5;
void readArray(int p_Array[][C_SIZE], string fName); // function read prototype
void printArray(int p_Array[][C_SIZE]); // function print prototype
void sumArray (int p_Array1[][C_SIZE],int p_Array2[][C_SIZE],int p_Array3[][C_SIZE]);
/*..............myFunction.cpp ...........*/
#include \"myfunction.h\"
// Function: printArray
// Purpose: To print values of an array.
// Parameters: Base address of an array.
// Returns: void
// --------------------------------------------------------
void printArray(int p_Array[R_SIZE][C_SIZE]){
for (int i=0; i < R_SIZE; i++)
{
for (int j=0; j< C_SIZE; j++)
{
cout<< p_Array[i][j] << \" \";
}
cout << endl;
}
}
// Function: readArray
// Purpose: To read values into an array.
// Parameters: Base address of an array.
// Returns: void
// --------------------------------------------------------
void readArray(int p_Array[R_SIZE][C_SIZE], string fName)
{
ifstream inF;
int i, j;
inF.open(fName.c_str());
if(inF.fail())
{
cout << fName << \"does not enist\" << endl;
}
else
{
cout << fName .
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. .
Complete code in Java The hashtable you'll be making will use String.pdfaarifi9988
According to analysts, the growth rate in dividends for YBM for the next five years is expected
to be 20 percent. Suppose YBM meets this growth rate in dividends for the next five years and
then the dividend growth rate falls to 5.25 percent, indefinitely. Assume investors require a
return of 13 percent on YBM stock. According to the dividend growth model, what should the
stock price be today? Note: Do not round intermediate calculations and round your answer to 2
decimal places, e.g., 32.16.) Answer is complete but not entirely correct. Based on these
assumptions, is the stock currently overvalued, undervalued, or correctly valued?.
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.
using the code below write the public V add(K key, V value); that ad.pdfamirthagiftsmadurai
using the code below write the public V add(K key, V value); that adds a new entry into
hashtable if the table (hashTable[index] != null) && (hashTable[index] != AVAILABLE
if the key is the same as keyindex inside the hash replace the old value with the new value
if the key is different from the keyindex go to the next index and count for collisions until will
you find a null space inside the hashtable index
import java.util.Iterator;
public interface DictionaryInterface
{
/** Adds a new entry to this dictionary. If the given search key already
exists in the dictionary, replaces the corresponding value.
@param key An object search key of the new entry.
@param value An object associated with the search key.
@return Either null if the new entry was added to the dictionary
or the value that was associated with key if that value
was replaced. */
public V add(K key, V value);
/** Removes a specific entry from this dictionary.
@param key An object search key of the entry to be removed.
@return Either the value that was associated with the search key
or null if no such object exists. */
public V remove(K key);
/** Retrieves from this dictionary the value associated with a given
search key.
@param key An object search key of the entry to be retrieved.
@return Either the value that is associated with the search key
or null if no such object exists. */
public V getValue(K key);
/** Sees whether a specific entry is in this dictionary.
@param key An object search key of the desired entry.
@return True if key is associated with an entry in the dictionary. */
public boolean contains(K key);
/** Creates an iterator that traverses all search keys in this dictionary.
@return An iterator that provides sequential access to the search
keys in the dictionary. */
public Iterator getKeyIterator();
/** Creates an iterator that traverses all values in this dictionary.
@return An iterator that provides sequential access to the values
in this dictionary. */
public Iterator getValueIterator();
/** Sees whether this dictionary is empty.
@return True if the dictionary is empty. */
public boolean isEmpty();
/** Gets the size of this dictionary.
@return The number of entries (key-value pairs) currently
in the dictionary. */
public int getSize();
/** Removes all entries from this dictionary. */
public void clear();
} // end DictionaryInterface
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A class that implements the ADT dictionary by using hashing and
* linear probing to resolve collisions.
* The dictionary is unsorted and has distinct search key.
Search keys and associated values are not null.
*/
public class HashedDictionary implements DictionaryInterface
{
// The dictionary:
private int numberOfEntries;
private static final int DEFAULT_CAPACITY = 5; // Must be prime
private static final int MAX_CAPACITY = 10000;
// The hash table:
private Entry[] hashTable;
private int tableSize; // Must be prime
private static final int MAX_SIZE = 2 * MAX_CAPA.
The hashtable youll be making will use Strings as the keys and Obje.pdfvicky309441
The hashtable you'll be making will use Strings as the keys and Object as the values. Similar to
linked lists, by storing Object as values, you can store any kind of object in the hashtable.
package Dictionary;
import java.util.ArrayList;
import java.util.Hashtable;
import List.ListInterface;
import List.MyLinkedList;
public class MyHashtable implements DictionaryInterface {
protected int tableSize;
protected int size;
// The LinkedList is of type Entry
protected MyLinkedList[] table;
public MyHashtable(int tableSize) {
table = new MyLinkedList[tableSize];
this.tableSize = tableSize;
}
public int biggestBucket()
{
int biggestBucket = 0;
for(int i = 0; i < table.length; i++) {
// Loop through the table looking for non-null locations.
if (table[i] != null) {
// If you find a non-null location, compare the bucket size against the largest
// bucket size found so far. If the current bucket size is bigger, set biggestBucket
// to this new size.
MyLinkedList bucket = table[i];
if (biggestBucket < bucket.size())
biggestBucket = bucket.size();
}
}
return biggestBucket; // Return the size of the biggest bucket found.
}
// Returns the average bucket length. Gives a sense of how many collisions are happening
overall.
public float averageBucket() {
float bucketCount = 0; // Number of buckets (non-null table locations)
float bucketSizeSum = 0; // Sum of the size of all buckets
for(int i = 0; i < table.length; i++) {
// Loop through the table
if (table[i] != null) {
// For a non-null location, increment the bucketCount and add to the bucketSizeSum
MyLinkedList bucket = table[i];
bucketSizeSum += bucket.size();
bucketCount++;
}
}
// Divide bucketSizeSum by the number of buckets to get an average bucket length.
return bucketSizeSum/bucketCount;
}
public String toString()
{
String s = "";
for(int tableIndex = 0; tableIndex < tableSize; tableIndex++) {
if (table[tableIndex] != null) {
MyLinkedList bucket = table[tableIndex];
for(int listIndex = 0; listIndex < bucket.size(); listIndex++) {
Entry e = (Entry)bucket.get(listIndex);
s = s + "key: " + e.key + ", value: " + e.value + "\n";
}
}
}
return s;
}
protected class Entry
{
String key;
Object value;
Entry(String key, Object value) {
this.key = key;
this.value = value;
}
}
// Implement these methods
public boolean isEmpty() {return true;} // returns true if the Dictionary is empty, false otherwise.
public int size(){return -1;} //Returns the number of key/value pairs stored in the dictionary.
// Adds a value stored under the given key. If the key has already been stored in the Dictionary,
// replaces the value associated with the key and returns the old value. If the key isn't in the
dictionary
// returns null.
public Object put(String key, Object value){
// 1. Compute an array index given the key
// 2. If that location in the table is null,
// that means nothing has been previously stored using a key with this hash code.
// a. Create a new MyLinkedList to be the bucket.
// b. Add the new Entry for the key/value.
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
2.(Sorted list: array implementation)This sorted list ADT discussed in class should be extended
by the addition of two new methods:
//Interface: ArrayListADT
//works for int
public interface ArrayListADT {
public boolean isEmpty(); //Method to determine whether the list is empty.
public boolean isFull(); //Method to determine whether the list is full.
public int listSize(); //Method to return the number of elements in the list.
public int maxListSize(); //Method to return the maximum size of the list.
public void print(); //Method to output the elements of the list.
public boolean isItemAtEqual(int location, int item); //Method to determine whether item is
the same as the item in the list at location.
public void insertAt(int location, int insertItem); //Method to insert insertItem in the list at
the position
public void insertEnd(int insertItem); //Method to insert insertItem at the end of the list.
public void removeAt(int location); //Method to remove the item from the list at location.
public int retrieveAt(int location); //Method to retrieve the element from the list at location.
public void replaceAt(int location, int repItem); //Method to replace the element in the list at
location with repItem.
public void clearList(); //Method to remove all the elements from the list.
public int search(int searchItem); //Method to determine whether searchItem is in the list.
public void remove(int removeItem); //Method to remove an item from the list.
}
//Class: ArrayListClass implements
//Interface: ArrayListADT
public abstract class ArrayListClass implements ArrayListADT {
protected int length; //to store the length of the list
protected int maxSize; //to store the maximum size of the list
protected int[] list; //array to hold the list elements
//Default constructor
public ArrayListClass() {
maxSize = 100;
length = 0;
list = new int[maxSize];
}
//Alternate Constructor
public ArrayListClass(int size) {
if(size <= 0) {
System.err.println(\"The array size must be positive. Creating an array of size 100.\");
maxSize = 100;
}
else
maxSize = size;
length = 0;
list = new int[maxSize];
}
public boolean isEmpty() {
return (length == 0);
}
public boolean isFull() {
return (length == maxSize);
}
public int listSize() {
return length;
}
public int maxListSize() {
return maxSize;
}
public void print() {
for (int i = 0; i < length; i++)
System.out.print(list[i] + \" \");
System.out.println();
}
public boolean isItemAtEqual(int location, int item) {
if (location < 0 || location >= length) {
System.err.println(\"The location of the item to be compared is out of range.\");
return false;
}
return list[location]== item;
}
public void clearList() {
for (int i = 0; i < length; i++)
list[i] = 0;
length = 0;
System.gc(); //invoke the Java garbage collector
}
public void removeAt(int location) {
if (location < 0 || location >= length)
System.err.println(\"The location of the item to be removed is out of range.\");
else {
for(int i = location; i < length - 1; i++)
list[i] .
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdfformicreation
Assignment is :
\"Page 349-350 #4 and #5 Use the \"Linked List lab\" you have been working on in class and add
the two functions the questions are asking you to develop: divideMid and divideAt. Be sure to
include comments Use meaningful identifier names (constants where appropriate) Do not work
together; no two people should have identical work!?!? Turn in .cpp file AND Turn in a \"print-
screen\' of your output (press \"print-screen\' on keyboard, then \'paste\' in MS-Word)\"
How do you solve QUESTION #5 in the book data structures using c++ by D.S. Malik in Visiual
Studios using the linked list below with what is being asked? Please need help
Linked list :
#include
#include
using namespace std;
struct nodeType
{
int info;
nodeType *link;
};
void createList(nodeType*& first, nodeType*& last);
void printList(nodeType*& first);
void insertFront(nodeType*& first);
void insertBack(nodeType*& last);
void deleteFirst(nodeType*& first);
void deleteLast(nodeType*& last, nodeType* first);
int main()
{
nodeType *first, *last;
int num;
createList(first, last);
int choice;
while(true)
{
cout<<\"1. Insert Front.\ 2. Insert Last.\ 3. Delete Front.\ 4. Delete Last.\ 5. Print List.\ 6. Exit.\
\";
cout<<\"Enter your choice: \";
cin>>choice;
switch(choice)
{
case 1: insertFront(first); break;
case 2: insertBack(last); break;
case 3: deleteFirst(first); break;
case 4: deleteLast(last, first); break;
case 5: printList(first); break;
case 6: return 0;
default: cout<<\"Invalid menu option. Try again.\"<>number;
while (number != -999)
{
newNode = new nodeType; // create new node
newNode->info = number;
newNode->link = NULL;
if (first == NULL)
{
first = newNode;
last = newNode;
}
else
{
last->link = newNode;
last = newNode;
}
cout<<\"Enter an integer (-999 to stop): \";
cin>>number;
} // end of while-loop
} // end of build list function
void deleteFirst(nodeType*& first)
{
nodeType *temp;
temp= first;
first= temp->link;
delete temp;
return;
}
void deleteLast(nodeType*& last, nodeType* current)
{
nodeType *temp;
while(current->link != NULL)
{
temp=current;
current=current->link;
}
temp=last;
current->link=NULL;
delete temp;
last = current;
return;
}
void insertFront(nodeType*& front)
{
int num;
cout<<\"\ Enter the number to insert: \";
cin>>num;
nodeType *newNode = new nodeType;
newNode->info=num;
newNode->link= front;
front= newNode;
return;
}
void insertBack(nodeType*& last)
{
int num;
cout<<\"\ Enter the number to insert: \";
cin>>num;
nodeType *newNode = new nodeType;
newNode->info=num;
newNode->link= NULL;
last->link= newNode;
last = newNode;
return;
}
void printList(nodeType*& first)
{
cout<<\"Inside printList...printing linked list...\ \"<info << \" \";
current = current->link;
}
cout<
#include
using namespace std;
struct nodeType
{
int info;
nodeType *link;
};
void createList(nodeType*& first, nodeType*& last);
void printList(nodeType*& first);
void insertFront(nodeType*& first);
void insertBack(nodeType*& last);
void deleteFirst(nodeType*& first);
void dele.
You are to write an efficient program that will read a dictionary of.pdffortmdu
You are to write an efficient program that will read a dictionary of 100,000 words, and then
check a document of 2,000,000 words. The program should insert into an array the position of
each misspelled word. I have provided the driver program SpellRunner.cpp, and the necessary
class stubs in speller.h, and speller.cpp. You may add any classes and/or code you wish to
speller.cpp, and speller.h. You may also use, and alter any Weiss files. CreateDocs.out creates
files used for testing. Doc-3-4-1 and Dict-3-4-1 are two testing files for small file.
_____________________________________________________________________________
_________________
SpellRunner.cpp
#include
#include
#include
#include
#include
#include \"CPUTimer.h\"
#include \"mynew.h\"
#include \"speller.h\"
// uncomment line below for DOS/Windows OS.
// #define DOS
#ifdef DOS
#include
#else
#include
#endif
extern int maxRAM;
extern int currentRAM;
using namespace std;
char* readDictionary(char *filename, char **dictionary, int dictSize)
{
int fileSize;
char *s;
struct stat statbuf;
stat(filename, &statbuf);
fileSize = statbuf.st_size;
s = new char[fileSize + 1];
ifstream inf(filename);
inf.read(s, fileSize);
inf.close();
s[fileSize] = \'\\0\';
dictionary[0] = strtok(s, \"\ \");
for(int i = 1; i < dictSize; i++)
dictionary[i] = strtok(NULL, \"\ \ \");
return s;
} // readDictionary
char* readDocument(char **document, int dictSize, int docSize, int seed)
{
char *s, filename[80];
int fileSize;
struct stat statbuf;
sprintf(filename, \"Doc-%d-%d-%d.txt\", dictSize, docSize, seed);
stat(filename, &statbuf);
fileSize = statbuf.st_size;
s = new char[fileSize + 100];
ifstream inf(filename);
inf.read(s, fileSize);
inf.close();
s[fileSize] = \'\\0\';
document[0] = strtok(s, \"\ \");
for(int i = 1; i < docSize; i++)
document[i] = strtok(NULL, \"\ \ \");
return s;
} // readDocument()
void readWrongs(int *wrongs, int dictSize, int docSize, int seed,
int &wrongCount)
{
char filename[80];
wrongCount = 0;
sprintf(filename, \"Wrongs-%d-%d-%d.txt\", dictSize, docSize, seed);
ifstream inf(filename);
while(inf >> wrongs[wrongCount++]);
wrongCount--;
} // readWrongs()
void checkAnswers(int wrongs[], int wrongCount, int misspelled[],
int misspelledCount)
{
for(int i = 0; i < wrongCount && i < misspelledCount; i++)
if(wrongs[i] < misspelled[i])
{
cout << \"Speller missed misspelled word # \" << wrongs[i] << endl;
return;
}
else
if(wrongs[i] > misspelled[i])
{
cout << \"Speller thought correctly spelled word # \" << misspelled[i]
<< \" was wrong\ \";
return;
}
if(wrongCount != misspelledCount)
cout << \"Speller found \" << misspelledCount << \" misspelled words when \"
<< \" there were really \" << wrongCount << \" misspelled words.\ \";
} // checkAnswers
void cleanup(char **dictionary, char *docFilePtr, char **document, int *wrongs, int
*misspelled)
{
delete [] dictionary;
delete [] docFilePtr;
delete [] document;
delete [] wrongs;
delete [] misspelled;
} // cleanup()
int main(int argc, char* argv[])
{
char .
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfmohammadirfan136964
Part 1)
#include
#include
#include
#include
/*Error handling for pthread_create and pthread_join*/
/*from the pthread_create man page*/
#define handle_error_en(en, msg) \\
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
/* # of running threads */
volatile int running_threads = 0;
pthread_t thread[3]; /*Descriptors for our 3 threads*/
int numOfElements;/*Total # of elements from the user*/
struct Results{ /*Struct to hold the statistical results*/
int min;
int max;
int average;
}Results;
/*This function finds the minimum element of an array*/
void *findMin(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
Results.min = elements[0]; /*set minimum to first element */
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
if(elements[i] < Results.min){ /*if the current element is less than the current min*/
Results.min = elements[i]; /*store the new min*/
}
}
running_threads -= 1; /*Decrement thread count*/
return NULL;
}
/*This function finds the maximum element of an array*/
void *findMax(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
if(elements[i] > Results.max){ /*store the new max*/
Results.max = elements[i];
}
}
running_threads -= 1; /*Decrement thread count*/
return NULL;
}
/*This function finds the average of an array*/
void *findAverage(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
Results.average += elements[i]; /*add element @ i to average*/
}
Results.average = Results.average/numOfElements; /*Divide the sum by the number of
elements*/
running_threads -= 1; /*Decrement running threads counter*/
return NULL;
}
/* This method accepts a int n(initial size of array) and
pointer to an array and returns # of elements in the array
*/
int getArrayInput(int n, int *array_ptr){
int input;/*Store user input */
int numberOfElements = 0;/*Number of Integers inputed*/
printf(\"Creating Dynamic Array...\ -\ \");
for(;;){ /*infinite loop*/
printf(\"Enter a positive value:\ Negative Number to Stop\ -\ \");
//Get Int from console, store at address of input
if (scanf(\"%d\",&input) != 1){
printf(\"\ Oops that wasn\'t an Integer\ lets try filling the array again\ Remember
INTEGERS only!\ \");
exit(EXIT_FAILURE);
}
if (input >= 0){
if (numberOfElements == n){
n += 1; //Make room for the current input
array_ptr = realloc(array_ptr, n * sizeof(int));//realloc array and set pointer
}
array_ptr[numberOfElements++] = input;//Store input at next empty element
} else {
printf(\"\ Number of Integers: %d\ \", numberOfElements);
break;
}
}
return numberOfElements;
}
/*This function joins our n number of threads */
void joinThreads(int numberOfThreads){
int i; /*count*/
int s; /*error #*/
while(numberOfThreads >= 0){ /*Join our threads*/
s = pthread_jo.
For this lab, you will write the following filesAbstractDataCalc.pdfalokindustries1
For this lab, you will write the following files:
AbstractDataCalc
AverageDataCalc
MaximumDataCalc
MinimumDataCalc
MUST USE ALL 6 FILES PROVIDED
AbstractDataCalc is an abstract class, that AverageDataCalc, MaximumDataCalc and
MinimumDataCalc all inherit.
The following files are provided
CSVReader
To help read CSV Files.
DataSet
This file uses CSVReader to read the data into a List> type structure. Think of this as a Matrix
using ArrayLists. The important methods for you are rowCount() and getRow(int i) - Between
CSVReader and DataSet - all your data is loaded for you!
Main
This contains a public static void String[] args. You are very free to completely change this main
(and you should!). We don't test your main, but instead your methods directly. However, it will
give you an idea of how the following output is generated.
Sample Input / Output
Given the following CSV file
The output of the provided main is:
Note: the extra line between Set results is optional and not graded. All other spacing must be
exact!
Specifications
You will need to implement the following methods at a minimum. You are free to add additional
methods.
AbstractDataCalc
public AbstractDataCalc(DataSet set) - Your constructor that sets your dataset to an instance
variable, and runCalculations() based on the dataset if the passed in set is not null. (hint: call
setAndRun)
public void setAndRun(DataSet set) - sets the DataSet to an instance variable, and if the passed
in value is not null, runCalculations on that data
private void runCalculations() - as this is private, technically it is optional, but you are going to
want it (as compared to putting it all in setAndRun). This builds an array (or list) of doubles,
with an item for each row in the dataset. The item is the result returned from calcLine.
public String toString() - Override toString, so it generates the format seen above. Method is the
type returned from get type, row counting is the more human readable - starting at 1, instead of
0.
public abstract String getType() - see below
public abstract double calcLine(List line) - see below
AverageDataCalc
Extends AbstractDataCalc. Will implement the required constructor and abstract methods only.
public abstract String getType() - The type returned is "AVERAGE"
public abstract double calcLine(List line) - runs through all items in the line and returns the
average value (sum / count).
MaximumDataCalc
Extends AbstractDataCalc. Will implement the required constructor and abstract methods only.
public abstract String getType() - The type returned is "MAX"
public abstract double calcLine(List line) - runs through all items, returning the largest item in
the list.
MinimumDataCalc
Extends AbstractDataCalc. Will implement the required constructor and abstract methods only.
public abstract String getType() - The type returned is "MIN"
public abstract double calcLine(List line) - runs through all items, returning the smallest item in
the list.
MaximumDataCalc.java------ write code .
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.
This is the user guide for the quantum simulator I have developed. It includes tutorials on advanced quantum mechanics, quantum algorithms and geometric algebra, together with examples of using the simulator do quantum mechanics, Special Relativity, geometric algebra and quantum computing.
O(n) in time, O(1) in space substr-search algorithm, using O(1)-updatable hash derived using Group Theory. Hash function is greyed out, to prevent IP-theft. Algorithm is far simpler than trie or Knuth-Morris-Pratt. Very surprised it has not been discovered by others.
O(n) in time, O(1) in space substr-search algorithm, using O(1)-updatable hash derived using Group Theory. Hash function is greyed out, to prevent IP-theft. Algorithm is far simpler than trie or Knuth-Morris-Pratt. Very surprised it has not been discovered by others.
O(n) in time, O(1) in space substr-search algorithm, using O(1)-updatable hash derived using Group Theory. Hash function is greyed out, to prevent IP-theft. Algorithm is far simpler than trie or Knuth-Morris-Pratt. Very surprised it has not been discovered by others.
An O(n+m) in time and O(1) in space search-algorithm for substr, length m, in target string, length n. Simpler than trie or Knuth-Morris-Pratt. Can be reduced to O(n) using Group Theoretic O(1)-updatable hash that replaces the cumulative sum, which requires an O(m) verification step because "+" is commutative and cannot distinguish between anagrams: a+b+c = a+c+b = c+a+b etc. I am not uploading the hash, because it means giving away R&D I do in quantum simulations.
This is a roughly O(n) algorithm that generates the kth lexicographically ordered permutation of an n-element array from the integer k. Example, for a three-element
array:
0 --> 0 1 2
1 --> 0 2 1
2 --> 1 0 2
3 --> 1 2 0
4 --> 2 0 1
5 --> 2 1 0
This is a roughly O(n) algorithm that generates the kth lexicographically ordered permutation of an n-element array from the integer k. Example, for a three-element array:
0 --> 0 1 2
1 --> 0 2 1
2 --> 1 0 2
3 --> 1 2 0
4 --> 2 0 1
5 --> 2 1 0
UML design for C++11 written to solve a problem at interview, please also see "Interview C++11 code". The UML design can be zoomed to render it more legible.
Example of Dynamic Programming to achieve O(n).
Interview question: N houses, each with weighting on value of goods. How can a burglar maximise profit if they are not allowed to visit neighbouring houses?
Solution: optimum(i) = max( optimum(i-1)-w(i-1)+w(i) , optimum(i-2)+w(i) )
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
Shared_memory_hash_table
1. /**
* @mainpage
* @anchor mainpage
* @brief
* @details
* @copyright Russell John Childs, PhD, 2017
* @author Russell John Childs, PhD
* @date 2017-02-26
*
* This file contains classes: SharedMemoryHashTable
*
* SharedMemoryHashTable implements a hash table using shared memory instead of
* heap memory. Two blocks of shared memory are created. The first is for the
* buckets. The second is "heap memory" for the linked list nodes that hold hash
* collisions. Each node contains a "next pointer" that holds the array index
* into the second block where the next node in the linked list resides. A C++
* placement new is used to initialise each node in shared memory. A simple
* memory management model is used for new/delete on Shared Memory involving a
* linked list of free memory slots that may be pushed and popped.
*
* Currently, only a subset of the interface for std::unordered_set/map is
* offered (insertions+deletions). In a future release, STL Allocators will be
* implemented that allow Shared Memory to be used for STL container classes.
*
* Compiled and tested under Linux Mint, using g++ 4.8.
*
* g++ options: -O0 -g3 -Wall -O0 -fopenmp -mavx -m64 -g -Wall -c
* -fmessage-length=0 -fno-omit-frame-pointer --fast-math
* -std=c++11 -I/opt/intel/vtune_amplifier_xe_2013/include/
*
* Linker options: -Wl,--no-as-needed -fopenmp
* -L/opt/intel/vtune_amplifier_xe_2013/lib64/
*
* Cmd line options: -lpthread -latomic -littnotify -ldl -lrt
*
* Documentation: Doxygen comments for interfaces, normal for impl.
*
* @file shared_memory_hash_table.cpp
* @see
* @ref mainpage
*/
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <iostream>
#include <string>
#include <functional>
/**
* addtogroup SharedMemoryContainers
* @{
*/
namespace SharedMemoryContainers
{
/**
* This class implements a hash table using shared memory instead of
* heap memory. Two blocks of shared memory are created. The first is for the
* buckets. The second is "heap memory" for the linked list nodes that hold hash
* collisions. Each node contains a "next pointer" that holds the array index
* into the second block where the next node in the linked list resides. A C++
* placement new is used to initialise each node in shared memory. A simple
2. * memory management model is used for new/delete on Shared Memory involving a
* linked list of free memory slots that may be pushed and popped.
*
* Currently, only a subset of the interface for std::unordered_set/map is
* offered (insertions+deletions). In a future release, STL Allocators will be
* implemented that allow Shared Memory to be used for STL container classes.
*
* Notes: The user type T must provide:
*
* (1) A default ctor
*
* (2) operator std::string(void) that returns a unique ID as an std::string of
* the form "/key" where key is some set of chars excluding '/'.
*
* @tparam T - The type of the item to be stored in hash map.
* @tparam Size - The number of buckets.
* @tparam NumItems - Number of items to be stored.
*
*/
template<typename T,unsigned Size,unsigned NumItems> class SharedMemoryHashTable
{
public:
/**
* Creates or accesses hash table in shared memory
*
* @param init {bool = false} - true iff hash table is being created, false
* if it already exists and is being accessed by a process.
*
* @param key {const std::string&="/shared_memory_hash_table"} - unique key
* for the shared memory of the form "/key" where key is some set of chars
* excluding '/'.
*
*/
SharedMemoryHashTable(
bool init = false, const std::string& key="/shared_memory_hash_table") :
m_key(key.c_str()),
m_buckets(0),
m_shared(0),
m_free(0)
{
//Shared memory for buckets
auto size = sizeof(unsigned)*Size;
auto shmid = shm_open(key.c_str(), O_CREAT | O_RDWR, 0666);
if(errno!=0) perror("shm_open: ");
ftruncate(shmid,size);
auto prot = PROT_READ | PROT_WRITE;
m_buckets=
static_cast<unsigned*>(mmap(0,size,prot,MAP_SHARED,shmid,0));
if(init) for(unsigned i=0; i<Size; ++i) m_buckets[i]=0;
close(shmid);
//Shared memory for linked list nodes
size = sizeof(LinkedList)*(NumItems+1);
shmid = shm_open((key+"nodes").c_str(), O_CREAT | O_RDWR, 0666);
if(errno!=0) perror("shm_open: ");
ftruncate(shmid,size);
m_shared=static_cast<LinkedList*>(mmap(0,size,prot,MAP_SHARED,shmid,0));
//Stored "ptr" to free memory in m_shared[0] so all processes see it
m_free = &m_shared->m_next;
close(shmid);
//Create "heap" of free memory (linked list of free slots)
if(init)
{
for(unsigned i=1; i <= NumItems; ++i)
{
3. (m_shared+*m_free)->m_next = i;
*m_free = i;
}
m_free = &(m_shared->m_next=1);
}
}
/**
* Detach shared memory associated with this hash table
*/
~SharedMemoryHashTable(void)
{
munmap(m_shared, NumItems*sizeof(LinkedList));
munmap(m_buckets, sizeof(unsigned)*Size);
shm_unlink(m_key.c_str());
shm_unlink((m_key+"nodes").c_str());
}
/**
* This class provides the linked list for hash collisions.
*
*/
struct LinkedList
{
T m_data;
unsigned m_next;
/**
* @param data {const T&} - item to be placed in linked list node
*/
LinkedList(const T& data = T()) :
m_data(data),
m_next(0)
{
}
/**
* Dtor
*/
~LinkedList(void)
{
}
};
/**
* @param key {const std::string&} - unique item id to be searched for
*
* @return T* - reference to item with specified id or NULL if not found
*
*/
T* find(const std::string& key)
{
T* ret_val = 0;
//Convert key to bucket array index
auto index = std::hash<std::string>{}(key)%Size;
//Search for key
auto next = m_buckets[index];
while( next != 0 && ret_val==0)
{
//If key found ...
if(std::string((m_shared+next)->m_data)==key)
{
//Return value = found item
4. ret_val = &(m_shared+next)->m_data;
}
//Keep traversing linked list
next=(m_shared+next)->m_next;
}
return ret_val;
}
/**
* @param key {const std::string&} - unique item id
*
* @param in {const T&} - item to be inserted
*
* @return std::pair<T*, bool> - {existing_item_address, false} iff item
* already exists, {inserted_item_address, true} if item does not exist
*
*/
std::pair<T*, bool> insert(const std::string& key, const T& in)
{
//Get item if it exists, or NULL
T* ret_val = find(key);
bool is_success = false;
//If item does not exist, create it on the Shared Memory "heap"
if(ret_val==0)
{
//Convert key to bucket array index
auto index = std::hash<std::string>{}(key)%Size;
//Create new linked list node and return reference to stored item
unsigned free_slot = *m_free;
*m_free = (m_shared+*m_free)->m_next;
LinkedList* linked_list =new(m_shared+free_slot) LinkedList(in);
linked_list->m_next=m_buckets[index];
m_buckets[index]=free_slot;
//new item and success
ret_val = &linked_list->m_data;
is_success = true;
}
return std::make_pair(ret_val, is_success);
}
/**
* @param key {const std::string&} - unique item id
*
* @return T& - reference to item with specified id
*
*/
T& operator[](const std::string& key)
{
return *insert(key, T()).first;
}
/**
* @param key {const std::string&} - unique item id
*
* @param in {const T&} - item to be inserted
*
* @return std::pair<T*, bool> - {existing_item_address, false} iff item
* already exists, {inserted_item_address, true} if item does not exist
*
*/
void erase(const std::string& key)
{
//Convert key to bucket array index
auto index = std::hash<std::string>{}(key)%Size;
5. //Search for key
auto prev = m_buckets[index];
auto next = prev;
while( next != 0 )
{
//If key found ...
if(std::string((m_shared+next)->m_data)==key)
{
//delete found item
if(prev==m_buckets[index]) m_buckets[index] =
((m_shared+prev)->m_next=(m_shared+next)->m_next);
(m_shared+next)->m_next = *m_free;
*m_free = next;
}
//Keep traversing linked list
prev = next;
next=(m_shared+next)->m_next;
}
}
private:
std::string m_key;
unsigned* m_buckets;
LinkedList* m_shared;
unsigned* m_free;
};
}
/**
* @}
*/
int main(void)
{
using namespace SharedMemoryContainers;
//Raw Data
struct RawData
{
unsigned m_user_id;
unsigned m_dest_id;
std::string m_branch;
operator std::string(void)
{
return std::string(m_branch);
}
};
//Create a 100-bucket hash table
const int buckets = 100;
const int items = 5;
typedef SharedMemoryHashTable<RawData, buckets, items> Table;
Table shared_memory_hash_table(true);
//Parent process
unsigned user_id = 0;
unsigned dest_id = 1000;
//Insert values into shared memory hash table
std::cout << "=====================================" << std::endl;
std::cout << "Inserting values via parent process" << std::endl;
//Loop over keys
for(std::string str : {"a", "bb", "ccc", "dddd", "eeeee"})