From 175e97020d0eb0529bf1f7598effe475f8b11fc7 Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Mon, 12 Nov 2018 11:35:01 -0500 Subject: [PATCH] Added some comments and a function for permutations --- Algorithms.hpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/Algorithms.hpp b/Algorithms.hpp index 8598286..3dfd1d8 100644 --- a/Algorithms.hpp +++ b/Algorithms.hpp @@ -10,20 +10,29 @@ #include #include #include +#include namespace mee{ //A list of functions in the file //Also works as a declaration +//This is a function that returns all the primes <= goalNumber and returns a vector with those prime numbers template std::vector getPrimes(T goalNumber); +//This is a function that gets all the divisors of num and returns a vector containing the divisors template std::vector getDivisors(T num); +//This is a function that gets the sum of all elements in a vector and returns the number template T getSum(std::vector numbers); +//This is a function that searches a vecter for an element. Returns true if num is found in list template bool isFound(T num, std::vector list); +//This is a function that creates all permutations of a string and returns a vector of those permutations. +//It is meant to have only the string passed into it from the calling function. num is used for recursion purposes +//It can however be used with num if you want the first num characters to be stationary +std::vector getPermutations(std::string master, int num = 0); template @@ -103,6 +112,37 @@ bool isFound(T num, std::vector list){ return false; } +std::vector getPermutations(std::string master, int num){ + std::vector 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 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; +} + }