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;}
#include <bits/stdc++.h>#define MAXSIZE 50000#define INF 100000using namespace std;vector<int> adj[MAXSIZE]; //Adjacency Listbool visited[MAXSIZE]; //Checks if a node is visited or not in BFS and DFSbool isConnected = true; //Checks if the input graph is connected or notint dist[MAXSIZE], discover[MAXSIZE], finish[MAXSIZE]; //Distance for BFS, in time and out time for DFSint t = 1; //Time used for DFSint u, v, i, j, k, N = 0;stack<int> st; //Stack for TopSortmultiset<pair<int, int>> s; //collection of pairs to sort by distancepair<int, int> current; //pointer variable to a position in the multisetvoid BFS(){queue<int> q; //queue for BFSq.push(1); //pushing the sourcedist[1] = 0; //assign the distance of source as 0visited[1] = 1; //marking as visitedwhile(!q.empty()){u = q.front();q.pop();for(i=0; i < adj[u].size(); i++){v = adj[u][i]; //Adjacent vertexif(!visited[v]) //if not visited, update the distance and push onto queue{visited[v] = 1;dist[v] = dist[u]+1;q.push(v);}}}for(i = 1; i <= N; i++){s.insert(make_pair(dist[i], i)); //for sorted distance}cout << "BFS results:" << endl;//prints BFS results and checks if the graph is connectedwhile(!s.empty()){current = *s.begin();s.erase(s.begin());i = current.second;j = current.first;if(j == INF) //if any infinite value, graph is not connected{cout << i << " INF" << endl;isConnected = false;}else{cout << i << " " << j << endl;}}//marks blocks of memory as visitedmemset(visited, 0, sizeof visited);}void dfsSearch(int s){visited[s] = 1; //marking it visiteddiscover[s] = t++; //assigning and incrementing timeint i, v;for(i = 0; i < adj[s].size(); i++){v = adj[s][i];if(!visited[v]) //if vertex is not visited then visit, else continue{dfsSearch(v);}}st.push(s); //pushed onto stack for TopSort if it was calledfinish[s] = t++; //out time}void DFS(){for(i = 1; i <= N; i++){if(visited[i]) //if visited continue, else visit it with DFS{continue;}dfsSearch(i); //embedded function to actually perform DFS}for(i=1;i<=N;i++){s.insert(make_pair(discover[i], i)); //minheap for sorted discovery time}cout << "DFS results:" << endl;while(!s.empty()) //Prints DFS results as long as the multiset is not empty{current = *s.begin(); //duplicates the pointer to first object in the multisets.erase(s.begin()); //erases the first object in multiseti = current.second;cout << i << " " << discover[i] << " " << finish[i] << endl; //prints discover times and finish times}}void TopSort(){//call DFS so we can have a sorted stack to printfor(i=1;i<=N;i++){if(visited[i]){continue;}dfsSearch(i);}cout<<"Topological Sort results:"<<endl;//print sorted results from DFSwhile(!st.empty()){i = st.top();st.pop();cout << i << endl;}//declare blocks of memory as visitedmemset(visited, 0, sizeof visited);}int main(){string str, num, input;int selection, connectedChoice = 0;//get to input any file, more freedom than declaring file in command linecout << "Enter the exact name of your input file [case sensitive]: ";cin >> input;ifstream inputFile(input); //Read the input file//checks if the ifstream cannot openif(inputFile.fail()){cout << endl << "No input files matching that name. Terminating..." << endl;return 0;}//Read until the end of filewhile(!inputFile.eof()){getline(inputFile, str); //read the current lineif(str == ""){continue;}if(!isdigit(str[0])) //checks to see if the first item in a line is a digit or not{cout << "Invalid file format. You have a line beginning with a non-digit. Terminating..." << endl;return 0;}stringstream ss;ss << str; //convert the line to stream of stringsss >> num; //read the line numstringstream(num) >> u;while(!ss.eof()){ss>>num;if(stringstream(num) >> v){adj[u].push_back(v); //read the adjacent vertices}}N++; //calculate the number of verticessort(adj[u].begin(), adj[u].end()); //sort the adjacency list in case it is not sorted}//creates arbitrary values for distance, will check later if INF remainfor(i = 1; i <= N; i++){dist[i] = INF;}cout << endl << "Valid Input file loaded!" << endl;while(selection != 4){cout << "************************************************" << endl;cout << "What type of analysis would you like to perform?" << endl;cout << "1: Breadth-First Search" << endl;cout << "2: Depth-First Search" << endl;cout << "3: Topological Sort" << endl;cout << "4: Quit" << endl;cout << "************************************************" << endl;//read user input and execute selectioncin >> selection;switch(selection){case 1:cout << endl;BFS();cout << endl;cout << "Would you like to know if the graph is connected?" << endl;cout << "1: Yes" << endl;cout << "Any other key: No" << endl;cin >> connectedChoice;switch(connectedChoice){case 1:if(!isConnected){cout << "The graph is not connected." << endl << endl;}else{cout << "The graph is connected!" << endl << endl;}break;default:break;}break;case 2:cout << endl;DFS();cout << endl;break;case 3:cout << endl;TopSort();cout << endl;break;case 4:return 0;default:cout << endl << "Invalid selection." << endl; //loops the selection prompt until a valid selection is input.}}}
//From https://create.arduino.cc/projecthub/abhilashpatel121/easyfft-fast-fourier-transform-fft-for-arduino-9d2677#include <cmath>#include <iostream>const unsigned char sine_data[] = { //Quarter a sine wave0,4, 9, 13, 18, 22, 27, 31, 35, 40, 44,49, 53, 57, 62, 66, 70, 75, 79, 83, 87,91, 96, 100, 104, 108, 112, 116, 120, 124, 127,131, 135, 139, 143, 146, 150, 153, 157, 160, 164,167, 171, 174, 177, 180, 183, 186, 189, 192, 195, //Paste this at top of program198, 201, 204, 206, 209, 211, 214, 216, 219, 221,223, 225, 227, 229, 231, 233, 235, 236, 238, 240,241, 243, 244, 245, 246, 247, 248, 249, 250, 251,252, 253, 253, 254, 254, 254, 255, 255, 255, 255};float sine(int i){ //Inefficient sineint j=i;float out;while(j < 0) j = j + 360;while(j > 360) j = j - 360;if(j > -1 && j < 91) out = sine_data[j];else if(j > 90 && j < 181) out = sine_data[180 - j];else if(j > 180 && j < 271) out = -sine_data[j - 180];else if(j > 270 && j < 361) out = -sine_data[360 - j];return (out / 255);}float cosine(int i){ //Inefficient cosineint j = i;float out;while(j < 0) j = j + 360;while(j > 360) j = j - 360;if(j > -1 && j < 91) out = sine_data[90 - j];else if(j > 90 && j < 181) out = -sine_data[j - 90];else if(j > 180 && j < 271) out = -sine_data[270 - j];else if(j > 270 && j < 361) out = sine_data[j - 270];return (out / 255);}//Example data://-----------------------------FFT Function----------------------------------------------//float* FFT(int in[],unsigned int N,float Frequency){ //Result is highest frequencies in order of loudness. Needs to be deleted./*Code to perform FFT on arduino,setup:paste sine_data [91] at top of program [global variable], paste FFT function at end of programTerm:1. in[] : Data array,2. N : Number of sample (recommended sample size 2,4,8,16,32,64,128...)3. Frequency: sampling frequency required as input (Hz)If sample size is not in power of 2 it will be clipped to lower side of number.i.e, for 150 number of samples, code will consider first 128 sample, remaining sample will be omitted.For Arduino nano, FFT of more than 128 sample not possible due to mamory limitation (64 recomended)For higher Number of sample may arise Mamory related issue,Code by ABHILASHContact: [email protected]Documentation:https://www.instructables.com/member/abhilash_patel/instructables/2/3/2021: change data type of N from float to int for >=256 samples*/unsigned int sampleRates[13]={1,2,4,8,16,32,64,128,256,512,1024,2048};int a = N;int o;for(int i=0;i<12;i++){ //Snapping N to a sample rate in sampleRatesif(sampleRates[i]<=a){o = i;}}int in_ps[sampleRates[o]] = {}; //input for sequencingfloat out_r[sampleRates[o]] = {}; //real part of transformfloat out_im[sampleRates[o]] = {}; //imaginory part of transformint x = 0;int c1;int f;for(int b=0;b<o;b++){ // bit reversalc1 = sampleRates[b];f = sampleRates[o] / (c1 + c1);for(int j = 0;j < c1;j++){x = x + 1;in_ps[x]=in_ps[j]+f;}}for(int i=0;i<sampleRates[o];i++){ // update input array as per bit reverse orderif(in_ps[i]<a){out_r[i]=in[in_ps[i]];}if(in_ps[i]>a){out_r[i]=in[in_ps[i]-a];}}int i10,i11,n1;float e,c,s,tr,ti;for(int i=0;i<o;i++){ //ffti10 = sampleRates[i]; // overall values of sine/cosine :i11 = sampleRates[o] / sampleRates[i+1]; // loop with similar sine cosine:e = 360 / sampleRates[i+1];e = 0 - e;n1 = 0;for(int j=0;j<i10;j++){c=cosine(e*j);s=sine(e*j);n1=j;for(int k=0;k<i11;k++){tr = c*out_r[i10 + n1]-s*out_im[i10 + n1];ti = s*out_r[i10 + n1]+c*out_im[i10 + n1];out_r[n1 + i10] = out_r[n1]-tr;out_r[n1] = out_r[n1]+tr;out_im[n1 + i10] = out_im[n1]-ti;out_im[n1] = out_im[n1]+ti;n1 = n1+i10+i10;}}}/*for(int i=0;i<sampleRates[o];i++){std::cout << (out_r[i]);std::cout << ("\t"); // un comment to print RAW o/pstd::cout << (out_im[i]); std::cout << ("i");std::cout << std::endl;}*///---> here onward out_r contains amplitude and our_in conntains frequency (Hz)for(int i=0;i<sampleRates[o-1];i++){ // getting amplitude from compex numberout_r[i] = sqrt(out_r[i]*out_r[i]+out_im[i]*out_im[i]); // to increase the speed delete sqrtout_im[i] = i * Frequency / N;std::cout << (out_im[i]); std::cout << ("Hz");std::cout << ("\t"); // un comment to print freuency binstd::cout << (out_r[i]);std::cout << std::endl;}x = 0; // peak detectionfor(int i=1;i<sampleRates[o-1]-1;i++){if(out_r[i]>out_r[i-1] && out_r[i]>out_r[i+1]){in_ps[x] = i; //in_ps array used for storage of peak numberx = x + 1;}}s = 0;c = 0;for(int i=0;i<x;i++){ // re arraange as per magnitudefor(int j=c;j<x;j++){if(out_r[in_ps[i]]<out_r[in_ps[j]]){s=in_ps[i];in_ps[i]=in_ps[j];in_ps[j]=s;}}c=c+1;}float* f_peaks = new float[sampleRates[o]];for(int i=0;i<5;i++){ // updating f_peak array (global variable)with descending orderf_peaks[i]=out_im[in_ps[i]];}return f_peaks;}//------------------------------------------------------------------------------------////main.cppint data[64]={14, 30, 35, 34, 34, 40, 46, 45, 30, 4, -26, -48, -55, -49, -37,-28, -24, -22, -13, 6, 32, 55, 65, 57, 38, 17, 1, -6, -11, -19, -34,-51, -61, -56, -35, -7, 18, 32, 35, 34, 35, 41, 46, 43, 26, -2, -31, -50,-55, -47, -35, -27, -24, -21, -10, 11, 37, 58, 64, 55, 34, 13, -1, -7};int main(){const unsigned int SAMPLE_RATE = 48*1000; //48khzauto result = FFT(data,64,SAMPLE_RATE);std::cout << result[0] << " " << result[1] << " " << result[2] << " " << result[3] << std::endl;delete[] result;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;}
/*Algorithm:Step 1: Get radius of the cylinder from the user and store in variable rStep 2: Get height of the cylinder from the user and store in variable hStep 3: Multiply radius * radius * height * pi and store in vStep 4: Display the volume*/#include <iostream>using namespace std;int main(){float r; //define variable for radiusfloat h; //define variable for heightfloat v;float pi;pi=3.1416;cout<<"Enter radius:";cin>>r;cout<<"Enter height:";cin>>h;v=r*r*h*pi; //compute volumecout<<"Radius:"<<r<<"\tHeight:"<<h<<endl; //display radius and heightcout<<"\n************************\n";cout<<"Volume:"<<v<<endl;//display volumereturn 0;}
#include "stdio.h"#include <stdlib.h>int main (int argCount, char** args) {int a = atoi(args[1]);int b = atoi(args[2]);unsigned int sum = 0;unsigned int p = 1;for (unsigned int i = 1; i < b; i++) {p = p * i;}// (b!, (1 + b)!, (2 + b)!, ..., (n + b)!)for (unsigned int i = 0; i < a; i++) {p = p * (i + b);sum = sum + p;}printf("y: %u\n", sum);return 0;}