Split up algorithms to several sub files

This commit is contained in:
2021-07-02 20:50:28 -04:00
parent eba3d9e1f8
commit 5cf20b539a
14 changed files with 1527 additions and 1442 deletions

65
headers/mee/Dice.hpp Normal file
View File

@@ -0,0 +1,65 @@
//myClasses/Dice.hpp
//Matthew Ellison
// Created: 1-26-19
//Modified: 1-26-19
//This is a simple class to simulate a dice for games
///This file has to be modified slightly to work with windows because the random_device does not work correctly
/*
Copyright (C) 2018 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef DICE_HPP
#define DICE_HPP
#include <random>
#include <cinttypes>
//Use this for anything besides Linux. It replaces random_device
//I know this doesn't work correctly with mingw on Windows, not sure about msbuild or mac so I don't take the chance
#ifndef __linux
#include <ctime>
#endif //ifndef linux
namespace mee{
template<class T>
class Dice{
private:
T face; //Holds the currently rolled number
T sides; //Holds the number of sides the dice has
std::default_random_engine generator; //The number generator that all the numbers come from
std::uniform_int_distribution<T> dist; //A distribution to make sure the numbers come out relatively evenly
public:
#ifdef __linux
Dice(T sides = 6) : face(1), sides(sides), generator(std::random_device{}()), dist(1, sides) { }
#else
Dice(T sides = 6) : face(1), sides(sides), generator(time(0)), dist(1, sides) { }
#endif //ifdef linux
//Setup ways to get information from the class
T getFace() const { return face; }
T getSides() const { return sides; }
//Used to simulate rolling the dice. Returns the new number
T roll() {
face = dist(generator);
return face;
}
};
} //namespace mee
#endif //DICE_HPP

96
headers/mee/Generator.hpp Normal file
View File

@@ -0,0 +1,96 @@
//myClasses/Generator.hpp
//Matthew Ellison
// Created: 07-02-21
//Modified: 07-02-21
//This file contains a simple generator for coroutines
/*
Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MEE_GENERATOR_HPP
#define MEE_GENERATOR_HPP
#include <coroutine>
#include <iostream>
namespace mee{
template <class T>
class Generator{
public:
struct promise_type{
private:
T currentValue;
public:
promise_type() = default;
~promise_type() = default;
std::suspend_always initial_suspend(){
return {};
}
std::suspend_always final_suspend() noexcept{
return {};
}
Generator<T> get_return_object(){
return Generator<T>{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always yield_value(T value){
currentValue = value;
return {};
}
void return_void(){
}
void unhandled_exception(){
//If something goes really wrong rethrow the exception
std::rethrow_exception(std::current_exception());
}
//Don't allow any use of co_await
template<class U>
std::suspend_never await_transform(U&& value) = delete;
T current(){
return currentValue;
}
};
Generator(std::coroutine_handle<promise_type> handle) : coroutine(handle){
}
Generator(const Generator&) = delete; //Don't allow any copy connstructors
Generator(Generator&& other) : coroutine(other.coroutine){
other.coroutine = nullptr;
}
~Generator(){
if(coroutine){
coroutine.destroy();
}
}
T next(){
coroutine.resume();
return coroutine.promise().current();
}
T current(){
return coroutine.promise().current();
}
Generator& operator=(const Generator&) = delete; //Don't allow any = operations
private:
std::coroutine_handle<promise_type> coroutine;
};
}
#endif //MEE_GENERATOR_HPP

207
headers/mee/Stopwatch.hpp Normal file
View File

@@ -0,0 +1,207 @@
//MyClasses/Stopwatch.hpp
//Matthew Ellison
// Created: 10-30-18
//Modified: 07-09-20
//This file defines a class that can be used as a simple timer for programs
/*
Copyright (C) 2020 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef STOPWATCH_HPP
#define STOPWATCH_HPP
#include <chrono>
#include <sstream>
#include <iomanip>
namespace mee{
class Stopwatch{
public:
//Create an error class
class stopBeforeStart{}; //Used in stop() to check if you are trying to stop the stopwatch before starting it
class timeBeforeStart{}; //Used in getTime() to check if you are trying to get a time before you start it
class invalidTimeResolution{}; //Used to detect invalid time resolution in the getStr function
private:
std::chrono::high_resolution_clock::time_point startTime; //The time the start function was called
std::chrono::high_resolution_clock::time_point endTime; //The time the stop function was called
bool hasStarted; //A flag to show that start() has been called
bool hasStopped; //A flag to show that stop() has been called
enum TIME_RESOLUTION {NANOSECOND, MICROSECOND, MILLISECOND, SECOND, MINUTE, HOUR, DEFAULT};
//Return the duration in the default time period for the high_resolution_clock
double getTime(TIME_RESOLUTION timeResolution){
double timePassed = 0; //Holds the amount of time that has passed
//If the timer hasn't been stopped then record the time right now. This will simulate looping at the stopwatch while it is still running
//I put this at the beginning to get the timestamp at close to the calling of the function as possible
if(!hasStopped){
endTime = std::chrono::high_resolution_clock::now();
}
//If the timer hasn't been started throw an exception
if(!hasStarted){
throw timeBeforeStart();
}
//Decide what resolution to make the duration
if(timeResolution == HOUR){
std::chrono::duration<double, std::ratio<3600LL>> dur = (endTime - startTime);
timePassed = dur.count();
}
else if(timeResolution == MINUTE){
std::chrono::duration<double, std::ratio<60LL>> dur = (endTime - startTime);
timePassed = dur.count();
}
else if(timeResolution == SECOND){
std::chrono::duration<double> dur = (endTime - startTime);
timePassed = dur.count();
}
else if(timeResolution == MILLISECOND){
std::chrono::duration<double, std::milli> dur = (endTime - startTime);
timePassed = dur.count();
}
else if(timeResolution == MICROSECOND){
std::chrono::duration<double, std::micro> dur = (endTime - startTime);
timePassed = dur.count();
}
else if(timeResolution == NANOSECOND){
std::chrono::duration<double, std::nano> dur = (endTime - startTime);
timePassed = dur.count();
}
else if(timeResolution == DEFAULT){
std::chrono::high_resolution_clock::duration dur = (endTime - startTime);
timePassed = dur.count();
}
return timePassed;
}
public:
Stopwatch(){
//Make sure the flags are set to false to show nothing has been called yet
hasStarted = hasStopped = false;
startTime = endTime = std::chrono::high_resolution_clock::time_point(); //Set the times with a blank time
}
~Stopwatch(){
}
//Set the start time and flag and make sure the stop flag is unset
void start(){
hasStarted = true; //Show that the stopwatch has been started
hasStopped = false; //Show that the stopwatch is still running. Security in case the Stopwatch is used in multiple places
//Put this last to ensure that the time recorded is as close to the return time as possible
startTime = std::chrono::high_resolution_clock::now();
}
//Set the stop time and flag
void stop(){
//Put this first to ensure the time recorded is as close to the call time as possible
std::chrono::high_resolution_clock::time_point tempTime = std::chrono::high_resolution_clock::now();
//Make sure the stopwatch has started before you say it has stopped
if(hasStarted){
endTime = tempTime; //Set the end time appropriately
hasStopped = true; //Show that the stop function has been called
}
//If the stopwatch hadn't been started throw an exception
else{
throw stopBeforeStart();
}
}
//Return the duration in nanoseconds
double getNano(){
return getTime(NANOSECOND);
}
//Return the duration in microseconds
double getMicro(){
return getTime(MICROSECOND);
}
//Return the duration in milliseconds
double getMilli(){
return getTime(MILLISECOND);
}
//Return the duration in seconds
double getSeconds(){
return getTime(SECOND);
}
//Return the duration in minutes
double getMinutes(){
return getTime(MINUTE);
}
//Return the duration in hours
double getHours(){
return getTime(HOUR);
}
//Return the duration in the default resolution of high_resolution_clock
double getTime(){
return getTime(DEFAULT);
}
//Returns a string with the time at best resolution
std::string getStr(){
//Setup the variables
return getStr(getTime(NANOSECOND)); //Holds the time that we are manipulating
}
//This function resets all the variables so that it can be run again
void reset(){
hasStarted = hasStopped = false; //Set the flags as though nothing has happened
endTime = startTime = std::chrono::high_resolution_clock::time_point(); //Set the times with a blank time
}
friend std::ostream& operator<<(std::ostream& out, Stopwatch& timer);
static std::string getStr(double nanoseconds){
//Setup the variables
double tempTime = nanoseconds; //Holds the time that we are manipulating
std::stringstream timeStr;
//Decide what time resolution would be best. Looking for the format of XXX.XXX
int timeRes = NANOSECOND;
for(timeRes = NANOSECOND;(timeRes < SECOND) && (tempTime >= 1000);++timeRes){
tempTime /= 1000;
}
//Check if the resolution is seconds and if there are more than 120 seconds
if((timeRes == SECOND) && (tempTime >= 120)){
++timeRes;
tempTime /= 60;
}
//Check if the resolution is minutes and if there are more than 120 minutes
if((timeRes == MINUTE) && (tempTime >= 120)){
++timeRes;
tempTime /= 60;
}
//Put the number in the string
timeStr << std::fixed << std::setprecision(3) << tempTime << ' ';
//From the timeRes variable decide what word should go on the end of the string
switch(timeRes){
case HOUR: timeStr << "hours"; break;
case MINUTE: timeStr << "minutes"; break;
case SECOND: timeStr << "seconds"; break;
case MILLISECOND: timeStr << "milliseconds"; break;
case MICROSECOND: timeStr << "microseconds"; break;
case NANOSECOND: timeStr << "nanoseconds"; break;
case DEFAULT: timeStr << "time"; break;
default: throw invalidTimeResolution(); //This should never be hit with this code, but it's good to have all the bases covered
}
//Return the string
return timeStr.str();
}
}; //end class Stopwatch
std::ostream& operator<<(std::ostream& out, Stopwatch& timer){
out << timer.getStr();
bool num = timer.hasStopped;
return out;
}
} //end namespace mee
#endif //end STOPWATCH_HPP

View File

@@ -0,0 +1,345 @@
//myClasses/headers/mee/numberAlgorithms.hpp
//Matthew Ellison
// Created: 07-02-21
//Modified: 07-02-21
//This file contains declarations of functions I have created to manipulate numbers
/*
Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MEE_NUMBER_ALGORITHMS_HPP
#define MEE_NUMBER_ALGORITHMS_HPP
#include <bitset>
#include <cinttypes>
#include <cmath>
#include <map>
#include <string>
#include <unordered_map>
#include <vector>
#include "Generator.hpp"
namespace mee{
//This function determines whether the number passed into it is a prime
template <class T>
bool isPrime(T possiblePrime){
if(possiblePrime <= 3){
return possiblePrime > 1;
}
else if(((possiblePrime % 2) == 0) || ((possiblePrime % 3) == 0)){
return false;
}
for(T cnt = 5;(cnt * cnt) <= possiblePrime;cnt += 6){
if(((possiblePrime % cnt) == 0) || ((possiblePrime % (cnt + 2)) == 0)){
return false;
}
}
return true;
}
//This is a function that returns all the primes <= goalNumber and returns a vector with those prime numbers
template <class T>
std::vector<T> getPrimes(T goalNumber){
std::vector<T> primes;
bool foundFactor = false;
//If the number is 1, 0, or a negative number return an empty vector
if(goalNumber <= 1){
return primes;
}
else{
primes.push_back(2);
}
//We can now start at 3 and skip all of the even numbers
for(T possiblePrime = 3;possiblePrime <= goalNumber;possiblePrime += 2){
//Step through every element in the current primes. If you don't find anything that divides it, it must be a prime itself
uint64_t topPossibleFactor = ceil(sqrt(possiblePrime));
for(uint64_t cnt = 0;(cnt < primes.size()) && (primes.at(cnt) <= topPossibleFactor);++cnt){
if((possiblePrime % primes.at(cnt)) == 0){
foundFactor = true;
break;
}
}
//If you didn't find a factor then it must be prime
if(!foundFactor){
primes.push_back(possiblePrime);
}
//If you did find a factor you need to reset the flag
else{
foundFactor = false;
}
}
std::sort(primes.begin(), primes.end());
return primes;
}
//This function returns a vector with a specific number of primes
template <class T>
std::vector<T> getNumPrimes(T numberOfPrimes){
std::vector<T> primes;
primes.reserve(numberOfPrimes); //Saves cycles later
bool foundFactor = false;
//If the number is 1, 0, or a negative number return an empty vector
if(numberOfPrimes <= 1){
return primes;
}
//Otherwise 2 is the first prime number
else{
primes.push_back(2);
}
//Loop through every odd number starting at 3 until we find the requisite number of primes
//Using possiblePrime >= 3 to make sure it doesn't loop back around in an overflow error and create an infinite loop
for(T possiblePrime = 3;(primes.size() < numberOfPrimes) && (possiblePrime >= 3);possiblePrime += 2){
//Step through every element in the current primes. If you don't find anything that divides it, it must be a prime itself
uint64_t topPossibleFactor = ceil(sqrt(possiblePrime));
for(uint64_t cnt = 0;(cnt < primes.size()) && (primes.at(cnt) <= topPossibleFactor);++cnt){
if((possiblePrime % primes.at(cnt)) == 0){
foundFactor = true;
break;
}
}
//If you didn't find a factor then it must be prime
if(!foundFactor){
primes.push_back(possiblePrime);
}
//If you did find a factor you need to reset the flag
else{
foundFactor = false;
}
}
//The numbers should be in order, but sort them anyway just in case
std::sort(primes.begin(), primes.end());
return primes;
}
//This function returns all prime factors of a number
template <class T>
std::vector<T> getFactors(T goalNumber){
//Get all the prime numbers up to sqrt(number). If there is a prime < goalNumber it will have to be <= sqrt(goalNumber)
std::vector<T> primes = getPrimes((T)ceil(sqrt(goalNumber))); //Make sure you are getting a vector of the correct type
std::vector<T> factors;
//Need to step through each prime and see if it is a factor of the number
for(int cnt = 0;cnt < primes.size();){
if((goalNumber % primes[cnt]) == 0){
factors.push_back(primes[cnt]);
goalNumber /= primes[cnt];
}
else{
++cnt;
}
}
//If it didn't find any factors in the primes the number itself must be prime
if(factors.size() == 0){
factors.push_back(goalNumber);
goalNumber /= goalNumber;
}
///Should add some kind of error throwing inc ase the number != 1 after searching for all prime factors
return factors;
}
//This is a function that gets all the divisors of num and returns a vector containing the divisors
template <class T>
std::vector<T> getDivisors(T num){
std::vector<T> divisors; //Holds the number of divisors
//Ensure the parameter is a valid number
if(num <= 0){
return divisors;
}
else if(num == 1){
divisors.push_back(1);
return divisors;
}
//You only need to check up to sqrt(num)
T topPossibleDivisor = ceil(sqrt(num));
for(uint64_t possibleDivisor = 1;possibleDivisor <= topPossibleDivisor;++possibleDivisor){
//Check if the counter evenly divides the number
//If it does the counter and the other number are both divisors
if((num % possibleDivisor) == 0){
//We don't need to check if the number already exists because we are only checking numbers <= sqrt(num), so there can be no duplicates
divisors.push_back(possibleDivisor);
//We still need to account for sqrt(num) being a divisor
if(possibleDivisor != topPossibleDivisor){
divisors.push_back(num / possibleDivisor);
}
//Take care of a few occations where a number was added twice
if(divisors.at(divisors.size() - 1) == (possibleDivisor + 1)){
++possibleDivisor;
}
}
}
//Sort the vector for neatness
std::sort(divisors.begin(), divisors.end());
//Return the vector of divisors
return divisors;
}
//These functions return the numth Fibonacci number
template <class T>
T getFib(const T num){
//Make sure the number is within bounds
if(num <= 2){
return 1;
}
//Setup the variables
T fib = 0;
T tempNums[3];
tempNums[0] = tempNums[1] = 1;
//Do the calculation
unsigned int cnt;
for(cnt = 2;(cnt < num) && (tempNums[(cnt - 1) % 3] >= tempNums[(cnt - 2) % 3]);++cnt){
tempNums[cnt % 3] = tempNums[(cnt + 1) % 3] + tempNums[(cnt + 2) % 3];
}
fib = tempNums[(cnt - 1) % 3]; //Transfer the answer to permanent variable. -1 to account for the offset of starting at 0
return fib;
}
//This function returns a vector that includes all Fibonacci numbers <= num
template <class T>
std::vector<T> getAllFib(const T num){
std::vector<T> fibList;
//Make sure the number is within bounds
if(num <= 1){
fibList.push_back(1);
return fibList;
}
else{ //Make sure to add the first 2 elements
fibList.push_back(1);
fibList.push_back(1);
}
//Setup the variables
T fib = 0;
T tempNums[3];
tempNums[0] = tempNums[1] = 1;
//Do the calculation and add each number to the vector
for(T cnt = 2;(tempNums[(cnt - 1) % 3] <= num) && (tempNums[(cnt - 1) % 3] >= tempNums[(cnt - 2) % 3]);++cnt){
tempNums[cnt % 3] = tempNums[(cnt + 1) % 3] + tempNums[(cnt + 2) % 3];
fibList.push_back(tempNums[cnt % 3]);
}
//If you triggered the exit statement you have one more element than you need
fibList.pop_back();
//Return the vector that contains all of the Fibonacci numbers
return fibList;
}
//This function converts a number to its binary equivalent
template <class T>
std::string toBin(T num){
//Convert the number to a binary string
std::string fullString = std::bitset<sizeof(T) * 8>(num).to_string();
//Remove leading zeros
int loc = 0;
for(loc = 0;(loc < fullString.size()) && (fullString[loc] == '0');++loc);
std::string trimmedString = fullString.substr(loc);
if(trimmedString == ""){
trimmedString = "0";
}
return trimmedString;
}
//Return the factorial of the number passed in
template <class T>
T factorial(T num){
T fact = 1;
for(T cnt = 1;cnt <= num;++cnt){
fact *= cnt;
}
return fact;
}
//A generator for prime numbers
template <class T>
mee::Generator<T> sieveOfEratosthenes(){
//Return 2 the first time, this lets us skip all even numbers later
co_yield 2;
int num = 0;
//Dictionary to hold the primes we have already found
std::unordered_map<T, std::vector<T>> dict;
//Start checking for primes with the number 3 and skip all even numbers
for(T possiblePrime = 3;true;possiblePrime += 2){
//If possiblePrime is in the dictionary it is a composite number
if(dict.contains(possiblePrime)){
//Move each number to its next odd multiple
for(T num : dict[possiblePrime]){
dict[possiblePrime + num + num].push_back(num);
}
//We no longer need this, free the memory
dict.erase(possiblePrime);
}
//If possiblePrime is not in the dictionary it is a new prime number
//Return it and mark its next multiple
else{
co_yield possiblePrime;
dict[possiblePrime * possiblePrime].push_back(possiblePrime);
}
}
}
//An alternate to sieveOfEratosthenes that uses map instead of unordered_map for greater compatibility but lower performance
template <class T>
mee::Generator<T> sieveOfEratosthenesAlt(){
//Return 2 the first time, this lets us skip all even numbers later
co_yield 2;
int num = 0;
//Dictionary to hold the primes we have already found
std::map<T, std::vector<T>> dict;
//Start checking for primes with the number 3 and skip all even numbers
for(T possiblePrime = 3;true;possiblePrime += 2){
//If possiblePrime is in the dictionary it is a composite number
if(dict.contains(possiblePrime)){
//Move each number to its next odd multiple
for(T num : dict[possiblePrime]){
dict[possiblePrime + num + num].push_back(num);
}
//We no longer need this, free the memory
dict.erase(possiblePrime);
}
//If possiblePrime is not in the dictionary it is a new prime number
//Return it and mark its next multiple
else{
co_yield possiblePrime;
dict[possiblePrime * possiblePrime].push_back(possiblePrime);
}
}
}
}
#endif //MEE_NUMBER_ALGORITHMS_HPP

View File

@@ -0,0 +1,117 @@
//myClasses/headers/mee/stringAlgorithms.hpp
//Matthew Ellison
// Created: 07-02-21
//Modified: 07-02-21
//This file contains declarations of functions I have created to manipulate strings
/*
Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MEE_STRING_ALGORITHMS_HPP
#define MEE_STRING_ALGORITHMS_HPP
#include <string>
#include <vector>
namespace mee{
//This is a function that creates all permutations of a string and returns a vector of those permutations.
std::vector<std::string> getPermutations(std::string master, int num = 0){
std::vector<std::string> perms;
//Check if the number is out of bounds
if((num >= master.size()) || (num < 0)){
return perms;
}
//If this is the last possible recurse just return the current string
else if(num == (master.size() - 1)){
perms.push_back(master);
return perms;
}
//If there are more possible recurses, recurse with the current permutation
std::vector<std::string> temp;
temp = getPermutations(master, num + 1);
perms.insert(perms.end(), temp.begin(), temp.end());
//You need to swap the current letter with every possible letter after it
//The ones needed to swap before will happen automatically when the function recurses
for(int cnt = 1;(num + cnt) < master.size();++cnt){
std::swap(master[num], master[num + cnt]);
temp = getPermutations(master, num + 1);
perms.insert(perms.end(), temp.begin(), temp.end());
std::swap(master[num], master[num + cnt]);
}
//The array is not necessarily in alpha-numeric order. So if this is the full array sort it before returning
if(num == 0){
std::sort(perms.begin(), perms.end());
}
return perms;
}
//This function returns the number of times the character occurs in the string
int findNumOccurrence(std::string str, char ch){
int num = 0; //Set the number of occurrences to 0 to start
//Loop through every character in the string and compare it to the character passed in
for(char strCh : str){
//If the character is the same as the one passed in increment the counter
if(strCh == ch){
++num;
}
}
//Return the number of times the character appeared in the string
return num;
}
//Return a vector of strings split on the delimiter
std::vector<std::string> split(std::string str, char delimiter){
std::vector<std::string> splitStrings;
int location = 0;
location = str.find(delimiter);
while(location != std::string::npos){
//Split the string
std::string firstString = str.substr(0, location);
str = str.substr(location + 1); //+1 to skip the delimiter itself
//Add the string to the vector
splitStrings.push_back(firstString);
//Get the location of the next delimiter
location = str.find(delimiter);
}
//Get the final string if it isn't empty
if(!str.empty()){
splitStrings.push_back(str);
}
//Return the vector of strings
return splitStrings;
}
//This function returns true if the string passed in is a palindrome
bool isPalindrome(std::string str){
std::string rev = str;
std::reverse(rev.begin(), rev.end());
if(str == rev){
return true;
}
else{
return false;
}
}
}
#endif //MEE_STRING_ALGORITHMS_HPP

View File

@@ -0,0 +1,213 @@
//myClasses/headers/mee/vectorAlgorithms.hpp
//Matthew Ellison
// Created: 07-02-21
//Modified: 07-02-21
//This file contains declarations of functions I have created to manipulate vectors and the data inside them
/*
Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MEE_VECTOR_ALGORITHMS_HPP
#define MEE_VECTOR_ALGORITHMS_HPP
#include <cinttypes>
#include <sstream>
#include <vector>
namespace mee{
//This is a function that returns the sum of all elements in a vector
template <class T>
T getSum(const std::vector<T>& ary){
T sum = 0;
for(unsigned int cnt = 0;cnt < ary.size();++cnt){
sum += ary.at(cnt);
}
return sum;
}
//This is a function that returns the product of all elmements in a vector
template <class T>
T getProduct(const std::vector<T>& ary){
//Make sure there is something in the array
if(ary.size() == 0){
return 0;
}
//Multiply all elements in the array together
T prod = 1;
for(T cnt = 0;cnt < ary.size();++cnt){
prod *= ary.at(cnt);
}
return prod;
}
//This is a function that searches a vecter for an element. Returns true if they key is found in list
template <class T>
bool isFound(std::vector<T> ary, T key){
typename std::vector<T>::iterator location = std::find(ary.begin(), ary.end(), key);
if(location == ary.end()){
return false;
}
else{
return true;
}
}
//This is a function that performs a bubble sort on a vector
template <class T>
void bubbleSort(std::vector<T>& ary){
bool notFinished = true; //A flag to determine if the loop is finished
for(int numLoops = 0;numLoops < ary.size();++numLoops){ //Loop until you finish
notFinished = false; //Assume you are finished until you find an element out of order
//Loop through every element in the vector, moving the largest one to the end
for(int cnt = 1;cnt < (ary.size() - numLoops);++cnt){ //use size - 1 to make sure you don't go out of bounds
if(ary.at(cnt) < ary.at(cnt - 1)){
std::swap(ary.at(cnt), ary.at(cnt - 1));
notFinished = true;
}
}
}
}
//This is a helper function for quickSort. It chooses a pivot element and sorts everything to larger or smaller than the pivot. Returns location of pivot
template <class T>
int64_t partition(std::vector<T>& ary, int64_t bottom, int64_t top){
int64_t pivot = ary.at(top); //Pick a pivot element
int64_t smaller = bottom - 1; //Keep track of where all elements are smaller than the pivot
//Loop through every element in the vector testing if it is smaller than pivot
for(int64_t cnt = bottom;cnt < top;++cnt){
//If the element is smaller than pivot move it to the correct location
if(ary.at(cnt) < pivot){
//Increment the tracker for elements smaller than pivot
++smaller;
//Swap the current element to the correct location for being smaller than the pivot
std::swap(ary.at(smaller), ary.at(cnt));
}
}
//Move the pivot element to the correct location
++smaller;
std::swap(ary.at(top), ary.at(smaller));
//Return the pivot element
return smaller;
}
//This is the function that actually performs the quick sort on the vector
template <class T>
void quickSort(std::vector<T>& ary, int64_t bottom, int64_t top){
//Make sure you have a valid slice of the vector
if(bottom < top){
//Get the pivot location
int64_t pivot = partition(ary, bottom, top);
//Sort all element less than the pivot
quickSort(ary, bottom, pivot - 1);
//Sort all element greater than the pivot
quickSort(ary, pivot + 1, top);
}
}
//This is a function that makes quick sort easier to start
template <class T>
void quickSort(std::vector<T>& ary){
//Call the other quickSort function with all the necessary info
quickSort(ary, 0, ary.size() - 1);
}
//This is a function that performs a search on a vector and returns the subscript of the item being searched for
template <class T>
int64_t search(const std::vector<T>& ary, T num){
int64_t subscript = 0; //Start with the subscript at 0
//Step through every element in the vector and return the subscript if you find the correct element
while(subscript < ary.size()){
if(ary.at(subscript) == num){
return subscript;
}
else{
++subscript;
}
}
//If you cannot find the element return -1
return -1;
}
//This function finds the smallest element in a vector
template <class T>
T findMin(const std::vector<T>& ary){
T min; //For the smallest element
//Make sure the vector is not empty
if(ary.size() > 0){
//Use the first element as the smallest element
min = ary.at(0);
//Run through every element in the vector, checking it against the current minimum
for(int cnt = 1;cnt < ary.size();++cnt){
//If the current element is smaller than the minimum, make it the new minimum
if(ary.at(cnt) < min){
min = ary.at(cnt);
}
}
}
//Return the element
return min;
}
//This function finds the largest element in a vector
template <class T>
T findMax(const std::vector<T>& ary){
T max; //For the largest element
//Make sure the vector is not empty
if(ary.size() > 0){
//Use the first element as the largest element
max = ary.at(0);
//Run through every element in the vector, checking it against the current minimum
for(int cnt = 1;cnt < ary.size();++cnt){
//If the current element is larger than the maximum, make it the new maximum
if(ary.at(cnt) > max){
max = ary.at(cnt);
}
}
}
//Return the element
return max;
}
//Print a vector
template <class T>
std::string printVector(std::vector<T>& ary){
std::stringstream str;
str << "[";
for(int cnt = 0;cnt < ary.size();++cnt){
str << ary[cnt];
if(cnt < ary.size() - 1){
str << ", ";
}
}
str << "]";
return str.str();
}
}
#endif //MEE_VECTOR_ALGORITHMS_HPP