Loading...
More C++ Posts
using namespace std;class Hash{int BUCKET; // No. of buckets// Pointer to an array containing bucketslist<int> *table;public:Hash(int V); // Constructor// inserts a key into hash tablevoid insertItem(int x);// deletes a key from hash tablevoid deleteItem(int key);// hash function to map values to keyint hashFunction(int x) {return (x % BUCKET);}void displayHash();};Hash::Hash(int b){this->BUCKET = b;table = new list<int>[BUCKET];}void Hash::insertItem(int key){int index = hashFunction(key);table[index].push_back(key);}void Hash::deleteItem(int key){// get the hash index of keyint index = hashFunction(key);// find the key in (inex)th listlist <int> :: iterator i;for (i = table[index].begin();i != table[index].end(); i++) {if (*i == key)break;}// if key is found in hash table, remove itif (i != table[index].end())table[index].erase(i);}// function to display hash tablevoid Hash::displayHash() {for (int i = 0; i < BUCKET; i++) {cout << i;for (auto x : table[i])cout << " --> " << x;cout << endl;}}// Driver programint main(){// array that contains keys to be mappedint a[] = {15, 11, 27, 8, 12};int n = sizeof(a)/sizeof(a[0]);// insert the keys into the hash tableHash h(7); // 7 is count of buckets in// hash tablefor (int i = 0; i < n; i++)h.insertItem(a[i]);// delete 12 from hash tableh.deleteItem(12);// display the Hash tableh.displayHash();return 0;}
//Get data file at https://codecatch.net/post.php?postID=91e87d73//Iteration 1 of Wing Project. Solution breaks down around n=35#include <iostream>#include <fstream>#include <string>#include <vector>#include <map>using namespace std;int getSum(map<int, int> list);void readData(map<int, float>* data);void lowestPrice();void findSums(int n, vector<map<int, int>>* sumsList, map<int, float>* data);//void findSum(map<int, int> currList, int x, int n, vector<map<int, int>>* sumsList);void findSum(map<int, int> currList, int x, int n, vector<map<int, int>>* sumsList, map<int, float>* data);float getPrice(map<int, int> set, map<int, float>* data);template <typename S>ostream& operator<<(ostream& os, const vector<S>& vector){// Printing all the elements using <<for (auto element : vector) {os << element << " ";}return os;}bool operator==(map<int, int> m1, map<int, int> m2){if(m1.size() != m2.size())return false;bool ret = true;for(auto it = m1.begin(); it !=m1.end() && ret; it++){if(ret && m1.count(it->first) != m2.count(it->first))ret = false;if(ret && m1.count(it->first) == 1){if(m1.at(it->first) != m2.at(it->first))ret = false;}}return ret;}int main(){map<int, float> data;readData(&data);vector<map<int, int>> *sumsList;sumsList = new vector<map<int, int>>;findSums(40, sumsList, &data);for(auto el : *sumsList){for(auto it = el.begin(); it != el.end(); it++){cout << it->first << "->" << it->second << " ";}cout << getPrice(el, &data) << endl;}return 0;}/* Returns the price of wings given a set of numbers of wings to buy.* Returns -1 if the set contains a number that is not possible to buy.*/float getPrice(map<int, int> set, map<int, float>* data){float price = 0;for(auto it = set.begin(); it != set.end(); it++){//If data doesn't contain an element of set, return -1if(data->count(it->first) == 0)return -1;price += data->at(it->first) * it->second; //pricePerPacket * qtyOfPackets}return price;}/* Adds the elements of list.* Suppose mapping is <num, qty>.* Returns sum(num*qty)*/int getSum(map<int, int> list){int sum = 0;for(auto it = list.begin(); it != list.end(); it++)sum += it->first * it->second;return sum;}void findSums(int n, vector<map<int, int>>* sumsList, map<int, float>* data){map<int, int> currList;//Recur when currSum < nauto it = data->begin();while(it->first <= n && it != data->end()){findSum(currList, it->first, n, sumsList, data);it++;}}void findSum(map<int, int> currList, int x, int n, vector<map<int, int>>* sumsList, map<int, float>* data){//Append x to currListif(currList.count(x) == 0)currList.emplace(x, 1);else{int val = 1+ currList.at(x);currList.erase(x);currList.emplace(x, val);}//Determine current sum, check for return casesint currSum = getSum(currList);if(currSum > n)return;else if(currSum == n){//Check to make sure no duplicatesfor(auto list : *sumsList){if(list == currList)return;}sumsList->push_back(currList);return;}//Recur when currSum < nauto it = data->begin();while(it->first <= n-x && it != data->end()){findSum(currList, it->first, n, sumsList, data);it++;}}void readData(map<int, float>* data){ifstream file ("./data", ifstream::in);if(file.is_open()){int i = 0;while(!file.eof()){float wings, price;string skipnl;file >> wings;file >> price;data->emplace(wings, price);getline(file, skipnl);i++;}}}
#include<iostream>using namespace std;const int rows = 8;const int cols = 8;char chessboard[rows][cols];void setBoard(char chessboard[][cols]);void printBoard(char chessboard[][cols]);void setBoard(char chessboard[][cols]) {for(int i = 0; i < rows; i++) {for(int j = 0; j < cols; j++) {if(i % 2 == 0 && j % 2 == 0) {chessboard[i][j] = 'x';} else {if(i % 2 != 0 && j % 2 == 1) {chessboard[i][j] = 'x';} else {chessboard[i][j] = '-';}}}}return;}void printBoard(char chessboard[][cols]) {for(int i = 0; i < rows; i++) {for(int j = 0; j < cols; j++) {cout << chessboard[i][j] << " ";}cout << endl;}return;}int main(int argc, char const *argv[]){setBoard(chessboard);printBoard(chessboard);return 0;}
/*this program will simulate the spreading of a disease through agrid of people, starting from a user-defined person. It will countthe number of turns taken before everyone on the grid is immunizedto the disease after having caught it once.This program will user the SIR model (Susceptible, Infectious, Recovered)and cellular automata to simulate the people in the grid.*/#include <iostream>using namespace std;/* Any and all global variables */const int SIZE = 8; //Size of the square person array/* Any and all functions */void gridDefaultify(char[][SIZE], int);//Purpose: Sets each item in the person array to 's'//Parameters: A square, two-dimensional array// The size of that array's boundsvoid gridDisplay(char[][SIZE], int);//Purpose: Formats and prints the information in the person grid//Parameters: A square, two-dimensional array// The value of the current dayvoid nextTurn(char[][SIZE], char[][SIZE], int&);//Purpose: Updates the grid of people, and the current day//Parameters: Two square, two-dimensional arrays// A reference to the current day (so that it can be updated)int countInfected(char[][SIZE], int);//Purpose: Counts the number of infectious people on the grid//Parameters: A square, two-dimensional array// The size of that array's boundsint main(){int currentDay = 0; //Infection begins on day 0, and ends one day after the last person is Recoveredchar gridCurrent[SIZE][SIZE]; //Grid of all peoplechar gridUpdate[SIZE][SIZE]; //Where the user chooses to start the infectionint xToInfect;int yToInfect; //Set of coordinates for the initial infection position, given by user//Initializes the grids to all 's'gridDefaultify(gridCurrent, SIZE);gridDefaultify(gridUpdate, SIZE);//The below block gets the initial infection coordinates from the usercout << "Please enter a location to infect: ";while(true){cin >> xToInfect >> yToInfect;xToInfect--;yToInfect--;if(xToInfect < 0 || yToInfect < 0 || xToInfect >= SIZE || yToInfect >= SIZE){cout << "Those coordinates are outside the bounds of this region." << endl;cout << "Please enter another location to infect: ";continue;} else {gridCurrent[xToInfect][yToInfect] = 'i';break;}}//Displays the initial state of the gridgridDisplay(gridCurrent, currentDay);//The below block will display and update the grid until the infection is done.while(true){nextTurn(gridCurrent, gridUpdate, currentDay);gridDisplay(gridCurrent, currentDay);if(countInfected(gridCurrent, SIZE) == 0) break; //Once there are no more infected, the game is done}//Displays the number of days taken for the infection to endcout << "It took " << currentDay + 1 << " days for the outbreak to end";cout << endl;return 0;}void gridDefaultify(char arr[][SIZE], int arrSize){for(int x = 0; x < arrSize; x++){for(int y = 0; y < arrSize; y++){arr[x][y] = 's'; //Sets all items in the passed-in array to 's'}}return;}void gridDisplay(char arr[][SIZE], int day){cout << "Day " << day << endl; //Prints the current dayfor(int x = 0; x < SIZE; x++){for(int y = 0; y < SIZE; y++){cout << arr[x][y] <<" "; //Prints the array's contents}cout << endl; //Formats with newlines}cout << endl; //Some spacingreturn;}void nextTurn(char today[][SIZE], char update[][SIZE], int& day){day++; //Updates the dayint xCheck; //X coordinate to be checkedint yCheck; //Y coordinate to be checkedfor(int x = 0; x < SIZE; x++){for(int y = 0; y < SIZE; y++){//Sets all 'i' to 'r' in the new gridif(today[x][y] == 'i' || today[x][y] == 'r'){update[x][y] = 'r'; //Updates all infectious to recovered, and keeps current recovered}if(today[x][y] == 's'){ // If the person is susceptible...for(int xCheck = x-1; xCheck <= x+1; xCheck++){ // Check all x coordinates around the personfor(int yCheck = y-1; yCheck <= y+1; yCheck++){ // Check all y coordinates around the personif(xCheck == x && yCheck == y){// Don't check at the person because there is no need to check there} else {if(xCheck >= 0 && yCheck >= 0 && xCheck < SIZE && yCheck < SIZE){ // Make sure the checked coordinates are in boundsif(today[xCheck][yCheck] == 'i'){ //Is the person at the checked coordinates infected?update[x][y] = 'i'; //If so, update the 's' to 'i' in the new grid}}}}}}}}for(int x = 0; x < SIZE; x++){for(int y = 0; y < SIZE; y++){today[x][y] = update[x][y]; //Updates today's grid with the new values}}}int countInfected(char arr[][SIZE], int arrSize){int count = 0;for(int x = 0; x < arrSize; x++){for(int y = 0; y < arrSize; y++){if(arr[x][y] == 'i') count++; //Increments count for each infected person in the grid}}return count;}
#include <iostream>using namespace std;int main(){int arr[] = {5, 1, 4, 20, 10, 2, 13, 11, 6, 21};int greed[] = {0, 0, 0, 0};int k = 0;int i;int set_index;while (k < 4){i = 0;while (i < 10){if (arr[i] > greed[k]){greed[k] = arr[i];set_index = i;}i++;}arr[set_index] = 0;k++;}cout << greed[0] << " " << greed[1] << " " << greed[2] << " " << greed[3] << endl;}
#include <iostream>#include <vector>using namespace std;void swap(int *a, int *b){int temp = *b;*b = *a;*a = temp;}void heapify(vector<int> &hT, int i){int size = hT.size();int largest = i;int l = 2 * i + 1;int r = 2 * i + 2;if (l < size && hT[l] > hT[largest])largest = l;if (r < size && hT[r] > hT[largest])largest = r;if (largest != i){swap(&hT[i], &hT[largest]);heapify(hT, largest);}}void insert(vector<int> &hT, int newNum){int size = hT.size();if (size == 0){hT.push_back(newNum);}else{hT.push_back(newNum);for (int i = size / 2 - 1; i >= 0; i--){heapify(hT, i);}}}void deleteNode(vector<int> &hT, int num){int size = hT.size();int i;for (i = 0; i < size; i++){if (num == hT[i])break;}swap(&hT[i], &hT[size - 1]);hT.pop_back();for (int i = size / 2 - 1; i >= 0; i--){heapify(hT, i);}}void printArray(vector<int> &hT){for (int i = 0; i < hT.size(); ++i)cout << hT[i] << " ";cout << "\n";}int main(){vector<int> heapTree;insert(heapTree, 3);insert(heapTree, 4);insert(heapTree, 9);insert(heapTree, 5);insert(heapTree, 2);cout << "Max-Heap array: ";printArray(heapTree);deleteNode(heapTree, 4);cout << "After deleting an element: ";printArray(heapTree);}