aboutsummaryrefslogtreecommitdiff
path: root/week03/Exercise7.cpp
diff options
context:
space:
mode:
authorSyndamia <kamen@syndamia.com>2024-03-07 18:00:02 +0200
committerSyndamia <kamen@syndamia.com>2024-03-07 18:00:02 +0200
commita2c7c3ac1fb6e3c877f58f2bab1754f4d93e522f (patch)
treeb44282a01417c35f47f543ca61ccc2de2e8dbb40 /week03/Exercise7.cpp
parentc4efdf0a5b9af3d70d75f4ab642305d44e27ba1f (diff)
downloadoop-2023-solutions-a2c7c3ac1fb6e3c877f58f2bab1754f4d93e522f.tar
oop-2023-solutions-a2c7c3ac1fb6e3c877f58f2bab1754f4d93e522f.tar.gz
oop-2023-solutions-a2c7c3ac1fb6e3c877f58f2bab1754f4d93e522f.zip
[w3] Solved exercises 5-7
Diffstat (limited to 'week03/Exercise7.cpp')
-rw-r--r--week03/Exercise7.cpp58
1 files changed, 58 insertions, 0 deletions
diff --git a/week03/Exercise7.cpp b/week03/Exercise7.cpp
new file mode 100644
index 0000000..4c7975b
--- /dev/null
+++ b/week03/Exercise7.cpp
@@ -0,0 +1,58 @@
+#include <iostream>
+
+int max(int a, int b) {
+ return (a > b) ? a : b;
+}
+
+struct Interval {
+private:
+ int left;
+ int right;
+public:
+ Interval(int left, int right) {
+ if (left > right) throw "Left cannot be greater than right!";
+
+ this->left = left;
+ this->right = right;
+ }
+
+ int getLeft() {
+ return left;
+ }
+ int getRight() {
+ return right;
+ }
+
+ bool TryMergeWith(Interval*& other) {
+ if (this == nullptr || other == nullptr || other == this || right < other->left || other->right < left)
+ return false;
+
+ left = max(left, other->left);
+ right = max(right, other->right);
+
+ delete other;
+ other = nullptr;
+
+ return true;
+ }
+};
+
+int main() {
+ Interval* ivs[] = { new Interval(0, 3), new Interval(3, 5), new Interval(3, 8),
+ new Interval(10, 15),
+ new Interval(30, 80), };
+ int size = 5;
+ for (int i = 0; i < size; i++) {
+ for (int j = 0; j < size; j++) {
+ ivs[i]->TryMergeWith(ivs[j]);
+ }
+ }
+
+ for (int i = 0; i < size; i++) {
+ if (ivs[i] != nullptr) {
+ std::cout << "[" << ivs[i]->getLeft() << ", " << ivs[i]->getRight() << "]";
+ delete ivs[i];
+ }
+ }
+ std::cout << std::endl;
+}