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