Our Mathematical Selection code in C++.
Mathematical Selection Class Header File:
#pragma once
#include <string>
#include <vector>
using namespace std;
class Selection
{
public:
Selection();
virtual ~Selection();
// variables
vector<string> words;
unsigned short r; // min length of word
// functions
vector<vector<string>> groupSelection(vector<string>, unsigned short);
void recursiveFillUp(vector<string>);
protected:
vector<vector<string>> complete_group;
private:
unsigned i;
};
Mathematical Selection Class File:
#include "stdafx.h"
#include "Selection.h"
Selection::Selection()
{
}
vector<vector<string>> Selection::groupSelection(vector<string> candidates, unsigned short dimension) {
words = candidates;
r = dimension;
complete_group = {};
i = 0;
recursiveFillUp({});
return complete_group;
}
// pick elements recursively
void Selection::recursiveFillUp(vector<string> temp) {
vector<string> * picked_elements;
picked_elements = new vector<string>[words.size()];
unsigned j = i;
while (j < words.size()) {
picked_elements[j] = temp;
picked_elements[j].push_back(words[j]);
// recoil factor
if (i >= words.size()) {
i = j;
}
// satisfied yet?
if (picked_elements[j].size() == r) {
complete_group.push_back(picked_elements[j]);
}
else if (picked_elements[j].size() < r) {
recursiveFillUp(picked_elements[j]);
}
j++;
}
if (!picked_elements[--j].empty() && picked_elements[j].size() == r) {
i++; // keep recoil factor straightened out
}
delete[] picked_elements;
}
Selection::~Selection()
{
}
Main Class:
#include "stdafx.h"
#include "Selection.h"
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<string> goods = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
Selection pick;
vector<vector<string>> result = pick.groupSelection(goods, 2);
// print choices and operation
cout << "\n[ ";
for (string choice : pick.words) {
cout << choice << "; ";
}
cout << "] selection " << pick.r << ":\n\n";
// print out selections nicely
int i = 0;
for (vector<string> set : result) {
i++;
cout << i << ": ";
for (string member : set) {
cout << member << "; ";
}
cout << "\n";
}
cout << "\nNumber of ways is " << result.size() << ".";
return 0;
}
Try it out!
Elegance (0.0)