Loading...
More C++ Posts
#include <iostream>using namespace std;/*Description: uses switch case statements to determine whether it is hot or not outside.Also uses toupper() function which forces user input char to be uppercase in order to work for the switch statement*/int main() {char choice;cout << "S = Summer, F = Fall, W = Winter, P = Spring" << endl;cout << "Enter a character to represent a season: ";asdasdasdasdcin >> choice;enum Season {SUMMER='S', FALL='F', WINTER='W', SPRING='P'};switch(toupper(choice)) // This switch statement compares a character entered with values stored inside of an enum{case SUMMER:cout << "It's very hot outside." << endl;break;case FALL:cout << "It's great weather outside." << endl;break;case WINTER:cout << "It's fairly cold outside." << endl;break;case SPRING:cout << "It's rather warm outside." << endl;break;default:cout << "Wrong choice" << endl;break;}return 0;}
#include <iostream>#include <string> //Should already be in iostream#include <cstdlib>//A word score adds up the character values. a-z gets mapped to 1-26 for the values of the characters.//wordScore [wordValue]//Pipe in the input into stdin, or type the words yourself.//Lowercase words onlyint characterValue(const char b){return ((b >= 'a') && (b <= 'z'))? ((b - 'a') + 1) : 0;}int main(int argc, char** argv){//The first argument specifies if you are trying to look for a certain word scoreint wordValue = (argc > 1)? std::atoi(argv[1]) : 0;std::string line;while(std::getline(std::cin, line)){int sum = 0;for(const char c : line){sum += characterValue(c);}if(wordValue){ //If wordValue is 0 or the sum is the correct valueif(wordValue == sum){std::cout << line << std::endl;}} else {std::cout << sum << "\t" << line << std::endl;}}return 0;}
#include <iostream>int main(){const char* const hello = "Hello, world!";const char* bruh = hello;char* const yeet = hello;std::cout << bruh << std::endl;std::cout << yeet << std::endl;return 0;}/*Place your bets!Will the program:a.) Print "Hello, world!" twice?b.) Compile error on line 5 (bruh initialize line) because the pointer gets implicit cast to non-const?c.) Compile error on line 7 (yeet initialize line) because the char gets implicit cast to non-const?d.) Both b and c?e.) Compile error line 11 (print yeet) because the pointer is constant and can't be incrementedf.) Print "Hello, world!" then print the pointer address in hexadecimalg.) Both b and e?h.) Both c and e?i.) B, c, and e?*/// The answer is in this base 64 string:// T25seSBjLikKVGhlIGNvbXBpbGVyIGRvZXNu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lciBiZWNhdXNlIGl0J3MgbWFraW5nIGEgY29weS4gVGhlIHBvaW50ZXIgZ2V0cyBjb3BpZWQgYmVjYXVzZSB0aGUgcG9pbnRlciBpcyBwYXNzZWQgYnkgdmFsdWUsIG5vdCByZWZlcmVuY2Uu
/*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>#include <vector>#include <utility>#include <algorithm>#include <chrono>using namespace std;#include <stdio.h>#include <Windows.h>int nScreenWidth = 120; // Console Screen Size X (columns)int nScreenHeight = 40; // Console Screen Size Y (rows)int nMapWidth = 16; // World Dimensionsint nMapHeight = 16;float fPlayerX = 14.7f; // Player Start Positionfloat fPlayerY = 5.09f;float fPlayerA = 0.0f; // Player Start Rotationfloat fFOV = 3.14159f / 4.0f; // Field of Viewfloat fDepth = 16.0f; // Maximum rendering distancefloat fSpeed = 5.0f; // Walking Speedint main(){// Create Screen Bufferwchar_t *screen = new wchar_t[nScreenWidth*nScreenHeight];HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);SetConsoleActiveScreenBuffer(hConsole);DWORD dwBytesWritten = 0;// Create Map of world space # = wall block, . = spacewstring map;map += L"#########.......";map += L"#...............";map += L"#.......########";map += L"#..............#";map += L"#......##......#";map += L"#......##......#";map += L"#..............#";map += L"###............#";map += L"##.............#";map += L"#......####..###";map += L"#......#.......#";map += L"#......#.......#";map += L"#..............#";map += L"#......#########";map += L"#..............#";map += L"################";auto tp1 = chrono::system_clock::now();auto tp2 = chrono::system_clock::now();while (1){// We'll need time differential per frame to calculate modification// to movement speeds, to ensure consistant movement, as ray-tracing// is non-deterministictp2 = chrono::system_clock::now();chrono::duration<float> elapsedTime = tp2 - tp1;tp1 = tp2;float fElapsedTime = elapsedTime.count();// Handle CCW Rotationif (GetAsyncKeyState((unsigned short)'A') & 0x8000)fPlayerA -= (fSpeed * 0.75f) * fElapsedTime;// Handle CW Rotationif (GetAsyncKeyState((unsigned short)'D') & 0x8000)fPlayerA += (fSpeed * 0.75f) * fElapsedTime;// Handle Forwards movement & collisionif (GetAsyncKeyState((unsigned short)'W') & 0x8000){fPlayerX += sinf(fPlayerA) * fSpeed * fElapsedTime;;fPlayerY += cosf(fPlayerA) * fSpeed * fElapsedTime;;if (map.c_str()[(int)fPlayerX * nMapWidth + (int)fPlayerY] == '#'){fPlayerX -= sinf(fPlayerA) * fSpeed * fElapsedTime;;fPlayerY -= cosf(fPlayerA) * fSpeed * fElapsedTime;;}}// Handle backwards movement & collisionif (GetAsyncKeyState((unsigned short)'S') & 0x8000){fPlayerX -= sinf(fPlayerA) * fSpeed * fElapsedTime;;fPlayerY -= cosf(fPlayerA) * fSpeed * fElapsedTime;;if (map.c_str()[(int)fPlayerX * nMapWidth + (int)fPlayerY] == '#'){fPlayerX += sinf(fPlayerA) * fSpeed * fElapsedTime;;fPlayerY += cosf(fPlayerA) * fSpeed * fElapsedTime;;}}for (int x = 0; x < nScreenWidth; x++){// For each column, calculate the projected ray angle into world spacefloat fRayAngle = (fPlayerA - fFOV/2.0f) + ((float)x / (float)nScreenWidth) * fFOV;// Find distance to wallfloat fStepSize = 0.1f; // Increment size for ray casting, decrease to increasefloat fDistanceToWall = 0.0f; // resolutionbool bHitWall = false; // Set when ray hits wall blockbool bBoundary = false; // Set when ray hits boundary between two wall blocksfloat fEyeX = sinf(fRayAngle); // Unit vector for ray in player spacefloat fEyeY = cosf(fRayAngle);// Incrementally cast ray from player, along ray angle, testing for// intersection with a blockwhile (!bHitWall && fDistanceToWall < fDepth){fDistanceToWall += fStepSize;int nTestX = (int)(fPlayerX + fEyeX * fDistanceToWall);int nTestY = (int)(fPlayerY + fEyeY * fDistanceToWall);// Test if ray is out of boundsif (nTestX < 0 || nTestX >= nMapWidth || nTestY < 0 || nTestY >= nMapHeight){bHitWall = true; // Just set distance to maximum depthfDistanceToWall = fDepth;}else{// Ray is inbounds so test to see if the ray cell is a wall blockif (map.c_str()[nTestX * nMapWidth + nTestY] == '#'){// Ray has hit wallbHitWall = true;// To highlight tile boundaries, cast a ray from each corner// of the tile, to the player. The more coincident this ray// is to the rendering ray, the closer we are to a tile// boundary, which we'll shade to add detail to the wallsvector<pair<float, float>> p;// Test each corner of hit tile, storing the distance from// the player, and the calculated dot product of the two raysfor (int tx = 0; tx < 2; tx++)for (int ty = 0; ty < 2; ty++){// Angle of corner to eyefloat vy = (float)nTestY + ty - fPlayerY;float vx = (float)nTestX + tx - fPlayerX;float d = sqrt(vx*vx + vy*vy);float dot = (fEyeX * vx / d) + (fEyeY * vy / d);p.push_back(make_pair(d, dot));}// Sort Pairs from closest to farthestsort(p.begin(), p.end(), [](const pair<float, float> &left, const pair<float, float> &right) {return left.first < right.first; });// First two/three are closest (we will never see all four)float fBound = 0.01;if (acos(p.at(0).second) < fBound) bBoundary = true;if (acos(p.at(1).second) < fBound) bBoundary = true;if (acos(p.at(2).second) < fBound) bBoundary = true;}}}// Calculate distance to ceiling and floorint nCeiling = (float)(nScreenHeight/2.0) - nScreenHeight / ((float)fDistanceToWall);int nFloor = nScreenHeight - nCeiling;// Shader walls based on distanceshort nShade = ' ';if (fDistanceToWall <= fDepth / 4.0f) nShade = 0x2588; // Very closeelse if (fDistanceToWall < fDepth / 3.0f) nShade = 0x2593;else if (fDistanceToWall < fDepth / 2.0f) nShade = 0x2592;else if (fDistanceToWall < fDepth) nShade = 0x2591;else nShade = ' '; // Too far awayif (bBoundary) nShade = ' '; // Black it outfor (int y = 0; y < nScreenHeight; y++){// Each Rowif(y <= nCeiling)screen[y*nScreenWidth + x] = ' ';else if(y > nCeiling && y <= nFloor)screen[y*nScreenWidth + x] = nShade;else // Floor{// Shade floor based on distancefloat b = 1.0f - (((float)y -nScreenHeight/2.0f) / ((float)nScreenHeight / 2.0f));if (b < 0.25) nShade = '#';else if (b < 0.5) nShade = 'x';else if (b < 0.75) nShade = '.';else if (b < 0.9) nShade = '-';else nShade = ' ';screen[y*nScreenWidth + x] = nShade;}}}// Display Statsswprintf_s(screen, 40, L"X=%3.2f, Y=%3.2f, A=%3.2f FPS=%3.2f ", fPlayerX, fPlayerY, fPlayerA, 1.0f/fElapsedTime);// Display Mapfor (int nx = 0; nx < nMapWidth; nx++)for (int ny = 0; ny < nMapWidth; ny++){screen[(ny+1)*nScreenWidth + nx] = map[ny * nMapWidth + nx];}screen[((int)fPlayerX+1) * nScreenWidth + (int)fPlayerY] = 'P';// Display Framescreen[nScreenWidth * nScreenHeight - 1] = '\0';WriteConsoleOutputCharacter(hConsole, screen, nScreenWidth * nScreenHeight, { 0,0 }, &dwBytesWritten);}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.}}}