#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int combine(std::vector<int>&);
int main()
{
int dig[3] = {0, 1, 2};
std::vector<int> permutations, tempDigits;
for (int a=0;a<3;a++)
{
for (int b=0;b<3;b++)
{
if (b == a) //Checking so it doesn't repeat the digits
continue;
for (int c=0;c<3;c++)
{
if (c == a || c == b)
continue;
tempDigits.push_back(a);
tempDigits.push_back(b);
tempDigits.push_back(c);
permutations.push_back(combine(tempDigits));
tempDigits.clear();
}
}
}
for (int i=0;i<permutations.size();i++)
std::cout << permutations[i] << " ";
}
int combine(std::vector<int>& digits) //This function takes a vector of digits (for example {1, 2, 3} and returns a digit that is the combination of those (123).
{
std::string str;
for (int i=0;i<digits.size();i++)
str += std::to_string(digits[i]);
int num;
std::istringstream(str) >> num;
return num;
}
It works and it's ok for 3 digits, but if I wanted to do all 10 or maybe even the whole alphabet, it would be a pain to write 26 or even 10 nested for loops. If you have any ideas on how to optimize this and how to make it flexible so I don't need to alter the source code for a different number of digits, please let me know. Thanks!
You can do this using recursion. Given an array, you permute like this:
for each position N in the array
swap the first item with the Nth item
find all permutations of the array, starting with the second item
swap the first item and Nth items back.