64 lines
2.2 KiB
C++
64 lines
2.2 KiB
C++
#include <algorithm>
|
|
#include <iostream>
|
|
#include <vector>
|
|
|
|
std::vector<std::size_t> getReversalsToSort(const std::vector<int> &arr);
|
|
/**
|
|
* Imagine a sort algorithm, that sorts array of integers by repeatedly
|
|
* reversing the order of the first several elements of it.
|
|
*
|
|
* For example, to sort [12,13,11,14], you need to reverse the order of the
|
|
* first two (2) elements. You will get [13,12,11,14]. Then you shall reverse
|
|
* the order of the first three (3) elements, and you will get [11,12,13,14]
|
|
*
|
|
* For this assignment you shall implement function
|
|
* that returns list of integers corresponding to the required reversals.
|
|
* E.g. for given vector [12,13,11,14]
|
|
* the function should return [2, 3].
|
|
*/
|
|
std::vector<std::size_t> getReversalsToSort(const std::vector<int> &arr) {
|
|
|
|
// there's a slightly more fancy version of this but who cares
|
|
// all we need is the elements sorted from least to greatest
|
|
// sorting to get info might be cheating but eeeeeh it wasn't specified
|
|
std::vector<int> sorted = arr;
|
|
std::sort(sorted.begin(), sorted.end());
|
|
|
|
std::vector<int> intermediate = arr;
|
|
std::vector<std::size_t> ret = {};
|
|
|
|
// a bit more explicit than necessary but my brain thought it was useful info
|
|
std::size_t i = intermediate.size();
|
|
for (auto elem = sorted.rbegin(); elem != sorted.rend(); elem++) {
|
|
|
|
// only searching the unsorted elements
|
|
auto found =
|
|
std::find(intermediate.cbegin(), intermediate.cbegin() + i, *elem);
|
|
|
|
std::size_t first_swap = found - intermediate.cbegin() + 1;
|
|
std::size_t second_swap = i;
|
|
// remove false positives of elements already being in the correct spot
|
|
if (first_swap != second_swap) {
|
|
// also remove reverses where nothing changes
|
|
if (first_swap > 1) {
|
|
ret.push_back(first_swap);
|
|
std::reverse(intermediate.begin(), intermediate.begin() + first_swap);
|
|
}
|
|
if (second_swap > 1) {
|
|
ret.push_back(second_swap);
|
|
std::reverse(intermediate.begin(), intermediate.begin() + second_swap);
|
|
}
|
|
}
|
|
i--;
|
|
}
|
|
|
|
return ret;
|
|
}
|
|
int main(void) {
|
|
std::cout << "{";
|
|
std::vector<int> arr{12, 13, 11, 14};
|
|
for (auto &e : getReversalsToSort(arr)) {
|
|
std::cout << e << ",";
|
|
}
|
|
std::cout << "}\n";
|
|
}
|