Loading...
More C++ Posts
#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;}
//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++;}}}
/*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 <iostream>using namespace std;main{cout << "No tabbing. That's very sad :(\n";cout << "No in-editor highlighting either :(((\n";cout << "Descriptions might be niice too.";}
//===============Header File==================#include <iostream>#include <sstream> //stringbuf#include <utility> //exchange//Couple rules://Characters given through the getter functions have to be removed from the buffer.//This is so that bufferEmpty() == buffer.in_avail() > 0 basically always.//skipWhitespace doesn't remove the text from the buffer, but it does return the number of characters.//nextWord will trim whitespace before the word//nextInt will trim non-numbers before the number//hasNextInt and hasNextWord will trim the whitespace. If you think you need it, you should get nextWhitespace before doing any of those.//Whitespace after a word or an int is left on the buffer.//nextWhitespace will (get and) remove whitespace until the end of the line, including the newline character, but stops before the next line.//nextWhitespace won't read the next line when called before the end of the line, and it won't prompt the user for the next line if interactive.//If nextWhitespace is called after reading the end of the line, then it will read a new line into the buffer, which will prompt the user.//It acts like nextLine, but if there's something non-whitespace on the current line it stops there.class Scanner {public:std::stringbuf buffer;std::istream& input;Scanner(std::istream& in = std::cin) : buffer(), input(in) {}//Buffer debuggingbool fillBuffer();bool bufferEmpty();void printBufferEmpty();std::string getBuffer();size_t bufferLength();void printBufferStats();//Intbool hasNextInt();int nextInt();//Wordbool hasNextWord();std::string nextWord();//Linebool hasNextLine();//Whitespacesize_t skipWhitespace(); //Prob should be private, but I don't believe in that private shit.bool hasNextWhitespace();std::string nextWhitespace();std::string nextWhitespaceAll();std::string nextLine();};//===============Source File==================bool Scanner::fillBuffer() { //Returns if it had to get the next line from the input.const bool badInput = input.eof() || input.bad();const bool shouldFillBuffer = bufferEmpty() && !badInput;if (shouldFillBuffer) {std::string line;if (std::getline(input, line)) {buffer.str(buffer.str() + line + "\n");}}return shouldFillBuffer;}bool Scanner::bufferEmpty(){return buffer.str() == "";}void Scanner::printBufferEmpty(){std::cout << "The buffer is " << (bufferEmpty()? "" : "not") << " empty." << std::endl;}std::string Scanner::getBuffer(){return buffer.str();}size_t Scanner::bufferLength(){return buffer.str().length();}void Scanner::printBufferStats(){if(bufferEmpty()){std::cout << "The buffer is \"\"" << std::endl;return;}std::cout << "The length of the buffer is " << bufferLength() << std::endl;if(buffer.sgetc() == '\r'){std::cout << "The buffer is \\r\\n" << std::endl;}else if(buffer.sgetc() == '\n'){std::cout << "The buffer is \\n" << std::endl;}}bool Scanner::hasNextInt() {return hasNextWord() && (std::isdigit(buffer.sgetc()) || buffer.sgetc() == '-');}int Scanner::nextInt() {if (!hasNextInt()) { //Will fill the buffer if not filled. Will also trim whitespace.return 0;}std::string num;size_t charactersRead = 0;while (buffer.in_avail() > 0 && (std::isdigit(buffer.sgetc()) || buffer.sgetc() == '-')) {num += buffer.sbumpc();++charactersRead;}buffer.str(buffer.str().erase(0, charactersRead));return std::stoi(num);}bool Scanner::hasNextWord() {nextWhitespaceAll();return buffer.in_avail() > 0;}std::string Scanner::nextWord() {if (!hasNextWord()) { //Will fill the buffer if not filled. Will also trim whitespace.return "";}std::string word;size_t charactersRead = 0;while (buffer.in_avail() > 0 && !std::isspace(buffer.sgetc())) {word += buffer.sbumpc();++charactersRead;}buffer.str(buffer.str().erase(0, charactersRead));return word;}bool Scanner::hasNextLine() {return (!bufferEmpty()) || fillBuffer();}size_t Scanner::skipWhitespace() { //Returns characters readsize_t charactersRead = 0;while (buffer.in_avail() > 0 && std::isspace(buffer.sgetc())) {buffer.sbumpc();++charactersRead;}return charactersRead;}bool Scanner::hasNextWhitespace(){fillBuffer();return buffer.in_avail() > 0 && std::isspace(buffer.sgetc());}std::string Scanner::nextWhitespace() {if (!hasNextWhitespace()) { //Will fill the buffer if not filledreturn "";}const size_t charactersRead = skipWhitespace();std::string whitespace = buffer.str().substr(charactersRead);buffer.str(buffer.str().erase(0, charactersRead));return whitespace;}std::string Scanner::nextWhitespaceAll(){std::string whitespace;while(hasNextWhitespace()){std::string gottenWhiteSpace = nextWhitespace();whitespace += gottenWhiteSpace;}return whitespace;}std::string Scanner::nextLine(){if (!hasNextLine()) {return "";}fillBuffer();//Swap out the old buffer with an empty buffer, and get the old buffer as a variable.std::string line = std::exchange(buffer, std::stringbuf()).str();//Remove the newline.if(line[line.length() - 1] == '\n' || line[line.length() - 1] == '\r' ) line.pop_back();if(line[line.length() - 1] == '\r' || line[line.length() - 1] == '\n' ) line.pop_back();return line;}//=================Word and Int test=================while(bruh.hasNextInt() || bruh.hasNextWord()){std::cout << "started loop" << std::endl;if(bruh.hasNextInt()){std::cout << "Int: " << bruh.nextInt() << " " << std::endl;}else{std::cout << "Word: " << bruh.nextWord() << " " << std::endl;}bruh.nextWhitespace();}//===================Line test======================for(int count = 1; bruh.hasNextLine(); ++count){std::string line = bruh.nextLine();std::cout << "Line " << count << ": " << line << std::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);}