#include #include #include std::vector getReversalsToSort(const std::vector &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 getReversalsToSort(const std::vector &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 sorted = arr; std::sort(sorted.begin(), sorted.end()); std::vector intermediate = arr; std::vector ret = {}; // a bit more explicit than necessary but my brain thought it was useful info std::vector::const_iterator search_reference = arr.cbegin(); std::size_t i = arr.size() - 1; for (auto elem = sorted.rbegin(); elem != sorted.rend(); elem++) { // using search reference so we don't find the same element over and over // again search_reference = std::find(search_reference, arr.cend(), *elem); std::size_t first_swap = search_reference - arr.cbegin(); std::size_t second_swap = i; // remove false positives of elements already being in the correct spot if (first_swap != second_swap) { ret.push_back(first_swap); ret.push_back(second_swap); } i--; // checking if we're done early std::reverse(intermediate.begin(), intermediate.begin() + first_swap); std::reverse(intermediate.begin(), intermediate.begin() + second_swap); // TIL that std::equal exists if (std::equal(arr.cbegin(), arr.cend(), intermediate.cbegin(), intermediate.cend())) { break; } // pushing the search reference past what we just found so we don't find // it again if ((elem + 1) != sorted.rend() && *(elem + 1) == *elem) { search_reference++; } else { search_reference = arr.cbegin(); } } return ret; } int main(void) { std::cout << "{"; std::vector arr{12, 13, 11, 14}; for (auto &e : getReversalsToSort(arr)) { std::cout << e << ","; } std::cout << "}\n"; }