Website Summary Files Commits Branches @commit @diff @stats
path: root / Week12 / Exercise02.cpp
diff options
context:
space:
mode:
Commit3c427559e32750c40bbd0d95b525ea42e3b37fc7 (patch)
Author
 Syndamia <kamen@syndamia.com>
2025-12-23 22:22:32 +0200
Committer
 Syndamia <kamen@syndamia.com>
2025-12-23 22:22:32 +0200
Filesafd81633d93fc7687959952b2076d34be3a9689d /Week12/Exercise02.cpp
upp-2025-solutions-3c427559e32750c40bbd0d95b525ea42e3b37fc7.tar
upp-2025-solutions-3c427559e32750c40bbd0d95b525ea42e3b37fc7.tar.gz
upp-2025-solutions-3c427559e32750c40bbd0d95b525ea42e3b37fc7.zip
Parent6bb7b68394ebebbc69e76bee59e9351386115453 (diff)
feat(Week12): Add solutions to most exercises
1 files changed, 89 insertions, 0 deletions
-rw-r--r--Week12/Exercise02.cpp89
diff --git a/Week12/Exercise02.cpp b/Week12/Exercise02.cpp
new file mode 100644
index 0000000..1b884a5
--- /dev/null
+++ b/Week12/Exercise02.cpp
@@ -0,0 +1,89 @@
+#include <iostream>
+
+unsigned int findSpace(const char* text, unsigned int start, unsigned int size) {
+ for (unsigned int i = start; i < size; i++)
+ if (text[i] == ' ')
+ return i;
+ return size;
+}
+
+void fitToColumns(char* text, unsigned int size, unsigned int columns) {
+ unsigned indexInColumn = 0;
+ unsigned int lastSpace = size;
+
+ for (unsigned int i = 0; i < size; i++) {
+ if (text[i] == ' ')
+ lastSpace = i;
+
+ if (indexInColumn == columns) {
+ // Ако следващия знак е шпация, разделяме реда на него,
+ // вместо на предходна шпация (ако има такава).
+ // Това побира по-добре нашите полета и оправя пример 3.
+ if (i + 1 < size && text[i + 1] == ' ')
+ lastSpace = i + 1;
+ else if (i + 1 == size)
+ return;
+
+ if (lastSpace >= size)
+ lastSpace = findSpace(text, i, size);
+
+ if (lastSpace >= size)
+ return;
+
+ text[lastSpace] = '\n';
+ i = lastSpace + 1;
+
+ indexInColumn = 0;
+ lastSpace = size;
+ }
+ else {
+ indexInColumn++;
+ }
+ }
+}
+
+char* getInput(unsigned &allocated, unsigned &size);
+
+int main() {
+ unsigned int allocated, size;
+ char* text = getInput(allocated, size);
+
+ unsigned int columns;
+ std::cin >> columns;
+
+ fitToColumns(text, size, columns - 1);
+ std::cout << text << std::endl;
+
+ delete[] text;
+
+ return 0;
+}
+
+char* getInput(unsigned &allocated, unsigned &size) {
+ allocated = 8;
+ size = 0;
+
+ char* input = new char[allocated];
+
+ char curr;
+ std::cin.get(curr);
+ while (curr != '\n') {
+ input[size++] = curr;
+ std::cin.get(curr);
+
+ // Реоразмеряване
+ if (size >= allocated) {
+ allocated *= 2;
+ char* newSentenceArray = new char[allocated];
+
+ for (unsigned i = 0; i < size; i++)
+ newSentenceArray[i] = input[i];
+
+ delete[] input;
+ input = newSentenceArray;
+ }
+ }
+ input[size] = '\0';
+
+ return input;
+}