Question

In: Computer Science

Develop and pseudocode for the code below: #include <algorithm> #include <iostream> #include <time.h> #include "CSVparser.hpp" using...

Develop and pseudocode for the code below:

#include <algorithm>
#include <iostream>
#include <time.h>

#include "CSVparser.hpp"

using namespace std;

//============================================================================
// Global definitions visible to all methods and classes
//============================================================================

// forward declarations
double strToDouble(string str, char ch);

// define a structure to hold bid information
struct Bid {
string bidId; // unique identifier
string title;
string fund;
double amount;
Bid() {
amount = 0.0;
}
};

//============================================================================
// Static methods used for testing
//============================================================================

/**
* Display the bid information to the console (std::out)
*
* @param bid struct containing the bid info
*/
void displayBid(Bid bid) {
cout << bid.bidId << ": " << bid.title << " | " << bid.amount << " | "
<< bid.fund << endl;
return;
}

/**
* Prompt user for bid information using console (std::in)
*
* @return Bid struct containing the bid info
*/
Bid getBid() {
Bid bid;

cout << "Enter Id: ";
cin.ignore();
getline(cin, bid.bidId);

cout << "Enter title: ";
getline(cin, bid.title);

cout << "Enter fund: ";
cin >> bid.fund;

cout << "Enter amount: ";
cin.ignore();
string strAmount;
getline(cin, strAmount);
bid.amount = strToDouble(strAmount, '$');

return bid;
}

/**
* Load a CSV file containing bids into a container
*
* @param csvPath the path to the CSV file to load
* @return a container holding all the bids read
*/
vector<Bid> loadBids(string csvPath) {
cout << "Loading CSV file " << csvPath << endl;

// Define a vector data structure to hold a collection of bids.
vector<Bid> bids;

// initialize the CSV Parser using the given path
csv::Parser file = csv::Parser(csvPath);

try {
// loop to read rows of a CSV file
for (int i = 0; i < file.rowCount(); i++) {

// Create a data structure and add to the collection of bids
Bid bid;
bid.bidId = file[i][1];
bid.title = file[i][0];
bid.fund = file[i][8];
bid.amount = strToDouble(file[i][4], '$');

//cout << "Item: " << bid.title << ", Fund: " << bid.fund << ", Amount: " << bid.amount << endl;

// push this bid to the end
bids.push_back(bid);
}
} catch (csv::Error &e) {
std::cerr << e.what() << std::endl;
}
return bids;
}

// FIXME (2a): Implement the quick sort logic over bid.title

/**
* Partition the vector of bids into two parts, low and high
*
* @param bids Address of the vector<Bid> instance to be partitioned
* @param begin Beginning index to partition
* @param end Ending index to partition
*/
int partition(vector<Bid>& bids, int begin, int end) {

int l = begin;
int h = end;


int pivot = (begin + (end - begin) / 2);
bool finished = false;

// this while loops continually increments the low point as long as it's below the pivot
// then continually decrements the high point as long as it's above the pivot
while(!finished) {

while(bids[l].title.compare(bids[pivot].title) < 0) {
++l;
}

while(bids[pivot].title.compare(bids[h].title) < 0) {
--h;
}

if (l >= h) {
finished = true;
// if variable l is not greater than or equal to h the two bids are swapped
} else {
swap(bids[l] , bids[h]);


//bring end points closer to one another

++l;
--h;
}
}
return h;
}

/**
* Perform a quick sort on bid title
* Average performance: O(n log(n))
* Worst case performance O(n^2))
*
* @param bids address of the vector<Bid> instance to be sorted
* @param begin the beginning index to sort on
* @param end the ending index to sort on
*/
void quickSort(vector<Bid>& bids, int begin, int end) {
}

// FIXME (1a): Implement the selection sort logic over bid.title

/**
* Perform a selection sort on bid title
* Average performance: O(n^2))
* Worst case performance O(n^2))
*
* @param bid address of the vector<Bid>
* instance to be sorted
*/
void selectionSort(vector<Bid>& bids) {
// this creates an index to the smallest minimum bid found
unsigned int smallest;
unsigned int largest = bids.size();

// place designates the position at which bids are sorted/unsorted
for (unsigned place = 0; place < largest; ++place) {
smallest = place;

for (unsigned j = place + 1; j < largest; ++j) {
if (bids[j].title.compare(bids[smallest].title) < 0) {
smallest = j;
}
}

if (smallest != place)
swap(bids[place], bids[smallest]);
}

}

/**
* Simple C function to convert a string to a double
* after stripping out unwanted char
*
* credit: http://stackoverflow.com/a/24875936
*
* @param ch The character to strip out
*/
double strToDouble(string str, char ch) {
str.erase(remove(str.begin(), str.end(), ch), str.end());
return atof(str.c_str());
}

/**
* The one and only main() method
*/
int main(int argc, char* argv[]) {

// process command line arguments
string csvPath;
switch (argc) {
case 2:
csvPath = argv[1];
break;
default:
csvPath = "eBid_Monthly_Sales_Dec_2016.csv";
}

// Define a vector to hold all the bids
vector<Bid> bids;

// Define a timer variable
clock_t ticks;

int choice = 0;
while (choice != 9) {
cout << "Menu:" << endl;
cout << " 1. Load Bids" << endl;
cout << " 2. Display All Bids" << endl;
cout << " 3. Selection Sort All Bids" << endl;
cout << " 4. Quick Sort All Bids" << endl;
cout << " 9. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;

switch (choice) {

case 1:
// Initialize a timer variable before loading bids
ticks = clock();

// Complete the method call to load the bids
bids = loadBids(csvPath);

cout << bids.size() << " bids read" << endl;

// Calculate elapsed time and display result
ticks = clock() - ticks; // current clock ticks minus starting clock ticks
cout << "time: " << ticks << " clock ticks" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;

break;

case 2:
// Loop and display the bids read
for (int i = 0; i < bids.size(); ++i) {
displayBid(bids[i]);
}
cout << endl;

break;

// FIXME (1b): Invoke the selection sort and report timing results
    ticks = clock();

// call selectionSort method to sort the loaded bids
selectionSort(bids);

cout << bids.size() << " bids read" << endl;

// Calculate elapsed time and display result
ticks = clock() - ticks; // current clock ticks minus starting clock ticks
cout << "time: " << ticks << " clock ticks" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;

break;

// FIXME (2b): Invoke the quick sort and report timing results

   ticks = clock();

// call quickSort method to sort the loaded bids
quickSort(bids, 0, bids.size() - 1);

cout << bids.size() << " bids read" << endl;

// Calculate elapsed time and display result
ticks = clock() - ticks; // current clock ticks minus starting clock ticks
cout << "time: " << ticks << " clock ticks" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;

break;

}

cout << "Good bye." << endl;

return 0;
}

Solutions

Expert Solution

Start

Define a Structure to declare variable bidId as string, title as string, fund as string, amount as double.

Set amount=0.0

Display the whole Structure.

Take input from user for bidId, title, fund, amount.

Display the values of bidId, title, fund, amount.

Load CSV file using CSV path.

Define a vector data structure using the given CSV path.

Initialize the CSV parser using the given CSV path.

For i from 0 to (no. of rows in the file)

Declare a variable bid.

Set bid.bidId=file[i][1],

bid.title=file[i][0],

bid.fund=file[i][8],

bid.amount=strToDouble(file[i][4], 'S').

Display Item by bid.title, Fund by bid.fund, Amount by bid.amount.

Push the bid to the end.

End for.

Partition the vector of bids into two parts, low and high.

Set low= begin,

high= end.

Calculate the Pivot element by

pivot=(begin + ( end - begin)/2)

Set finished= false.

While there is no finished

compare title<0

increment low by 1.

decrement high by 1.

End while.

If low>=high

Set finished = true.

Else

increment low by 1.

decrement high by 1.

End if.

Return high.

Perform Quick sort on bid.title.

Perform Selection sort on bid.title.

Declare variable smallest and largest as unsigned int, and place and j as unsigned.

Store the bid.size() in largest.

For place from 0 to largest

Set smallest = place.

For j from (place + 1) to largest

If smallest<0

Set smallest = j.

End if.

End for.

If smallest not equals to place

Swap place and smallest

End if.

End for.

End Selection sort.

Convert a string to a double.

Return the string.

Define  main method.

Declare csvPath as string.

Use a Switch case on argc

case1: csvPath = argv[1]

default: show message.

End switch case.

Define a vector to hold all the bids.

Define a timer variable ticks as clock_t.

Set an integer variable choice.

Set choice = 0.

While choice not equals to 9

Print Menu.

Print Option1: Load bids.

Print Option2: Display All Bids.

Print Option3: Selection sort all bids.

Print Option4: Quick sort all bids.

Print Option9:exit.

Take input from user for the variable choice.

Apply Switch case on choice

case1: set timer variable as ticks = clock()

complete the method call to load the bids.

display the size of the bids.

calculate ticks = clock() - ticks

display time in clock ticks.

display time in seconds.

case2: for i from 0 to bids.size

display bids[i].

end for.

call Selection sort function.

display bids.size.

calculate elapsed time ticks = clock() - ticks.

display time in clock ticks.

display time in seconds.

End of Switch case.

Display "good bye" message.

End.


Related Solutions

Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell {...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell { int val; Cell *next; }; int main() { int MAX = 10; Cell *c = NULL; Cell *HEAD = NULL; srand (time(NULL)); for (int i=0; i<MAX; i++) { // Use dynamic memory allocation to create a new Cell then initialize the // cell value (val) to rand(). Set the next pointer to the HEAD and // then update HEAD. } print_cells(HEAD); }
C++ CODE ONLY Using the following code. #include <iostream> #include <string> #include <climits> #include <algorithm> using...
C++ CODE ONLY Using the following code. #include <iostream> #include <string> #include <climits> #include <algorithm> using namespace std; // M x N matrix #define M 5 #define N 5 // Naive recursive function to find the minimum cost to reach // cell (m, n) from cell (0, 0) int findMinCost(int cost[M][N], int m, int n) {    // base case    if (n == 0 || m == 0)        return INT_MAX;    // if we're at first cell...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char plain[50], cipher[50]="", decrypt[50]=""; int subkeys[50], len;       cout<<"Enter the plain text:"<<endl; cin>>plain;    cout<<"Enter the first subkey:"<<endl; cin>>subkeys[0];    _strupr(plain);    len = strlen(plain);    /**********Find the subkeys**************/    for(int i=1; i<len; i++) { if ((plain[i-1]>='A') && (plain[i-1]<='Z')) { subkeys[i] = plain[i-1]-65; } }    /****************ENCRYPTION***************/       for(int i=0; i<len; i++) { if ((plain[i]>='A') && (plain[i]<='Z')) {    cipher[i] = (((plain[i]-65)+subkeys[i])%26)+65; }...
Please write variables and program plan(pseudocode) of this C++ programming code: #include <iostream> using namespace std;...
Please write variables and program plan(pseudocode) of this C++ programming code: #include <iostream> using namespace std; void leapYear(int x); int main() { int x; cout << "Enter a year: "; cin >> x; leapYear (x);   return 0; } void leapYear(int x ) {    if (x % 400 == 0)    {    cout << "This is a leap Year";}    else if    ((x % 4 == 0) && (x % 100 != 0))    {    cout <<...
C++ code Why my code is not compiling? :( #include <iostream> #include <iomanip> #include <string> using...
C++ code Why my code is not compiling? :( #include <iostream> #include <iomanip> #include <string> using namespace std; const int CWIDTH = 26; int main() {    int choice;    double convertFoC, converCtoF;    double starting, endvalue, incrementvalue;    const int CWIDTH = 13;    do {       cin >> choice;    switch (choice)    {        cin >> starting;    if (starting == 28){       cout << "Invalid range. Try again.";    }    while (!(cin >> starting)){       string  garbage;       cin.clear();       getline(cin, garbage);       cout << "Invalid data Type, must be a number....
Please use C++, linked list and Bubble Sort to slove this problem. #include <iostream> #include <time.h>...
Please use C++, linked list and Bubble Sort to slove this problem. #include <iostream> #include <time.h> using namespace std; struct ListNode { int data; ListNode *next; ListNode(int x) : data(x), next(nullptr) {} }; class LinkedList { private: ListNode *head = nullptr; public: void addNode(int x) { ListNode *p = new ListNode(x); if (head == nullptr) head = p; else { ListNode *q = head; while (q->next != nullptr) q = q->next; q->next = p; } } void display() { ListNode...
Using the pseudocode found below, write only the actual (C++) code for this program. Include all...
Using the pseudocode found below, write only the actual (C++) code for this program. Include all libraries. Specification: Write a program that will repeatedly ask the user for quiz grades in the range from 0 to 20. Any negative value will act as a sentinel. When the sentinel is entered compute the average of the grades entered. Design: Constants None Variables float grade float total = 0 int count = 0 float average ------- Inital Algorithm Repeatedly ask user for...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; //...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; // constants const int FINAL_POSITION = 43; const int INITIAL_POSITION = -1; const int NUM_PLAYERS = 2; const string BLUE = "BLUE"; const string GREEN = "GREEN"; const string ORANGE = "ORANGE"; const string PURPLE = "PURPLE"; const string RED = "RED"; const string YELLOW = "YELLOW"; const string COLORS [] = {BLUE, GREEN, ORANGE, PURPLE, RED, YELLOW}; const int NUM_COLORS = 6; // names...
PLEASE SOLVE THIS QUESTION WITHOUT CHANGING THE SOURCE CODE POSTED BELOW. (ONLY ADDING) #include <iostream> using...
PLEASE SOLVE THIS QUESTION WITHOUT CHANGING THE SOURCE CODE POSTED BELOW. (ONLY ADDING) #include <iostream> using namespace std; const int arrSize = 3; // QUESTION ii. COMPLETE A displayMatrix(...) FUNCTION HERE // QUESTION iii. COMPLETE A transposedMatrix(...) FUNCTION HERE // QUESTION iv. COMPLETE A calculateTotal(...) FUNCTION HERE int main(){ // variable declaration int mat[arrSize][arrSize], transMat[arrSize][arrSize] = {0}, total = 0; // QUESTION i. Prompt user to enter 9 integer numbers and fill in into the matrix cout << "\nThe original...
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace...
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace std; AVLTree::AVLTree() { root = NULL; } AVLTree::~AVLTree() { delete root; root = NULL; } // insert finds a position for x in the tree and places it there, rebalancing // as necessary. void AVLTree::insert(const string& x) { // YOUR IMPLEMENTATION GOES HERE } // remove finds x's position in the tree and removes it, rebalancing as // necessary. void AVLTree::remove(const string& x) {...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT