From 70af121c7641c2a69245c2756b2fc9e48f915605 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 7 Aug 2022 17:19:54 +0200 Subject: [PATCH] =?UTF-8?q?4kyu:=20add=20=E2=80=9ERange=20Extraction?= =?UTF-8?q?=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit • Also add missing „Sum of Intervals“ to README Signed-off-by: Matej Focko --- 4kyu/range_extraction/solution.cpp | 68 ++++++++++++++++++++++++++++++ README.md | 5 +++ 2 files changed, 73 insertions(+) create mode 100644 4kyu/range_extraction/solution.cpp diff --git a/4kyu/range_extraction/solution.cpp b/4kyu/range_extraction/solution.cpp new file mode 100644 index 0000000..bab5929 --- /dev/null +++ b/4kyu/range_extraction/solution.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include + +namespace { + +struct range_t { + int from; + int to; + + range_t(int from, int to) : from(from), to(to) {} + void extend() { to++; } + + int size() const { return to - from + 1; } + bool prefixes(int x) const { return x == to + 1; } +}; + +std::ostream &operator<<(std::ostream &stream, const range_t &range) { + if (range.size() >= 3) { + stream << range.from << "-" << range.to; + } else { + stream << range.from; + + for (int i = range.from + 1; i <= range.to; i++) { + stream << "," << i; + } + } + return stream; +} + +} // namespace + +std::string range_extraction(std::vector args) { + if (args.empty()) { + return ""; + } + + std::vector ranges; + + for (int x : args) { + if (ranges.size() && ranges.back().prefixes(x)) { + ranges.back().extend(); + } else { + ranges.emplace_back(x, x); + } + } + + std::stringstream out; + + auto it = ranges.cbegin(); + out << (*it); + + for (++it; it != ranges.cend(); ++it) { + out << "," << (*it); + } + + return out.str(); +} + +int main() { + assert(range_extraction({-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, + 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}) == + "-6,-3-1,3-5,7-11,14,15,17-20"); + assert(range_extraction({-3, -2, -1, 2, 10, 15, 16, 18, 19, 20}) == + "-3--1,2,10,15,16,18-20"); +} diff --git a/README.md b/README.md index 237a68f..799aa79 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ - [Permutations](https://www.codewars.com/kata/5254ca2719453dcc0b00027d) - [solution](4kyu/permutations) - [Matrix Determinant](https://www.codewars.com/kata/52a382ee44408cea2500074c) - [solution](4kyu/matrix_determinant) - [Infix to Postfix Converter](https://www.codewars.com/kata/52e864d1ffb6ac25db00017f) - [solution](4kyu/infix_to_postfix_converter) +- [Range Extraction](https://www.codewars.com/kata/51ba717bb08c1cd60f00002f) - [solution](4kyu/range_extraction) ### JS @@ -52,6 +53,10 @@ - [Route Calculator](https://www.codewars.com/kata/581bc0629ad9ff9873000316) - [solution](4kyu/route_calculator) +### Java + +- [Sum of Intervals](https://www.codewars.com/kata/52b7ed099cdc285c300001cd) - [solution](4kyu/sum_of_intervals) + ## 5 kyu ### Kotlin