1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Attempt finding a sequence from an array of numbers so that
// consecutive numbers only differ by 1. Example:
// [ 1, 2, 2, 1, 3, 4, 4, 5, 5, 6 ]
// One possible solution would be
// [ 1, 2, 1, 2, 3, 4, 5, 4, 5, 6 ]
void Show(const vector<int>& v)
{
for (auto& n : v)
cout << n << " ";
cout << endl;
}
// i - index of next spot to fill, from 1 to v.size()-1
void DifferOne(vector<int> v, int i)
{
if (i == v.size())
{
Show(v);
return;
}
// From remainder of array, find element one lower than previous value
auto it = find(v.begin()+i, v.end(), v[i-1] - 1);
if (it != v.end())
{
vector<int> dup(v);
swap(dup[i], dup[it - v.begin()]);
DifferOne(dup, i+1);
}
// From remainder of array, find element one higher than previous value
it = find(v.begin()+i, v.end(), v[i-1] + 1);
if (it != v.end())
{
vector<int> dup(v);
swap(dup[i], dup[it - v.begin()]);
DifferOne(dup, i+1);
}
}
void DifferOneFind(const vector<int>& orig)
{
vector<int> v(orig);
auto it = min_element(v.begin(), v.end());
swap(v[0], v[it-v.begin()]);
DifferOne(v, 1);
vector<int> v2(orig);
it = max_element(v2.begin(), v2.end());
swap(v2[0], v2[it-v2.begin()]);
DifferOne(v2, 1);
}
int main()
{
vector<int> v { 1, 2, 2, 1, 3, 4, 4, 5, 5, 6 };
cout << "Input:\n";
Show(v);
cout << "\nOutput:\n";
DifferOneFind(v);
return 0;
}
|