Created
July 11, 2021 21:12
-
-
Save benlmyers/fc3c44085ae30272438c461557576434 to your computer and use it in GitHub Desktop.
A c++ script that calculates all permutations of all subsets of a given list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.cpp | |
// SubsetPermutations | |
// | |
// Created by Ben Myers on 7/11/21. | |
// | |
#include <iostream> | |
#include <cstring> | |
#include <vector> | |
#include <algorithm> | |
using namespace std; | |
/** | |
Prints an array to console. | |
*/ | |
void printarray(int arg[], int length) { | |
cout << "["; | |
for(int i = 0; i < length; i++) | |
cout << arg[i] << " "; | |
cout << "]" << endl; | |
} | |
/** | |
Prints a vector to console. | |
*/ | |
void printvector(vector<int> arg) { | |
cout << "["; | |
for(auto element: arg) { | |
cout << element << " "; | |
} | |
cout << "]"; | |
} | |
/** | |
Pushes some vector of integers to a vector of vectors and prints the contents of the pushed vector. | |
*/ | |
void pushAndOutput(vector<int> new_vec, vector<vector<int>> & to_vec) { | |
printvector(new_vec); | |
cout << ",\n"; | |
to_vec.push_back(new_vec); | |
} | |
/** | |
Prints all permutations of all subsets of an inputted vector of integers to console and returns the result. | |
*/ | |
vector<vector<int>> subsetAndPermutate(int arg[], int length) { | |
vector<vector<int>> a; | |
for(int i = 0; i < length; i++) { | |
vector<int> b = {arg[i]}; | |
pushAndOutput(b, a); | |
} | |
for(int i = 1; i < length; i++) { | |
vector<vector<int>> c(a.begin(), a.end()); | |
for(auto d: c) { | |
for(int j = 0; j < length; j++) { | |
vector<int> e(d.begin(), d.end()); | |
if(find(e.begin(), e.end(), arg[j]) == e.end()) { | |
e.push_back(arg[j]); | |
if(find(a.begin(), a.end(), e) == a.end()) { | |
pushAndOutput(e, a); | |
} | |
} | |
} | |
} | |
} | |
return a; | |
} | |
int main(int argc, const char * argv[]) { | |
cout << "Subset Permutation Challenge" << endl; | |
cout << "by Ben Myers on 7/11/21" << endl; | |
cout << "\n"; | |
// MARK: ADD YOUR PRIMARY LIST HERE TO TEST | |
int list[] = {1, 2, 3, 4, 5}; | |
// MARK: ADD THE LENGTH OF THE LIST HERE | |
int items = 5; | |
cout << "Inputted list:" << endl; | |
printarray(list, items); | |
cout << "\n"; | |
cout << "All permutations of all subsets:" << endl; | |
vector<vector<int>> output = subsetAndPermutate(list, items); | |
cout << "Total permutations of subsets: " << output.size() << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use: change the values of
list[]
anditems
in themain
method.