Skip to main content

Simple Greedy sort C++

0 likes • Jun 30, 2023 • 5 views
C++
Loading...

More C++ Posts

Critques

0 likes • Feb 4, 2021 • 0 views
C++
#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.";
}

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

C++ Range Slicer

0 likes • Oct 31, 2023 • 3 views
C++
//Leif Messinger
//Compile with C++ 20
#include <iostream>
#include <ranges>
#include <vector>
#include <functional>
#include <cctype> //toupper
#include <cxxabi.h>
template <typename T>
void printType(){
std::cout << abi::__cxa_demangle(typeid(T).name(), NULL, NULL, NULL) << std::endl;
}
template <typename T>
class Slicer{
public:
T begin_;
T end_;
T trueEnd;
Slicer(T begin, T end): begin_(begin), end_(begin), trueEnd(end){}
template<typename U>
Slicer(U&& vec) : begin_(vec.begin()), end_(vec.begin()), trueEnd(vec.end()){}
Slicer& finish(){
begin_ = end_;
end_ = trueEnd;
return (*this);
}
Slicer& to(long int index){
begin_ = end_;
if(index > 0){
end_ = (begin_ + index);
}else{
index *= -1;
end_ = (trueEnd - index);
}
return (*this);
}
Slicer& operator[](long int index){
return to(index);
}
T begin(){
return this->begin_;
}
T end(){
return this->end_;
}
Slicer& operator()(std::function<void(decltype(*begin_))> func) {
for(decltype(*begin_) thing : (*this)){
func(thing);
}
return (*this);
}
};
static_assert(std::ranges::range< Slicer<std::vector<int>::const_iterator> >);
int main(){
std::string vec = "abcdefghijklmnopqrstuvwxyz";
Slicer<std::string::const_iterator> bruh(vec);
//printType<decltype(bruh)>();
bruh.to(3)([](char yeet){
std::cout << yeet;
})
.to(-1)([](char yeet){
std::cout << char(std::toupper(yeet));
}).finish()([](char yeet){
std::cout << yeet << yeet << yeet << yeet << yeet;
});
std::cout << std::endl << std::endl;
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
Slicer<int*> arrSlicer(arr, arr + (sizeof(arr)/sizeof(int)));
std::cout << "[";
arrSlicer.to(-1)([](int yeet){
std::cout << yeet << ", ";
}).finish()([](int yeet){
std::cout << yeet << "]" << std::endl;
});
return 0;
}

Egg Problem Template

0 likes • Jul 10, 2023 • 3 views
C++
#include <iostream>
#include <vector>
#include <limits>
#define DEBUG_TRIAL false
class Trial{
public:
const size_t HEIGHT;
std::string record;
//Breaking height is the index of the floor, so 0 is the bottom floor, height-1 is the top floor.
//Eggs is the eggs remaining.
//Start is the bottom floor.
//End is one above the top floor.
const size_t BREAKING_HEIGHT;
size_t eggs;
size_t start;
size_t end;
size_t floorsLeft(){
return (end-start);
}
size_t middle(){
return start + (floorsLeft()/2UL);
}
size_t drops = 0;
Trial(const size_t BREAKING_HEIGHT, size_t eggs, size_t start, size_t end): BREAKING_HEIGHT(BREAKING_HEIGHT), eggs(eggs), start(start), end(end), HEIGHT(end), record(end, '_'){
record[BREAKING_HEIGHT] = 'B'; //Marking the breaking point
}
bool foundAnswer(){
return ((record[0] == 'X') || (record.find("OX")!=std::string::npos));
}
//returns true if the egg broke.
//height is the index of the floor, so 0 is the bottom floor, height-1 is the top floor.
bool drop(size_t height){
#if DEBUG_TRIAL
std::cout << "Start: " << start << ". End: " << end << ". Floors Left: " << floorsLeft() << ". Middle Index: " << middle() << std::endl;
#endif
drops++;
bool cracked = height >= BREAKING_HEIGHT;
if(cracked) --eggs;
//Update the record
record[height] = (height >= BREAKING_HEIGHT)? 'X' : 'O';
#if DEBUG_TRIAL
//Print the record
std::cout << record << std::endl;
#endif
return cracked;
}
size_t nowWhat(){
if(foundAnswer()){
return drops;
}else if(eggs <= 0){ //Ran out of eggs
throw "Algorithm failed! No more eggs!";
return 1UL;
}else if(eggs > 1){
return wrecklessSearch();
}else{
return safeSearch();
}
}
size_t safeSearch(){
if(drop(start)){
--end;
}else{
++start;
}
return nowWhat();
}
size_t wrecklessSearch(){
//If the egg breaks
if(drop(middle())){
end -= (floorsLeft()/2UL);
}else{ //egg doesn't crack
start += (floorsLeft()/2UL);
}
return nowWhat();
}
//returns the amount of drops needed to find the answer
size_t search(){
return nowWhat();
}
};
//Height is the height of the building in floors.
//Breaking height is the index of the floor, so 0 is the bottom floor, height-1 is the top floor.
//Eggs is the eggs given.
//returns the amount of drops needed to find the answer
size_t search(const size_t height, const size_t BREAKING_HEIGHT, size_t eggs){
Trial trial(BREAKING_HEIGHT, eggs, 0, height);
return trial.search();
}
class TrialStats {
public:
size_t min = std::numeric_limits<size_t>::max();
size_t max = 0;
double mean = -1.0;
void printStats(){
// Print the results
std::cout << "Minimum drops: " << min << std::endl;
std::cout << "Maximum drops: " << max << std::endl;
std::cout << "Mean drops: " << mean << std::endl;
}
};
//Benchmarks all the possible breaking points of a single building height with a number of eggs.
TrialStats trial(const size_t HEIGHT, const size_t eggs){
TrialStats stats;
int totaldrops = 0;
//Test every possible breaking point
//Breaking height is the index of the floor, so 0 is the bottom floor, height-1 is the top floor.
for (int breakingHeight = 0; breakingHeight < HEIGHT; ++breakingHeight) {
size_t drops = search(HEIGHT, breakingHeight, eggs);
stats.min = std::min(stats.min, drops);
stats.max = std::max(stats.max, drops);
totaldrops += drops;
}
// Calculate the mean number of drops
stats.mean = static_cast<double>(totaldrops) / HEIGHT;
return stats;
}
//Benchmarks a single building height from 1 egg to MAX_EGGS
void testTower(const size_t height, const size_t MAX_EGGS){
//Drop every amount of eggs that you'd need.
for (int eggs = 1; eggs <= MAX_EGGS; ++eggs) {
std::cout << "Building height: " << height << ". Num eggs: " << eggs << std::endl;
TrialStats stats = trial(height, eggs);
stats.printStats();
std::cout << std::endl << std::endl;
}
}
//Benchmarks all buildings from 0 to MAX_HEIGHT
void benchmark(const size_t MAX_HEIGHT){
const size_t MAX_EGGS = 2;
//Test every building
for (size_t height = 1; height <= MAX_HEIGHT; ++height) {
testTower(height, std::min(height, MAX_EGGS));
}
}
int main() {
constexpr size_t MAX_HEIGHT = 36;
benchmark(MAX_HEIGHT);
return 0;
}

CSCE 1040 Lab 9

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

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