Skip to content

Instantly share code, notes, and snippets.

@WhiteBlackGoose
Created March 18, 2021 17:40
Show Gist options
  • Save WhiteBlackGoose/c18ae5e8497498cfc2f482f6524e9ad8 to your computer and use it in GitHub Desktop.
Save WhiteBlackGoose/c18ae5e8497498cfc2f482f6524e9ad8 to your computer and use it in GitHub Desktop.
My inefficient (very inefficient) permutations
/*
Do NOT use it. It is not efficient.
*/
#include <iostream>
#include <vector>
#include <algorithm>
void printVec(const std::vector<int>& s)
{
for (auto v : s)
std::cout << v + 1;
std::cout << "\n";
}
int findAtLeast(size_t from, std::vector<int>& vec, int at_least)
{
if (at_least > vec.size())
return -1;
for (int i = from; i < vec.size(); i++)
if (vec[i] == at_least)
return i;
return findAtLeast(from, vec, at_least + 1);
}
bool go(std::vector<int>& s, int id)
{
if (id == s.size() - 2)
{
if (s[id + 1] > s[id])
{
std::swap(s[id + 1], s[id]);
return true;
} else
return false;
}
if (go(s, id + 1))
return true;
auto nextIndex = findAtLeast(id + 1, s, s[id] + 1);
if (nextIndex == -1)
return false;
auto next = s[nextIndex];
std::swap(s[nextIndex], s[id]);
std::sort(s.begin() + id + 1, s.end());
return true;
}
int main()
{
int N;
std::cin >> N;
if (N == 1)
{
std::cout << 1;
return 0;
}
std::vector<int> s(N);
for (int i = 0; i < N; i++)
s[i] = i;
do
{
printVec(s);
}
while(go(s, 0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment