Website Summary Files Commits Branches @commit @diff @stats
path: root / Practicum / pract03 / solutions.cpp
diff options
context:
space:
mode:
Commit097b0826ae970e3115c7ba59648074b31a821896 (patch)
Author
 Desislava Shunina <115353472+desiish@users.noreply.github.com>
2024-10-29 19:21:46 +0200
Committer
 GitHub <noreply@github.com>
2024-10-29 19:21:46 +0200
Files4ab6d2e05223033578b48c111eadc03933cf7313 /Practicum/pract03/solutions.cpp
Data-structures-and-algorithms-097b0826ae970e3115c7ba59648074b31a821896.tar
Data-structures-and-algorithms-097b0826ae970e3115c7ba59648074b31a821896.tar.gz
Data-structures-and-algorithms-097b0826ae970e3115c7ba59648074b31a821896.zip
Parente35c6f6a3cbb8fc5c0d498db21043f9456f11427 (diff)
add solutions pract03
1 files changed, 106 insertions, 0 deletions
-rw-r--r--Practicum/pract03/solutions.cpp106
diff --git a/Practicum/pract03/solutions.cpp b/Practicum/pract03/solutions.cpp
new file mode 100644
index 0000000..2370a93
--- /dev/null
+++ b/Practicum/pract03/solutions.cpp
@@ -0,0 +1,106 @@
+#include <iostream>
+#include <algorithm>
+#include <vector>
+using namespace std;
+
+//Task 1
+void orderByFirstLetter(vector<string>& words)
+{
+ auto first = words.begin();
+ auto last = words.end();
+
+ for (char letter = 'a'; letter <= 'z'; letter++)
+ {
+ auto new_beg = partition(first, last, [letter](const string& str) { return str[0] == letter; });
+ first = new_beg;
+ }
+}
+
+//Task 2
+bool isEven(int n)
+{
+ return n % 2 == 0;
+}
+
+bool isOdd(int n)
+{
+ return n % 2;
+}
+
+template <class Pred>
+void mergeSortedPred(vector<int>& res, const vector<int>& first, const vector<int>& second, Pred p)
+{
+ auto beg1 = first.begin();
+ auto beg2 = second.begin();
+
+ auto end1 = first.end();
+ auto end2 = second.end();
+
+ while (beg1 != end1 && beg2 != end2)
+ {
+ if (p(*beg1) && p(*beg2))
+ {
+ if (*beg1 <= *beg2)
+ {
+ res.push_back(*beg1);
+ ++beg1;
+ }
+ else
+ {
+ res.push_back(*beg2);
+ ++beg2;
+ }
+ }
+ else
+ {
+ if (!p(*beg1))
+ ++beg1;
+
+ if (!p(*beg2))
+ ++beg2;
+ }
+ }
+
+ while (beg1 != end1)
+ {
+ if (p(*beg1))
+ res.push_back(*beg1);
+
+ ++beg1;
+ }
+
+ while (beg2 != end2)
+ {
+ if (p(*beg2))
+ res.push_back(*beg2);
+
+ ++beg2;
+ }
+}
+vector<int> mergeSortedEvensAndOdds(const vector<int>& first, const vector<int>& second)
+{
+ vector<int> res;
+ mergeSortedPred(res, first, second, isEven);
+ mergeSortedPred(res, first, second, isOdd);
+
+ return res;
+}
+
+int main()
+{
+ //task 1
+ vector<string> v = { "banana", "apple", "alpaca", "cat", "biscuit", "elephant", "string", "house", "progress", "trousers", "mouse" };
+ orderByFirstLetter(v);
+
+ for (auto it = v.begin(); it != v.end(); ++it)
+ cout << *it << " ";
+
+ //task 2
+ vector<int> v1 = { 1, 2, 3, 4, 5 };
+ vector<int> v2 = { 5, 17, 32, 80, 81, 82, 83 };
+
+ vector<int> res = mergeSortedEvensAndOdds(v1, v2);
+
+ for (auto it = res.begin(); it != res.end(); ++it)
+ std::cout << *it << " ";
+}