Loading...
More C++ Posts
//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;}
#include "goat.h" //include goat.hvoid Goat::setBreed(string breed) {this->breed = breed;}void Goat::setWeight(float weight) {this->weight = weight;}void Goat::setName(string name) {this->name = name;}void Goat::setGender(char gender) {this->gender = gender;}void Goat::setSpayed(bool goatIsSpayed) {this->goatIsSpayed = goatIsSpayed;}void Goat::setRegistrationID(string registrationID) {this->registrationID = registrationID;}void Goat::setColor(string color) {this->color = color;}void Goat::setOtherComments(string otherComments) {this->otherComments = otherComments;}string Goat::getBreed() {return breed;}float Goat::getWeight() {return weight;}string Goat::getName() {return name;}char Goat::getGender() {return gender;}bool Goat::getSpayed() {return goatIsSpayed;}string Goat::getRegistrationID() {return registrationID;}string Goat::getColor() {return color;}string Goat::getOtherComments() {return otherComments;}Goat::Goat() {breed = "";weight = 0.0;name = "";gender = '\0';goatIsSpayed = false;registrationID = "";color = "";otherComments = "";}Goat::Goat(string goatBreed, float goatWeight, string goatName, char goatGender, bool goatSpayedStatus, string goatRegistrationID, string goatColor, string goatOtherComments) {breed = goatBreed;weight = goatWeight;name = goatName;gender = goatGender;goatIsSpayed = goatSpayedStatus;registrationID = goatRegistrationID;color = goatColor;otherComments = goatOtherComments;}Goat::~Goat() {cout << "goat destroyed" << endl;}void Goat::printinfo() {cout << "Breed: " << breed << endl << "weight: " << weight << endl << "Name: " << name << endl << "Gender: " << gender << endl << "is Spayed: ";if(goatIsSpayed) { //here I do a logical test on boolean goatIsSpayed. if true cout << true else cout << falsecout << "True";} else {cout << "False";}cout << endl << "Registration ID: " << registrationID << endl << "Color Description: " << color << endl << "Other Comments: " << otherComments << endl << endl;}
/*Good morning! Here's your coding interview problem for today.This problem was asked by Stripe.Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.You can modify the input array in-place.*/#include <iostream>using namespace std;int calcMissing(int* input, int size){int sum = 0;int n = 1; //add one to account for missing valuefor(int i = 0; i < size; i++){if(input[i] > 0){sum += input[i];n++;}}//If no numbers higher than 0, answer is 1if(sum == 0)return 1;return (n*(n+1)/2) - sum; //Formula is expectedSum - actualSum/* expectedSum = n*(n+1)/2, the formula for sum(1, n) */}int main(){cout << calcMissing(new int[4]{3, 4, -1, 1}, 4) << endl;cout << calcMissing(new int[3]{1, 2, 0}, 3) << endl;//No positive numberscout << calcMissing(new int[1]{0}, 1) << endl;}
/*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;}
//Leif Messinger//Finds all sets of 5 5 letter words that don't have duplicate letters in either themselves or each other.//First it reads the words in and puts them in groups of their bitmasks//After that, we recurse on each group. Before doing that, we remove the group from the set of other groups to check it against.#include <cstdio> //getchar, printf#include <cassert> //assert#include <vector>#include <set>#include <algorithm> //std::copy_if#include <iterator> //std::back_inserter#define CHECK_FOR_CRLF true#define MIN_WORDS 5#define MAX_WORDS 5#define WORD_TOO_LONG(len) (len != 5)const unsigned int charToBitmask(const char bruh){assert(bruh >= 'a' && bruh <= 'z');return (1 << (bruh - 'a'));}void printBitmask(unsigned int bitmask){char start = 'a';while(bitmask != 0){if(bitmask & 1){putchar(start);}bitmask >>= 1;++start;}}//Pointer needs to be deletedconst std::set<unsigned int>* getBitmasks(){std::set<unsigned int>* bitmasksPointer = new std::set<unsigned int>;std::set<unsigned int>& bitmasks = (*bitmasksPointer);unsigned int bitmask = 0;unsigned int wordLength = 0;bool duplicateLetters = false;for(char c = getchar(); c >= 0; c = getchar()){if(CHECK_FOR_CRLF && c == '\r'){continue;}if(c == '\n'){if(!(WORD_TOO_LONG(wordLength) || duplicateLetters)) bitmasks.insert(bitmask);bitmask = 0;wordLength = 0;duplicateLetters = false;continue;}if((bitmask & charToBitmask(c)) != 0) duplicateLetters = true;bitmask |= charToBitmask(c);++wordLength;}return bitmasksPointer;}void printBitmasks(const std::vector<unsigned int>& bitmasks){for(unsigned int bruh : bitmasks){printBitmask(bruh);putchar(','); putchar(' ');}puts("");}//Just to be clear, when I mean "word", I mean a group of words with the same letters.void recurse(std::vector<unsigned int>& oldBitmasks, std::vector<unsigned int> history, const unsigned int currentBitmask){//If there's not enough words leftif(oldBitmasks.size() + (-(history.size())) + (-MIN_WORDS) <= 0){//If there's enough wordsif(history.size() >= MIN_WORDS){//Print the listprintBitmasks(history);}return;//To make it faster, we can stop it after 5 words too}else if(history.size() >= MAX_WORDS){//Print the listprintBitmasks(history);return;}//Thin out the array with only stuff that matches the currentBitmask.std::vector<unsigned int> newBitmasks;std::copy_if(oldBitmasks.begin(), oldBitmasks.end(), std::back_inserter(newBitmasks), [¤tBitmask](unsigned int bruh){return (bruh & currentBitmask) == 0;});while(newBitmasks.size() > 0){//I know this modifies 'oldBitmasks' too. It's intentional.//This makes it so that the word is never involved in any of the child serches or any of the later searches in this while loop.const unsigned int word = newBitmasks.back(); newBitmasks.pop_back();std::vector<unsigned int> newHistory = history;newHistory.push_back(word);recurse(newBitmasks, newHistory, currentBitmask | word);}}int main(){const std::set<unsigned int>* bitmasksSet = getBitmasks();std::vector<unsigned int> bitmasks(bitmasksSet->begin(), bitmasksSet->end());delete bitmasksSet;recurse(bitmasks, std::vector<unsigned int>(), 0);return 0;}
#include <iostream>#include "PlaylistNode.h"using namespace std;void PrintMenu(string title);int main() {string plTitle;cout << "Enter playlist's title:" << endl;getline(cin, plTitle);PrintMenu(plTitle);return 0;}void PrintMenu(string title) {Playlist list;string id;string sname;string aname;int length;int oldPos;int newPos;char choice;while(true) {cout << endl << title << " PLAYLIST MENU" << endl;cout << "a - Add song" << endl;cout << "d - Remove song" << endl;cout << "c - Change position of song" << endl;cout << "s - Output songs by specific artist" << endl;cout << "t - Output total time of playlist (in seconds)" << endl;cout << "o - Output full playlist" << endl;cout << "q - Quit" << endl << endl;cout << "Choose an option:" << endl;cin >> choice;cin.ignore();if (choice == 'q') {exit(1);}else if (choice == 'a') {cout << "\nADD SONG" << endl;cout << "Enter song's unique ID: ";cin >> id;cin.ignore();cout << "Enter song's name: ";getline(cin,sname);cout << "Enter artist's name: ";getline(cin,aname);cout << "Enter song's length (in seconds): ";cin >> length;list.AddSong(id, sname, aname, length);}else if (choice == 'd') {cout << "\nREMOVE SONG" << endl;cout << "Enter song's unique ID: ";cin >> id;list.RemoveSong(id);}else if (choice == 'c') {cout << "\nCHANGE POSITION OF SONG" << endl;cout << "Enter song's current position: ";cin >> oldPos;cout << "Enter new position for song: ";cin >> newPos;list.ChangePosition(oldPos, newPos);}else if (choice == 's') {cout << "\nOUTPUT SONGS BY SPECIFIC ARTIST" << endl;cout << "Enter artist's name: ";getline(cin, aname);list.SongsByArtist(aname);}else if (choice == 't') {cout << "\nOUTPUT TOTAL TIME OF PLAYLIST (IN SECONDS)" << endl;cout << "Total time: " << list.TotalTime() << " seconds" << endl;}else if (choice == 'o') {cout << endl << title << " - OUTPUT FULL PLAYLIST" << endl;list.PrintList();}else {cout << "Invalid menu choice! Please try again." << endl;}}}