Website Summary Files Commits Branches @commit @diff @stats
path: root / Week08 / Exercise05.cpp
diff options
context:
space:
mode:
Commit5294e73a21f3402e14fcf3379c721275e2dd19c2 (patch)
Author
 Syndamia <kamen@syndamia.com>
2025-11-23 15:25:29 +0200
Committer
 Syndamia <kamen@syndamia.com>
2025-11-23 16:05:21 +0200
Files3f02cc12e0868ac043d7f937fec380b29f54c71a /Week08/Exercise05.cpp
upp-2025-solutions-5294e73a21f3402e14fcf3379c721275e2dd19c2.tar
upp-2025-solutions-5294e73a21f3402e14fcf3379c721275e2dd19c2.tar.gz
upp-2025-solutions-5294e73a21f3402e14fcf3379c721275e2dd19c2.zip
Parent3e8ac7ba4a8f410703aa5a8426f542217adcbf2f (diff)
feat(Week08): Add solutions
1 files changed, 53 insertions, 0 deletions
-rw-r--r--Week08/Exercise05.cpp53
diff --git a/Week08/Exercise05.cpp b/Week08/Exercise05.cpp
new file mode 100644
index 0000000..d046ee8
--- /dev/null
+++ b/Week08/Exercise05.cpp
@@ -0,0 +1,53 @@
+#include <iostream>
+
+const unsigned int SIZE = 3;
+
+void swap(int &a, int &b) {
+ int temp = a;
+ a = b;
+ b = temp;
+}
+
+void transpose(int mat[SIZE][SIZE]) {
+ /* Има по-проста имплементация за матрица 3x3, но тази работи за всякакъв размер матрица.
+ * Каква е идеята: движим се по диагоналите над главния и разменяме елементите със съответния
+ * диагонал под главния.
+ *
+ * Ето така обикаляме, като числото показва използваната diagDist и плюсовете маркират главния диагонал:
+ * +1234
+ * 1+123
+ * 21+12
+ * 321+1
+ * 4321+
+ *
+ * Би трябвало да е очевидно, че първия ред ще участва във всеки диагонал.
+ * Затова, почваме от елемента на първия ред, който участва в текущия диагонал, и от там
+ * увеличаваме реда и колоната на всяка итерация.
+ *
+ * Когато имаме позиция над главния диагонал, стигаме до тази под главния като просто
+ * разменим реда и колоната.
+ *
+ * Ако не разбирате някои от тези сметки/индексирания, просто си разпишете някой по-голям пример.
+ */
+ for (unsigned int diagDist = 1; diagDist < SIZE; diagDist++)
+ for (unsigned int diagElem = 0; diagElem + diagDist < SIZE; diagElem++)
+ swap(mat[diagElem][diagElem + diagDist], mat[diagElem + diagDist][diagElem]);
+}
+
+int main() {
+ int mat[SIZE][SIZE];
+
+ for (unsigned int i = 0; i < SIZE; i++)
+ for (unsigned int j = 0; j < SIZE; j++)
+ std::cin >> mat[i][j];
+
+ transpose(mat);
+
+ for (unsigned int i = 0; i < SIZE; i++) {
+ for (unsigned int j = 0; j < SIZE; j++)
+ std::cout << mat[i][j] << ' ';
+ std::cout << std::endl;
+ }
+
+ return 0;
+}