Loading...
More C++ Posts
#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);}
#include <iostream>#include <cstring>int main(int argc, char** argv){//With decimalif(strstr(argv[1], ".") != nullptr){int i = 0;//Skip i to first non 0 digitwhile(argv[1][i] < '1' || argv[1][i] > '9') ++i;//If digit comes before decimalif((argv[1] + i) < strstr(argv[1], ".")){ //Good example of pointer arithmeticstd::cout << strlen(argv[1] + i) - 1 << std::endl; //Another good example}else{//If digit is after decimalstd::cout << strlen(argv[1] + i) << std::endl;}}else{//Without decimalint m = 0;int i = 0;while(argv[1][i] < '1' || argv[1][i] > '9') ++i; //In case of some number like 0045for(; argv[1][i] != '\0'; ++i){if(argv[1][i] >= '1' && argv[1][i] <= '9') m = i + 1;}std::cout << m << std::endl;}return 0;}
/*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;}
#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 <string>#include <iostream>#include "PlaylistNode.h"using namespace std;PlaylistNode::PlaylistNode() {uniqueID = "none";songName = "none";artistName = "none";songLength = 0;nextNodePtr = 0;}PlaylistNode::PlaylistNode(string uniqueID_, string songName_, string artistName_, int songLength_) {uniqueID = uniqueID_;songName = songName_;artistName = artistName_;songLength = songLength_;nextNodePtr = 0;}void PlaylistNode::InsertAfter(PlaylistNode* ptr) {this->SetNext(ptr->GetNext());ptr->SetNext(this);}void PlaylistNode::SetNext(PlaylistNode* ptr) {nextNodePtr = ptr;}string PlaylistNode::GetID() {return uniqueID;}string PlaylistNode::GetSongName() {return songName;}string PlaylistNode::GetArtistName() {return artistName;}int PlaylistNode::GetSongLength() {return songLength;}PlaylistNode* PlaylistNode::GetNext() {return nextNodePtr;}void PlaylistNode::PrintPlaylistNode() {cout << "Unique ID: " << uniqueID << endl;cout << "Song Name: " << songName << endl;cout << "Artist Name: " << artistName << endl;cout << "Song Length (in seconds): " << songLength << endl;}Playlist::Playlist() {head = tail = 0;}void Playlist::AddSong(string id, string songname, string artistname, int length) {PlaylistNode* n = new PlaylistNode(id, songname, artistname, length);if (head == 0) {head = tail = n;}else {n->InsertAfter(tail);tail = n;}}bool Playlist::RemoveSong(string id) {if (head == NULL) {cout << "Playlist is empty" << endl;return false;}PlaylistNode* curr = head;PlaylistNode* prev = NULL;while (curr != NULL) {if (curr->GetID() == id) {break;}prev = curr;curr = curr->GetNext();}if (curr == NULL) {cout << "\"" << curr->GetSongName() << "\" is not found" << endl;return false;}else {if (prev != NULL) {prev ->SetNext(curr->GetNext());}else {head = curr->GetNext();}if (tail == curr) {tail = prev;}cout << "\"" << curr->GetSongName() << "\" removed." << endl;delete curr;return true;}}bool Playlist::ChangePosition(int oldPos, int newPos) {if (head == NULL) {cout << "Playlist is empty" << endl;return false;}PlaylistNode* prev = NULL;PlaylistNode* curr = head;int pos;if (head == NULL || head == tail) {return false;}for (pos = 1; curr != NULL && pos < oldPos; pos++) {prev = curr;curr = curr->GetNext();}if (curr != NULL) {string currentSong = curr->GetSongName();if (prev == NULL) {head = curr->GetNext();}else {prev->SetNext(curr->GetNext());}if (curr == tail) {tail = prev;}PlaylistNode* curr1 = curr;prev = NULL;curr = head;for (pos = 1; curr != NULL && pos < newPos; pos++) {prev = curr;curr = curr->GetNext();}if (prev == NULL) {curr1->SetNext(head);head = curr1;}else {curr1->InsertAfter(prev);}if (curr == NULL) {tail = curr1;}cout << "\"" << currentSong << "\" moved to position " << newPos << endl;return true;}else {cout << "Song's current position is invalid" << endl;return false;}}void Playlist::SongsByArtist(string artist) {if (head == NULL) {cout << "Playlist is empty" << endl;}else {PlaylistNode* curr = head;int i = 1;while (curr != NULL) {if (curr->GetArtistName() == artist) {cout << endl << i << "." << endl;curr->PrintPlaylistNode();}curr = curr->GetNext();i++;}}}int Playlist::TotalTime() {int total = 0;PlaylistNode* curr = head;while (curr != NULL) {total += curr->GetSongLength();curr = curr->GetNext();}return total;}void Playlist::PrintList() {if (head == NULL) {cout << "Playlist is empty" << endl;}else {PlaylistNode* curr = head;int i = 1;while (curr != NULL) {cout << endl << i++ << "." << endl;curr->PrintPlaylistNode();curr = curr->GetNext();}}}
#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;}}}