Skip to main content

Compute Volume of Cylinder

0 likes • Nov 18, 2022 • 0 views
C++
Loading...

More C++ Posts

Heapify a vector

0 likes • Nov 19, 2022 • 0 views
C++
#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);
}

Command line game

0 likes • Nov 19, 2022 • 1 view
C++
#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 Dimensions
int nMapHeight = 16;
float fPlayerX = 14.7f; // Player Start Position
float fPlayerY = 5.09f;
float fPlayerA = 0.0f; // Player Start Rotation
float fFOV = 3.14159f / 4.0f; // Field of View
float fDepth = 16.0f; // Maximum rendering distance
float fSpeed = 5.0f; // Walking Speed
int main()
{
// Create Screen Buffer
wchar_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, . = space
wstring 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-deterministic
tp2 = chrono::system_clock::now();
chrono::duration<float> elapsedTime = tp2 - tp1;
tp1 = tp2;
float fElapsedTime = elapsedTime.count();
// Handle CCW Rotation
if (GetAsyncKeyState((unsigned short)'A') & 0x8000)
fPlayerA -= (fSpeed * 0.75f) * fElapsedTime;
// Handle CW Rotation
if (GetAsyncKeyState((unsigned short)'D') & 0x8000)
fPlayerA += (fSpeed * 0.75f) * fElapsedTime;
// Handle Forwards movement & collision
if (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 & collision
if (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 space
float fRayAngle = (fPlayerA - fFOV/2.0f) + ((float)x / (float)nScreenWidth) * fFOV;
// Find distance to wall
float fStepSize = 0.1f; // Increment size for ray casting, decrease to increase
float fDistanceToWall = 0.0f; // resolution
bool bHitWall = false; // Set when ray hits wall block
bool bBoundary = false; // Set when ray hits boundary between two wall blocks
float fEyeX = sinf(fRayAngle); // Unit vector for ray in player space
float fEyeY = cosf(fRayAngle);
// Incrementally cast ray from player, along ray angle, testing for
// intersection with a block
while (!bHitWall && fDistanceToWall < fDepth)
{
fDistanceToWall += fStepSize;
int nTestX = (int)(fPlayerX + fEyeX * fDistanceToWall);
int nTestY = (int)(fPlayerY + fEyeY * fDistanceToWall);
// Test if ray is out of bounds
if (nTestX < 0 || nTestX >= nMapWidth || nTestY < 0 || nTestY >= nMapHeight)
{
bHitWall = true; // Just set distance to maximum depth
fDistanceToWall = fDepth;
}
else
{
// Ray is inbounds so test to see if the ray cell is a wall block
if (map.c_str()[nTestX * nMapWidth + nTestY] == '#')
{
// Ray has hit wall
bHitWall = 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 walls
vector<pair<float, float>> p;
// Test each corner of hit tile, storing the distance from
// the player, and the calculated dot product of the two rays
for (int tx = 0; tx < 2; tx++)
for (int ty = 0; ty < 2; ty++)
{
// Angle of corner to eye
float 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 farthest
sort(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 floor
int nCeiling = (float)(nScreenHeight/2.0) - nScreenHeight / ((float)fDistanceToWall);
int nFloor = nScreenHeight - nCeiling;
// Shader walls based on distance
short nShade = ' ';
if (fDistanceToWall <= fDepth / 4.0f) nShade = 0x2588; // Very close
else 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 away
if (bBoundary) nShade = ' '; // Black it out
for (int y = 0; y < nScreenHeight; y++)
{
// Each Row
if(y <= nCeiling)
screen[y*nScreenWidth + x] = ' ';
else if(y > nCeiling && y <= nFloor)
screen[y*nScreenWidth + x] = nShade;
else // Floor
{
// Shade floor based on distance
float 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 Stats
swprintf_s(screen, 40, L"X=%3.2f, Y=%3.2f, A=%3.2f FPS=%3.2f ", fPlayerX, fPlayerY, fPlayerA, 1.0f/fElapsedTime);
// Display Map
for (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 Frame
screen[nScreenWidth * nScreenHeight - 1] = '\0';
WriteConsoleOutputCharacter(hConsole, screen, nScreenWidth * nScreenHeight, { 0,0 }, &dwBytesWritten);
}
return 0;
}

Enumeration Basics

0 likes • Nov 18, 2022 • 0 views
C++
#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: ";asdasdasdasd
cin >> 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;
}

Daily: Find missing array value

0 likes • Dec 24, 2021 • 18 views
C++
/*
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 value
for(int i = 0; i < size; i++)
{
if(input[i] > 0)
{
sum += input[i];
n++;
}
}
//If no numbers higher than 0, answer is 1
if(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 numbers
cout << calcMissing(new int[1]{0}, 1) << endl;
}

Big O(n^2) Ascending Sort

0 likes • Nov 18, 2022 • 6 views
C++
#include <iostream>
using namespace std;
int main() {
int arr[5];
for(int i = 0; i < 5; i++) {
arr[i] = i;
}
for(int i = 0; i < 5; i++) {
cout << "Outputting array info at position " << i + 1 << ": " << arr[i] << endl;
}
for(int i=0;i<5;i++)
{
for(int j=i+1;j<5;j++)
{
if(arr[i]>arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
cout << endl;
for(int i = 0; i < 5; i++) {
cout << "Outputting sorted array info at position " << i + 1 << ": " << arr[i] << endl;
}
return 0;
}

GCD using Stein's Algorithm

0 likes • Jun 30, 2023 • 2 views
C++
// Iterative C++ program to
// implement Stein's Algorithm
//#include <bits/stdc++.h>
#include <bitset>
using namespace std;
// Function to implement
// Stein's Algorithm
int gcd(int a, int b)
{
/* GCD(0, b) == b; GCD(a, 0) == a,
GCD(0, 0) == 0 */
if (a == 0)
return b;
if (b == 0)
return a;
/*Finding K, where K is the
greatest power of 2
that divides both a and b. */
int k;
for (k = 0; ((a | b) & 1) == 0; ++k)
{
a >>= 1;
b >>= 1;
}
/* Dividing a by 2 until a becomes odd */
while ((a & 1) == 0)
a >>= 1;
/* From here on, 'a' is always odd. */
do
{
/* If b is even, remove all factor of 2 in b */
while ((b & 1) == 0)
b >>= 1;
/* Now a and b are both odd.
Swap if necessary so a <= b,
then set b = b - a (which is even).*/
if (a > b)
swap(a, b); // Swap u and v.
b = (b - a);
} while (b != 0);
/* restore common factors of 2 */
return a << k;
}
// Driver code
int main()
{
int a = 12, b = 780;
printf("Gcd of given numbers is %d\n", gcd(a, b));
return 0;
}