Skip to main content

Critques

0 likes • Feb 4, 2021 • 0 views
C++
Loading...

More C++ Posts

Wing Project 1

0 likes • Oct 31, 2021 • 1 view
C++
//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 -1
if(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 < n
auto 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 currList
if(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 cases
int currSum = getSum(currList);
if(currSum > n)
return;
else if(currSum == n)
{
//Check to make sure no duplicates
for(auto list : *sumsList)
{
if(list == currList)
return;
}
sumsList->push_back(currList);
return;
}
//Recur when currSum < n
auto 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++;
}
}
}

Get Coefficient

0 likes • Nov 18, 2022 • 4 views
C++
#include <iostream>
using namespace std;
/* Function: get_coeff
Parameters: double& coeff, int pos passed from bb_4ac
Return: type is void so no return, but does ask for user to input data that establishes what a b and c are.
*/
void get_coeff(double& coeff, int pos) {
char position;
if(pos == 1) {
position = 'a';
} else if(pos == 2) { //a simple system to determine what coefficient the program is asking for.
position = 'b';
} else {
position = 'c';
}
cout << "Enter the co-efficient " << position << ":"; //prompt to input coeff
coeff = 5; //input coeff
}
/* Function: bb_4ac
Parameters: no parameters passed from main, but 3 params established in function, double a, b, c.
Return: b * b - 4 * a * c
*/
double bb_4ac() {
double a, b, c; //coefficients of a quadratic equation
get_coeff(a, 1); // call function 1st time
get_coeff(b, 2); // call function 2nd time
get_coeff(c, 3); // call function 3rd time
return b * b - 4 * a * c; //return b * b - 4 * a * c
}
int main() {
cout << "Function to calculate the discriminant of the equation. . . " << endl;
double determinate = bb_4ac(); //assign double determinate to bb_4ac function
cout << "The discriminant for given values is: " << determinate << endl; //output the determinate!
}

Compute Volume of Cylinder

0 likes • Nov 18, 2022 • 0 views
C++
/*
Algorithm:
Step 1: Get radius of the cylinder from the user and store in variable r
Step 2: Get height of the cylinder from the user and store in variable h
Step 3: Multiply radius * radius * height * pi and store in v
Step 4: Display the volume
*/
#include <iostream>
using namespace std;
int main()
{
float r; //define variable for radius
float h; //define variable for height
float v;
float pi;
pi=3.1416;
cout<<"Enter radius:";
cin>>r;
cout<<"Enter height:";
cin>>h;
v=r*r*h*pi; //compute volume
cout<<"Radius:"<<r<<"\tHeight:"<<h<<endl; //display radius and height
cout<<"\n************************\n";
cout<<"Volume:"<<v<<endl;//display volume
return 0;
}

Hello, World!

0 likes • Nov 18, 2022 • 2 views
C++
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}

Daily: Cutting a Wall

0 likes • Dec 20, 2021 • 0 views
C++
/*
Good morning! Here's your coding interview problem for today.
This problem was asked by LinkedIn.
A wall consists of several rows of bricks of various integer lengths and uniform height. Your goal is to find a vertical line going from the top to the bottom of the wall that cuts through the fewest number of bricks. If the line goes through the edge between two bricks, this does not count as a cut.
For example, suppose the input is as follows, where values in each row represent the lengths of bricks in that row:
[[3, 5, 1, 1],
[2, 3, 3, 2],
[5, 5],
[4, 4, 2],
[1, 3, 3, 3],
[1, 1, 6, 1, 1]]
The best we can we do here is to draw a line after the eighth brick, which will only require cutting through the bricks in the third and fifth row.
Given an input consisting of brick lengths for each row such as the one above, return the fewest number of bricks that must be cut to create a vertical line.
AUTHORS NOTE:
Makes following assumptions:
- Each row is same length
- Data is in file called "data.dat" and formatted in space-separated rows
- The cuts at the beginning and end of the wall are not solutions
This requires the following file named data.dat that is a space separated file, or similar formatted file:
----START FILE----
3 5 1 1
2 3 3 2
5 5
4 4 2
1 3 3 3
1 1 6 1 1
----END FILE----
*/
#include <algorithm>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<vector<int>> wall;
ifstream in;
in.open("data.dat");
if(!in.good())
{
cout << "ERROR: File failed to open properly.\n";
}
/* Get input from space separated file */
string line;
while(!in.eof())
{
getline(in, line);
int i;
vector<int> currv;
stringstream strs(line);
while(strs >> i)
currv.push_back(i);
wall.push_back(currv);
}
/* Convert each value from "length of brick" to "position at end of brick" */
for(int y = 0; y < wall.size(); y++)
{
wall.at(y).pop_back(); //Delet last val
for(int x = 1; x < wall.at(y).size(); x++) //Skip the first bc data doesn't need change
wall.at(y).at(x) += wall.at(y).at(x-1);
}
/* Check output. COMMENT OUT */
// for(auto row : wall)
// {
// for(int pos : row)
// cout << pos << " ";
// cout << endl;
// }
/* Determine which ending position is most common, and cut there */
//Exclude final position, which will be the size of the wall
int mode = -1;
int amt = -1;
vector<int> tried;
for(auto row : wall)
{
for(int pos : row) //For each pos in the wall
{
//Guard. If pos is contained in the list, skip pos
if(find(tried.begin(), tried.end(), pos) != tried.end())
continue;
tried.push_back(pos);
/* Cycle through each row to see if it contains the pos */
int curramt = 0;
for(auto currrow : wall)
{
if( find( currrow.begin(), currrow.end(), pos ) != currrow.end() )
curramt++;
}
//cout << pos << " " << curramt << endl;
if(curramt > amt)
{
amt = curramt;
mode = pos;
}
}
}
cout << "Please cut at position " << mode << endl;
cout << "This will cut through " << (wall.size() - amt) << " bricks." << endl;
return 0;
}

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;
}