From 3fa6b95dd9cb2cfc0d45652a06bf91e36678b67f Mon Sep 17 00:00:00 2001 From: mustafaaydn Date: Mon, 29 Jan 2024 00:09:36 +0300 Subject: add solutions --- challenge-253/witawayar/cpp/ch-2.cpp | 58 ++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 challenge-253/witawayar/cpp/ch-2.cpp (limited to 'challenge-253/witawayar/cpp/ch-2.cpp') diff --git a/challenge-253/witawayar/cpp/ch-2.cpp b/challenge-253/witawayar/cpp/ch-2.cpp new file mode 100644 index 0000000000..cd14a85981 --- /dev/null +++ b/challenge-253/witawayar/cpp/ch-2.cpp @@ -0,0 +1,58 @@ +// g++ -Wall -Wextra -Wpedantic -std=c++17 cpp/ch-2.cpp +#include // transform +#include // cout +#include // accumulate +#include // stringstream +#include // tie +#include + +std::vector fun(std::vector> const& matrix) { + std::vector>> aug_matrix; + for (std::size_t idx{0}; idx < matrix.size(); ++idx) { + aug_matrix.emplace_back(idx, matrix[idx]); + } + std::sort(aug_matrix.begin(), aug_matrix.end(), + [](auto& vec_a, auto& vec_b) { + auto a_sum = std::accumulate(vec_a.second.cbegin(), vec_a.second.cend(), 0); + auto b_sum = std::accumulate(vec_b.second.cbegin(), vec_b.second.cend(), 0); + return std::tie(a_sum, vec_a.first) < std::tie(b_sum, vec_b.first); + }); + std::vector sorter_indexes; + std::transform(aug_matrix.cbegin(), aug_matrix.cend(), + std::back_inserter(sorter_indexes), + [](auto& pair) { return pair.first; }); + return sorter_indexes; +} + +int main(void) { + // Tests + std::vector>, std::vector>> tests = { + { + { + {1, 1, 0, 0, 0}, + {1, 1, 1, 1, 0}, + {1, 0, 0, 0, 0}, + {1, 1, 0, 0, 0}, + {1, 1, 1, 1, 1} + }, {2, 0, 3, 1, 4}}, + { + { + {1, 0, 0, 0}, + {1, 1, 1, 1}, + {1, 0, 0, 0}, + {1, 0, 0, 0} + }, {0, 2, 3, 1}} + }; + + std::size_t test_case{0}; + for (const auto& [input, expected_output] : tests) { + auto got = fun(input); + if (got != expected_output) { + std::stringstream error_msg; + error_msg << "Failed at " << test_case++ << "th test case"; + throw std::runtime_error(error_msg.str()); + } + } + + std::cout << "done-testing, success\n"; +} -- cgit