From 88e0b5ed69a91709d2a4b08d2bda1c80ccb7d075 Mon Sep 17 00:00:00 2001 From: JirR02 Date: Mon, 31 Mar 2025 08:40:43 +0200 Subject: [PATCH] Converted everything to orgmode converted everything to orgmode and added solution to the README files --- Informatik_I/Bonus_1/README.md | 19 -- Informatik_I/Bonus_1/{game.cpp => README.org} | 31 +++ .../Bonus_1/pictures/horizontal_00.svg | 112 -------- .../Bonus_1/pictures/horizontal_21.svg | 112 -------- .../Bonus_1/pictures/horizontal_idx.svg | 208 -------------- Informatik_I/Bonus_1/pictures/isboxdrawn0.svg | 122 --------- Informatik_I/Bonus_1/pictures/isboxdrawn1.svg | 151 ---------- Informatik_I/Bonus_1/pictures/vertical_00.svg | 112 -------- Informatik_I/Bonus_1/pictures/vertical_12.svg | 112 -------- .../Bonus_1/pictures/vertical_idx.svg | 222 --------------- Informatik_I/Examples/Week_1/README.md | 13 - Informatik_I/Examples/Week_1/main.cpp | 22 -- Informatik_I/Exercise_1/Task_1/README.md | 17 -- Informatik_I/Exercise_1/Task_1/README.org | 52 ++++ Informatik_I/Exercise_1/Task_1/main.md | 23 -- Informatik_I/Exercise_1/Task_2/README.md | 24 -- Informatik_I/Exercise_1/Task_2/README.org | 50 ++++ Informatik_I/Exercise_1/Task_2/submission.txt | 14 - Informatik_I/Exercise_1/Task_3/README.md | 18 -- Informatik_I/Exercise_1/Task_3/README.org | 55 ++++ Informatik_I/Exercise_1/Task_3/resistance.cpp | 25 -- Informatik_I/Exercise_2/task_1/README.md | 14 - Informatik_I/Exercise_2/task_1/README.org | 37 +++ Informatik_I/Exercise_2/task_1/solutions.txt | 17 -- Informatik_I/Exercise_2/task_2/README.md | 25 -- Informatik_I/Exercise_2/task_2/README.org | 86 ++++++ Informatik_I/Exercise_2/task_2/solutions.cpp | 49 ---- Informatik_I/Exercise_2/task_3a/README.md | 21 -- .../task_3a/{main.cpp => README.org} | 32 +++ Informatik_I/Exercise_2/task_3b/README.md | 58 ---- Informatik_I/Exercise_2/task_3b/README.org | 94 +++++++ Informatik_I/Exercise_2/task_3b/main.cpp | 26 -- Informatik_I/Exercise_2/task_4/README.md | 14 - Informatik_I/Exercise_2/task_4/README.org | 54 ++++ Informatik_I/Exercise_2/task_4/main.cpp | 32 --- Informatik_I/Exercise_3/Task_1/README.md | 24 -- .../Task_1/{loop.cpp => README.org} | 36 +++ Informatik_I/Exercise_3/Task_2/README.md | 23 -- .../Task_2/{loop.cpp => README.org} | 35 +++ Informatik_I/Exercise_3/Task_3/README.md | 27 -- Informatik_I/Exercise_3/Task_3/README.org | 92 +++++++ Informatik_I/Exercise_3/Task_3/loop.cpp | 54 ---- Informatik_I/Exercise_3/Task_4a/README.md | 19 -- Informatik_I/Exercise_3/Task_4a/README.org | 61 +++++ Informatik_I/Exercise_3/Task_4a/main.cpp | 30 -- Informatik_I/Exercise_3/Task_4b/README.md | 20 -- Informatik_I/Exercise_3/Task_4b/README.org | 66 +++++ Informatik_I/Exercise_3/Task_4b/main.cpp | 35 --- Informatik_I/Exercise_4/Task_1/README.md | 19 -- Informatik_I/Exercise_4/Task_1/README.org | 90 ++++++ Informatik_I/Exercise_4/Task_1/solutions.txt | 60 ---- Informatik_I/Exercise_4/Task_2/README.md | 17 -- Informatik_I/Exercise_4/Task_2/README.org | 54 ++++ Informatik_I/Exercise_4/Task_2/main.cpp | 25 -- Informatik_I/Exercise_4/Task_3/README.md | 16 -- Informatik_I/Exercise_4/Task_3/README.org | 41 +++ Informatik_I/Exercise_4/Task_3/rounding.h | 13 - Informatik_I/Exercise_4/Task_4/README.md | 7 - Informatik_I/Exercise_4/Task_4/README.org | 47 ++++ Informatik_I/Exercise_4/Task_4/main.cpp | 28 -- Informatik_I/Exercise_5/Task_1/README.md | 50 ---- Informatik_I/Exercise_5/Task_1/README.org | 152 +++++++++++ Informatik_I/Exercise_5/Task_1/calendar.cpp | 90 ------ Informatik_I/Exercise_5/Task_2/README.md | 8 - Informatik_I/Exercise_5/Task_2/README.org | 57 ++++ Informatik_I/Exercise_5/Task_2/functions.cpp | 38 --- Informatik_I/Exercise_5/Task_3/README.md | 28 -- Informatik_I/Exercise_5/Task_3/README.org | 74 +++++ Informatik_I/Exercise_5/Task_3/main.md | 35 --- .../Task_4/{README.md => README.org} | 115 ++++++-- Informatik_I/Exercise_5/Task_4/run_length.cpp | 63 ----- Projekt_1/Task_1/guess_a_number.cpp | 33 --- Projekt_1/Task_1/guess_a_number.h | 15 - Projekt_1/Task_1/main.cpp | 22 -- Projekt_1/Task_2/guess_a_number.cpp | 49 ---- Projekt_1/Task_2/guess_a_number.h | 82 ------ Projekt_1/Task_2/main.cpp | 48 ---- Projekt_2/README.md | 50 ---- Projekt_2/hangman.cpp | 69 ----- Projekt_2/hangman.h | 97 ------- Projekt_2/main.cpp | 69 ----- Projekt_2/termcolor.h | 20 -- Projekt_2/words.csv | 100 ------- README.md => README.org | 9 +- Vorkurs/Projekt_1/Task_1/README.org | 127 +++++++++ Vorkurs/Projekt_1/Task_2/README.org | 161 +++++++++++ Vorkurs/Projekt_2/README.org | 258 ++++++++++++++++++ Vorkurs/Projekt_2/game.png | Bin 0 -> 1956 bytes 88 files changed, 1942 insertions(+), 2989 deletions(-) delete mode 100644 Informatik_I/Bonus_1/README.md rename Informatik_I/Bonus_1/{game.cpp => README.org} (75%) delete mode 100644 Informatik_I/Bonus_1/pictures/horizontal_00.svg delete mode 100644 Informatik_I/Bonus_1/pictures/horizontal_21.svg delete mode 100644 Informatik_I/Bonus_1/pictures/horizontal_idx.svg delete mode 100644 Informatik_I/Bonus_1/pictures/isboxdrawn0.svg delete mode 100644 Informatik_I/Bonus_1/pictures/isboxdrawn1.svg delete mode 100644 Informatik_I/Bonus_1/pictures/vertical_00.svg delete mode 100644 Informatik_I/Bonus_1/pictures/vertical_12.svg delete mode 100644 Informatik_I/Bonus_1/pictures/vertical_idx.svg delete mode 100644 Informatik_I/Examples/Week_1/README.md delete mode 100644 Informatik_I/Examples/Week_1/main.cpp delete mode 100644 Informatik_I/Exercise_1/Task_1/README.md create mode 100644 Informatik_I/Exercise_1/Task_1/README.org delete mode 100644 Informatik_I/Exercise_1/Task_1/main.md delete mode 100644 Informatik_I/Exercise_1/Task_2/README.md create mode 100644 Informatik_I/Exercise_1/Task_2/README.org delete mode 100644 Informatik_I/Exercise_1/Task_2/submission.txt delete mode 100644 Informatik_I/Exercise_1/Task_3/README.md create mode 100644 Informatik_I/Exercise_1/Task_3/README.org delete mode 100644 Informatik_I/Exercise_1/Task_3/resistance.cpp delete mode 100644 Informatik_I/Exercise_2/task_1/README.md create mode 100644 Informatik_I/Exercise_2/task_1/README.org delete mode 100644 Informatik_I/Exercise_2/task_1/solutions.txt delete mode 100644 Informatik_I/Exercise_2/task_2/README.md create mode 100644 Informatik_I/Exercise_2/task_2/README.org delete mode 100644 Informatik_I/Exercise_2/task_2/solutions.cpp delete mode 100644 Informatik_I/Exercise_2/task_3a/README.md rename Informatik_I/Exercise_2/task_3a/{main.cpp => README.org} (52%) delete mode 100644 Informatik_I/Exercise_2/task_3b/README.md create mode 100644 Informatik_I/Exercise_2/task_3b/README.org delete mode 100644 Informatik_I/Exercise_2/task_3b/main.cpp delete mode 100644 Informatik_I/Exercise_2/task_4/README.md create mode 100644 Informatik_I/Exercise_2/task_4/README.org delete mode 100644 Informatik_I/Exercise_2/task_4/main.cpp delete mode 100644 Informatik_I/Exercise_3/Task_1/README.md rename Informatik_I/Exercise_3/Task_1/{loop.cpp => README.org} (52%) delete mode 100644 Informatik_I/Exercise_3/Task_2/README.md rename Informatik_I/Exercise_3/Task_2/{loop.cpp => README.org} (55%) delete mode 100644 Informatik_I/Exercise_3/Task_3/README.md create mode 100644 Informatik_I/Exercise_3/Task_3/README.org delete mode 100644 Informatik_I/Exercise_3/Task_3/loop.cpp delete mode 100644 Informatik_I/Exercise_3/Task_4a/README.md create mode 100644 Informatik_I/Exercise_3/Task_4a/README.org delete mode 100644 Informatik_I/Exercise_3/Task_4a/main.cpp delete mode 100644 Informatik_I/Exercise_3/Task_4b/README.md create mode 100644 Informatik_I/Exercise_3/Task_4b/README.org delete mode 100644 Informatik_I/Exercise_3/Task_4b/main.cpp delete mode 100644 Informatik_I/Exercise_4/Task_1/README.md create mode 100644 Informatik_I/Exercise_4/Task_1/README.org delete mode 100644 Informatik_I/Exercise_4/Task_1/solutions.txt delete mode 100644 Informatik_I/Exercise_4/Task_2/README.md create mode 100644 Informatik_I/Exercise_4/Task_2/README.org delete mode 100644 Informatik_I/Exercise_4/Task_2/main.cpp delete mode 100644 Informatik_I/Exercise_4/Task_3/README.md create mode 100644 Informatik_I/Exercise_4/Task_3/README.org delete mode 100644 Informatik_I/Exercise_4/Task_3/rounding.h delete mode 100644 Informatik_I/Exercise_4/Task_4/README.md create mode 100644 Informatik_I/Exercise_4/Task_4/README.org delete mode 100644 Informatik_I/Exercise_4/Task_4/main.cpp delete mode 100644 Informatik_I/Exercise_5/Task_1/README.md create mode 100644 Informatik_I/Exercise_5/Task_1/README.org delete mode 100644 Informatik_I/Exercise_5/Task_1/calendar.cpp delete mode 100644 Informatik_I/Exercise_5/Task_2/README.md create mode 100644 Informatik_I/Exercise_5/Task_2/README.org delete mode 100644 Informatik_I/Exercise_5/Task_2/functions.cpp delete mode 100644 Informatik_I/Exercise_5/Task_3/README.md create mode 100644 Informatik_I/Exercise_5/Task_3/README.org delete mode 100644 Informatik_I/Exercise_5/Task_3/main.md rename Informatik_I/Exercise_5/Task_4/{README.md => README.org} (54%) delete mode 100644 Informatik_I/Exercise_5/Task_4/run_length.cpp delete mode 100644 Projekt_1/Task_1/guess_a_number.cpp delete mode 100644 Projekt_1/Task_1/guess_a_number.h delete mode 100644 Projekt_1/Task_1/main.cpp delete mode 100644 Projekt_1/Task_2/guess_a_number.cpp delete mode 100644 Projekt_1/Task_2/guess_a_number.h delete mode 100644 Projekt_1/Task_2/main.cpp delete mode 100644 Projekt_2/README.md delete mode 100644 Projekt_2/hangman.cpp delete mode 100644 Projekt_2/hangman.h delete mode 100644 Projekt_2/main.cpp delete mode 100644 Projekt_2/termcolor.h delete mode 100644 Projekt_2/words.csv rename README.md => README.org (65%) create mode 100644 Vorkurs/Projekt_1/Task_1/README.org create mode 100644 Vorkurs/Projekt_1/Task_2/README.org create mode 100644 Vorkurs/Projekt_2/README.org create mode 100644 Vorkurs/Projekt_2/game.png diff --git a/Informatik_I/Bonus_1/README.md b/Informatik_I/Bonus_1/README.md deleted file mode 100644 index 0f5d1ff..0000000 --- a/Informatik_I/Bonus_1/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Project overview - -The goal of this project is to implement a game called _Dots And Boxes_: two players, **A** and **B**, take turns to draw lines connecting dots on a $m \times n$ (here $2 \times 2$) board. - -If a player manages to close a box (a $1 \times 1$ square surrounded by lines), the player claims the box by placing its token (**A/B**) in the box, and the player gets another turn. The game is finished when all boxes have been claimed, and the player with the most claimed boxes wins. Note that, even if a player claims multiple boxes in a single move, they would only get one extra move. - -For example, in the following game player **A** won: - -![](./pictures/dots_and_boxes.svg) - -## Your task - -The file `game.cpp` contains a partial implementation of the game. The main game loop is implemented in the function `play_game(grid)`. This function is called from `main.cpp` and gets the game grid as an argument. The game grid is already fully implemented. We describe the functionality it provides in a following section below. - -Your task is extending the game implementation in file `game.cpp` such that it works the way described above. We provide some functions in this file and thus suggest a certain structure -- but you are completely free to do it your way. Add, remove or change anything you want. The only constraint is that you must implement the function play_game which takes the game grid as argument. You are of course free to change the body of this function in whatever way you like. - -If you do decide to change the body of the play_game function be careful to not accidentally change the format of the outputs it generates. For example: If you change the output `std::cout << "Game finished" << std::endl;` to `std::cout << "Game Finished" << std::endl;` you will not pass some test cases. The autograder is very picky when checking whether or not your outputs are correct. You can get all the points in this exercise without changing any of the output lines in the template. - -_Note_: More Information on the the concept of the game on Code Expert. diff --git a/Informatik_I/Bonus_1/game.cpp b/Informatik_I/Bonus_1/README.org similarity index 75% rename from Informatik_I/Bonus_1/game.cpp rename to Informatik_I/Bonus_1/README.org index 3dae544..9baadb7 100644 --- a/Informatik_I/Bonus_1/game.cpp +++ b/Informatik_I/Bonus_1/README.org @@ -1,3 +1,29 @@ +#+TITLE: Dot and Boxes +#+AUTHOR: JirR02 + +* Project overview + +The goal of this project is to implement a game called _Dots And Boxes_: two players, **A** and **B**, take turns to draw lines connecting dots on a \(m \times n\) (here \(2 \times 2\)) board. + +If a player manages to close a box (a \(1 \times 1\) square surrounded by lines), the player claims the box by placing its token (**A/B**) in the box, and the player gets another turn. The game is finished when all boxes have been claimed, and the player with the most claimed boxes wins. Note that, even if a player claims multiple boxes in a single move, they would only get one extra move. + +For example, in the following game player **A** won: + +[[./pictures/dots_and_boxes.svg]] + +* Your task + +The file =game.cpp= contains a partial implementation of the game. The main game loop is implemented in the function =play_game(grid)=. This function is called from =main.cpp= and gets the game grid as an argument. The game grid is already fully implemented. We describe the functionality it provides in a following section below. + +Your task is extending the game implementation in file =game.cpp= such that it works the way described above. We provide some functions in this file and thus suggest a certain structure -- but you are completely free to do it your way. Add, remove or change anything you want. The only constraint is that you must implement the function play_game which takes the game grid as argument. You are of course free to change the body of this function in whatever way you like. + +If you do decide to change the body of the play_game function be careful to not accidentally change the format of the outputs it generates. For example: If you change the output =std::cout << "Game finished" << std::endl;= to =std::cout << "Game Finished" << std::endl;= you will not pass some test cases. The autograder is very picky when checking whether or not your outputs are correct. You can get all the points in this exercise without changing any of the output lines in the template. + +/Note/: More Information on the the concept of the game on Code Expert. + +* Solution + +#+begin_src cpp #include "game.h" #include @@ -240,3 +266,8 @@ void play_game(Grid &grid) { std::cout << "Player " << winner << " wins!" << std::endl; } } +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Bonus_1/pictures/horizontal_00.svg b/Informatik_I/Bonus_1/pictures/horizontal_00.svg deleted file mode 100644 index c3897cc..0000000 --- a/Informatik_I/Bonus_1/pictures/horizontal_00.svg +++ /dev/null @@ -1,112 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - diff --git a/Informatik_I/Bonus_1/pictures/horizontal_21.svg b/Informatik_I/Bonus_1/pictures/horizontal_21.svg deleted file mode 100644 index 11a94fa..0000000 --- a/Informatik_I/Bonus_1/pictures/horizontal_21.svg +++ /dev/null @@ -1,112 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - diff --git a/Informatik_I/Bonus_1/pictures/horizontal_idx.svg b/Informatik_I/Bonus_1/pictures/horizontal_idx.svg deleted file mode 100644 index d095795..0000000 --- a/Informatik_I/Bonus_1/pictures/horizontal_idx.svg +++ /dev/null @@ -1,208 +0,0 @@ - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - 0,0 - 0,1 - 1,0 - 1,1 - 2,0 - 2,1 - diff --git a/Informatik_I/Bonus_1/pictures/isboxdrawn0.svg b/Informatik_I/Bonus_1/pictures/isboxdrawn0.svg deleted file mode 100644 index 608b26e..0000000 --- a/Informatik_I/Bonus_1/pictures/isboxdrawn0.svg +++ /dev/null @@ -1,122 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - diff --git a/Informatik_I/Bonus_1/pictures/isboxdrawn1.svg b/Informatik_I/Bonus_1/pictures/isboxdrawn1.svg deleted file mode 100644 index 37017c8..0000000 --- a/Informatik_I/Bonus_1/pictures/isboxdrawn1.svg +++ /dev/null @@ -1,151 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Informatik_I/Bonus_1/pictures/vertical_00.svg b/Informatik_I/Bonus_1/pictures/vertical_00.svg deleted file mode 100644 index 6a768cf..0000000 --- a/Informatik_I/Bonus_1/pictures/vertical_00.svg +++ /dev/null @@ -1,112 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - diff --git a/Informatik_I/Bonus_1/pictures/vertical_12.svg b/Informatik_I/Bonus_1/pictures/vertical_12.svg deleted file mode 100644 index aa9304a..0000000 --- a/Informatik_I/Bonus_1/pictures/vertical_12.svg +++ /dev/null @@ -1,112 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - diff --git a/Informatik_I/Bonus_1/pictures/vertical_idx.svg b/Informatik_I/Bonus_1/pictures/vertical_idx.svg deleted file mode 100644 index 2fd56e7..0000000 --- a/Informatik_I/Bonus_1/pictures/vertical_idx.svg +++ /dev/null @@ -1,222 +0,0 @@ - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - 0,0 - 0,1 - 1,0 - 0,2 - 1,1 - 1,2 - - diff --git a/Informatik_I/Examples/Week_1/README.md b/Informatik_I/Examples/Week_1/README.md deleted file mode 100644 index a8a2828..0000000 --- a/Informatik_I/Examples/Week_1/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# Task - -Write a program which reads in an integer a larger than `1000` and outputs its last three digits. For example, if `a=14325`, the output should be `3 2 5`. - -_Hint_: You need to use integer division and modulo operators. - -# Input - -An integer larger than `1000`. - -# Output - -Last three digits separated by spaces. diff --git a/Informatik_I/Examples/Week_1/main.cpp b/Informatik_I/Examples/Week_1/main.cpp deleted file mode 100644 index c5fa680..0000000 --- a/Informatik_I/Examples/Week_1/main.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include - -int main() { - - int a; - std::cin >> a; // get input of for a - - if (a >= 1000) { // check if input is greater than 1000 - int b = a % 10; // get last digit - a /= 10; - int c = a % 10; // get second digit - a /= 10; - int d = a % 10; // get first digit - - std::cout << d << " " << c << " " - << b; // output first, second, and last digit - } else { // if input not greater than 1000 return 0 - return 0; - } - - return 0; -} diff --git a/Informatik_I/Exercise_1/Task_1/README.md b/Informatik_I/Exercise_1/Task_1/README.md deleted file mode 100644 index 12710bb..0000000 --- a/Informatik_I/Exercise_1/Task_1/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# Task - -Let `a`, `b`, `c`, and `d` be variables of type `int`. - -- Which of the following character sequences are valid expressions in the sense that they are accepted by a C++ Compiler? Explain your answer. - -1. a = b = 5 -1. 1 = a -1. ++a + b++ -1. a + b = c + d -1. a = 2 b - -Assume that all the variables have been defined and correctly initialized and that all expressions are completely independent from each other. - -- For each of the expressions that you have identified as valid, decide whether the entire expression is an `lvalue` or an `rvalue`, and explain your decision. - -- Determine the values of the expressions that you have identified as valid and explain how these values are obtained. diff --git a/Informatik_I/Exercise_1/Task_1/README.org b/Informatik_I/Exercise_1/Task_1/README.org new file mode 100644 index 0000000..7c5b490 --- /dev/null +++ b/Informatik_I/Exercise_1/Task_1/README.org @@ -0,0 +1,52 @@ +#+TITLE: Task 1: Expressions +#+AUTHOR: JirR02 + +* Task + +Let =a=, =b=, =c=, and =d= be variables of type =int=. + +- Which of the following character sequences are valid expressions in the sense that they are accepted by a C++ Compiler? Explain your answer. + +1. a = b = 5 +1. 1 = a +1. ++a + b++ +1. a + b = c + d +1. a = 2 b + +Assume that all the variables have been defined and correctly initialized and that all expressions are completely independent from each other. + +- For each of the expressions that you have identified as valid, decide whether the entire expression is an =lvalue= or an =rvalue=, and explain your decision. + +- Determine the values of the expressions that you have identified as valid and explain how these values are obtained. + +* Solution + +#+begin_src md +# Task 1 + +--- + +### Expression 1: `a = b = 5` + +The expression is valid and will be accepted by the CPP compiler. It will result with the l-values `a = 5` and `b = 5`. This is due to the fact the the `=` opperation is read from right to left so `b = 5` will run first and `a = b` afterwards. + +### Expression 2: `1 = a` + +The expression is invalid. + +### Expression 3: `++a + b++` + +The expression is valid and will be accepted by the CPP compiler. It will result in a r-value since the result is not assigned to a variable. + +### Expression 4: `a + b = c + d` + +The expression is invalid. + +### Expression 5: `a = 2 b` + +The expression is valid and will be accepted by the CPP compiler. It will result with the l-value `a = 2 b`. This is valid since a l-value can be a r-value. +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_1/Task_1/main.md b/Informatik_I/Exercise_1/Task_1/main.md deleted file mode 100644 index 8ccd845..0000000 --- a/Informatik_I/Exercise_1/Task_1/main.md +++ /dev/null @@ -1,23 +0,0 @@ -# Task 1 - ---- - -### Expression 1: `a = b = 5` - -The expression is valid and will be accepted by the CPP compiler. It will result with the l-values `a = 5` and `b = 5`. This is due to the fact the the `=` opperation is read from right to left so `b = 5` will run first and `a = b` afterwards. - -### Expression 2: `1 = a` - -The expression is invalid. - -### Expression 3: `++a + b++` - -The expression is valid and will be accepted by the CPP compiler. It will result in a r-value since the result is not assigned to a variable. - -### Expression 4: `a + b = c + d` - -The expression is invalid. - -### Expression 5: `a = 2 b` - -The expression is valid and will be accepted by the CPP compiler. It will result with the l-value `a = 2 b`. This is valid since a l-value can be a r-value. diff --git a/Informatik_I/Exercise_1/Task_2/README.md b/Informatik_I/Exercise_1/Task_2/README.md deleted file mode 100644 index 50ee818..0000000 --- a/Informatik_I/Exercise_1/Task_2/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# Task - -_This task is a text-based task but mostly automatically checked. You are required to write your answers into submission.txt by replacing the question marks with the correct solution. Please, do not change the line formating._ - -_You can check whether your solution is correct by clicking on the test button._ - -Numbers can be provided in various formats in C++. Literals prefixed with `0b` indicate binary encoding. Assume unsigned arithmetics with sufficient numbers of bits, i.e. no overflows. Convert the following binary numbers into decimal numbers (1-4) and decimal numbers to binary (5-8): - -```txt -# Lines starting with # are comments. Spaces is ignored. -# Lines starting with a whitespace before # will not be a comment. - -# Convert to decimal: -0b1 = ? -0b10 = ? -0b000001 = ? -0b101010 = ? - -# Convert to binary: -7 = ? -11 = ? -28 = ? -1024 = ? -``` diff --git a/Informatik_I/Exercise_1/Task_2/README.org b/Informatik_I/Exercise_1/Task_2/README.org new file mode 100644 index 0000000..03f5867 --- /dev/null +++ b/Informatik_I/Exercise_1/Task_2/README.org @@ -0,0 +1,50 @@ +#+TITLE: Task 2: Representation of Integers +#+AUTHOR: JirR02 + +* Task + +/This task is a text-based task but mostly automatically checked. You are required to write your answers into =submission.txt= by replacing the question marks with the correct solution. Please, do not change the line formating./ + +/You can check whether your solution is correct by clicking on the test button./ + +Numbers can be provided in various formats in C++. Literals prefixed with =0b= indicate binary encoding. Assume unsigned arithmetics with sufficient numbers of bits, i.e. no overflows. Convert the following binary numbers into decimal numbers (1-4) and decimal numbers to binary (5-8): + +#+begin_src txt +# Lines starting with # are comments. Spaces is ignored. +# Lines starting with a whitespace before # will not be a comment. + +# Convert to decimal: +0b1 = ? +0b10 = ? +0b000001 = ? +0b101010 = ? + +# Convert to binary: +7 = ? +11 = ? +28 = ? +1024 = ? +#+end_src + +* Solutions + +#+begin_src txt +# Lines starting with # are comments. Spaces are ignored. +# Lines starting with a whitespace before # will not be a comment. + +# Convert to decimal: +0b1 = 1 +0b10 = 2 +0b000001 = 1 +0b101010 = 42 + +# Convert to binary: +7 = 0b111 +11 = 0b1011 +28 = 0b11100 +1024 = 0b10000000000 +#+end_src + +—---- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_1/Task_2/submission.txt b/Informatik_I/Exercise_1/Task_2/submission.txt deleted file mode 100644 index 3769208..0000000 --- a/Informatik_I/Exercise_1/Task_2/submission.txt +++ /dev/null @@ -1,14 +0,0 @@ -# Lines starting with # are comments. Spaces are ignored. -# Lines starting with a whitespace before # will not be a comment. - -# Convert to decimal: -0b1 = 1 -0b10 = 2 -0b000001 = 1 -0b101010 = 42 - -# Convert to binary: -7 = 0b111 -11 = 0b1011 -28 = 0b11100 -1024 = 0b10000000000 \ No newline at end of file diff --git a/Informatik_I/Exercise_1/Task_3/README.md b/Informatik_I/Exercise_1/Task_3/README.md deleted file mode 100644 index ccc598c..0000000 --- a/Informatik_I/Exercise_1/Task_3/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Task - -Write a program resistance.cpp that computes the equivalent resistance of the following wiring: - -![circuit](./resistance.png) - -We assume that $R_1$, $R_2$, $R_3$, and $R_4$ have an integer valued resistance. After input of the four values, the program should output the result arithmetically rounded to the nearest integer. - -**Remark:** In order to facilitate the task, you may want to: - -- Conceptually divide the task into sub tasks. For example, start with computation of serial resistors $R_{12}$ and $R_{34}$. -- Solve the task first naively using default rounding and then think about how to accomplish arithmetic rounding. Recall that $\text{round}(x) = [x + 0.5] \text{ }\forall \text{ } x \in \mathbb{R}$, i.e., a real number can be rounded arithmetically by adding $0.5$ to it and then rounding down. For example, $\text{round}(8,6) = [8.6 + 0.5] = [9.1] = 9$. - -You can find formulas for computing the total resistance in this [Wikipedia article](https://en.wikipedia.org/wiki/Resistor#Series_and_parallel_resistors). - -**Important:** using anything other than int (e.g., floating point numbers, long, or double long) is forbidden. - -**Important:** using if-else and any other branches is forbidden. diff --git a/Informatik_I/Exercise_1/Task_3/README.org b/Informatik_I/Exercise_1/Task_3/README.org new file mode 100644 index 0000000..851f557 --- /dev/null +++ b/Informatik_I/Exercise_1/Task_3/README.org @@ -0,0 +1,55 @@ +#+TITLE: Task 3: Equivalent Resistance +#+AUTHOR: JirR02 + +* Task + +Write a program resistance.cpp that computes the equivalent resistance of the following wiring: + +[[./resistance.png]] + +We assume that \(R_1\), \(R_2\), \(R_3\), and \(R_4\) have an integer valued resistance. After input of the four values, the program should output the result arithmetically rounded to the nearest integer. + +*Remark:* In order to facilitate the task, you may want to: + +- Conceptually divide the task into sub tasks. For example, start with computation of serial resistors \(R_{12}\) and \(R_{34}\). +- Solve the task first naively using default rounding and then think about how to accomplish arithmetic rounding. Recall that \(\text{round}(x) = [x + 0.5] \text{ }\forall \text{ } x \in \mathbb{R}\), i.e., a real number can be rounded arithmetically by adding \(0.5\) to it and then rounding down. For example, \(\text{round}(8,6) = [8.6 + 0.5] = [9.1] = 9\). + +You can find formulas for computing the total resistance in this [[https://en.wikipedia.org/wiki/Resistor#Series_and_parallel_resistors][Wikipedia article]]. + +*Important:* using anything other than =int= (e.g., floating point numbers, =long=, or =double long=) is forbidden. + +*Important:* using =if-else= and any other branches is forbidden. + +* Solution + +#+begin_src cpp +#include + +int main() { + int r1; + int r2; + int r3; + int r4; + int res; + + std::cin >> r1; + std::cin >> r2; + std::cin >> r3; + std::cin >> r4; + + int r12 = r1 + r2; + int r34 = r3 + r4; + + res = (r12 * r34 + ((r12 + r34) / 2)) / + (r12 + r34); // By adding the average of r12 and r34, the result is + // increased enough to get the correct rounded number + + std::cout << res; + + return 0; +} +#+end_src + +-—--- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_1/Task_3/resistance.cpp b/Informatik_I/Exercise_1/Task_3/resistance.cpp deleted file mode 100644 index ad71bbd..0000000 --- a/Informatik_I/Exercise_1/Task_3/resistance.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include - -int main() { - int r1; - int r2; - int r3; - int r4; - int res; - - std::cin >> r1; - std::cin >> r2; - std::cin >> r3; - std::cin >> r4; - - int r12 = r1 + r2; - int r34 = r3 + r4; - - res = (r12 * r34 + ((r12 + r34) / 2)) / - (r12 + r34); // By adding the average of r12 and r34, the result is - // increased enough to get the correct rounded number - - std::cout << res; - - return 0; -} diff --git a/Informatik_I/Exercise_2/task_1/README.md b/Informatik_I/Exercise_2/task_1/README.md deleted file mode 100644 index 3f51c8d..0000000 --- a/Informatik_I/Exercise_2/task_1/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Task 1 - -This task is a text based task. You do not need to write any program/C++ file: the answer should be written in solutions.txt according to the indicated format. Lines that start with "#" are interpreted as comments. You can run the autograder to check correctness. - -## Task - -Which of the following expressions evaluate to `true`, which to `false`? - -1. `3 >= 3` -1. `true || false && false` -1. `(true || false) && false` -1. `3 > (1 < true)` -1. `8 > 4 > 2 > 1` -1. `2 < a < 4` (a is a variable of type int) diff --git a/Informatik_I/Exercise_2/task_1/README.org b/Informatik_I/Exercise_2/task_1/README.org new file mode 100644 index 0000000..db4232c --- /dev/null +++ b/Informatik_I/Exercise_2/task_1/README.org @@ -0,0 +1,37 @@ +#+TITLE: Task 1: Expression Evaluation +#+AUTHOR: JirR02 + + +This task is a text based task. You do not need to write any program/C++ file: the answer should be written in solutions.txt according to the indicated format. Lines that start with "#" are interpreted as comments. You can run the autograder to check correctness. + +* Task + +Which of the following expressions evaluate to =true=, which to =false=? + +1. =3 >= 3= +1. =true || false && false= +1. =(true || false) && false= +1. =3 > (1 < true)= +1. =8 > 4 > 2 > 1= +1. =2 < a < 4= (a is a variable of type int) + +* Solutions + +#+begin_src txt +# Lines starting with # are comments. Spaces are ignored. + +# Replace the question marks, indicating which of the following expression evaluate to true, which to false. + + +1. 3 >= 3 == true + +2. true || false && false == true + +3. (true || false) && false == false + +4. 3 > (1 < true) == true + +5. 8 > 4 > 2 > 1 == false + +6. 2 < a < 4 == true +#+end_src diff --git a/Informatik_I/Exercise_2/task_1/solutions.txt b/Informatik_I/Exercise_2/task_1/solutions.txt deleted file mode 100644 index 73a8b0e..0000000 --- a/Informatik_I/Exercise_2/task_1/solutions.txt +++ /dev/null @@ -1,17 +0,0 @@ -# Lines starting with # are comments. Spaces are ignored. - -# Replace the question marks, indicating which of the following expression evaluate to true, which to false. - - -1. 3 >= 3 == true - -2. true || false && false == true - -3. (true || false) && false == false - -4. 3 > (1 < true) == true - -5. 8 > 4 > 2 > 1 == false - -6. 2 < a < 4 == true - diff --git a/Informatik_I/Exercise_2/task_2/README.md b/Informatik_I/Exercise_2/task_2/README.md deleted file mode 100644 index 2d75e26..0000000 --- a/Informatik_I/Exercise_2/task_2/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# Task - -Translate the following natural language expressions to `C++` expressions. Assume that all the variables are non-negative integers or boolean (of value `true` or `false`). - -_For this task you need to write the solutions in the `solutions.cpp` file, by filling the various functions that have been defined for each subtasks._ - -**Example:** $a$ is greater than $3$ and smaller than $5$. $\Longrightarrow$ Solution: - -```cpp -return a > 3 && a < 5; -``` - -_Note:_ Do not confuse the bitwise logical operators (e.g., `&`) with their binary logical counterparts (`&&`). The semantics are slightly different — bitwise operators do not exhibit short circuit evaluation. - -1. $a$ greater than $b$ and the difference between $a$ and $b$ is smaller than $15$. -1. $a$ is an even natural number greater than $a$. -1. $a$ is at most $5$ times greater than $b$ (but can also be smaller than $b$) and at least $5$ times greater than $c$. -1. Either $a$ and $b$ are both false or $c$ is true, but not both. -1. $a$ is false and $b$ is zero. - -## Input - -The program expects the task number as the first input followed by the parameters to the chosen task. For example, `3 5 1 1` selects task `3` with `a = 5`, `b = 1`, and `c = 1`. - -Note that boolean parameters for tasks 4 and 5 are entered as true and false. For example `4 true false true` would run task `4` with `a = true`, `b = false`, and `c = true`. diff --git a/Informatik_I/Exercise_2/task_2/README.org b/Informatik_I/Exercise_2/task_2/README.org new file mode 100644 index 0000000..7d8a963 --- /dev/null +++ b/Informatik_I/Exercise_2/task_2/README.org @@ -0,0 +1,86 @@ +#+TITLE: Task 2: From Natural Language to C++ +#+AUTHOR: JirR02 + +* Task + +Translate the following natural language expressions to =C++= expressions. Assume that all the variables are non-negative integers or boolean (of value =true= or =false=). + +/For this task you need to write the solutions in the =solutions.cpp= file, by filling the various functions that have been defined for each subtasks./ + +*Example:* \(a\) is greater than \(3\) and smaller than \(5\). \(\Longrightarrow\) *Solution:* + +#+begin_src cpp +return a > 3 && a < 5; +#+end_src + +/Note:/ Do not confuse the bitwise logical operators (e.g., =&=) with their binary logical counterparts (=&&=). The semantics are slightly different — bitwise operators do not exhibit short circuit evaluation. + +1. \(a\) greater than \(b\) and the difference between \(a\) and \(b\) is smaller than \(15\). +1. \(a\) is an even natural number greater than \(a\). +1. \(a\) is at most \(5\) times greater than \(b\) (but can also be smaller than \(b\)) and at least \(5\) times greater than \(c\). +1. Either \(a\) and \(b\) are both false or \(c\) is true, but not both. +1. \(a\) is false and \(b\) is zero. + +** Input + +The program expects the task number as the first input followed by the parameters to the chosen task. For example, =3 5 1 1= selects task =3= with =a = 5=, =b = 1=, and =c = 1=. + +Note that boolean parameters for tasks 4 and 5 are entered as true and false. For example =4 true false true= would run task =4= with =a = true=, =b = false=, and =c = true=. + +* Solutions + +#+begin_src cpp +#include "solutions.h" + +// Fill out each function with the appropriate expression + +bool task1(int a, int b) { + // a greater than b and the difference between a and b is smaller than 15. + if (a > b && (a - b) < 15) { + return true; + } else { + return false; + } +} + +bool task2(int a) { + // a is an even natural number greater than 3. + if (a > 3 && a % 2 == 0) { + return true; + } else { + return false; + } +} + +bool task3(int a, int b, int c) { + // a is at most 5 times greater than b (but can also be smaller than b) + // and at least 5 times greater than c. + if (a <= 5 * b && a >= 5 * c) { + return true; + } else { + return false; + } +} + +bool task4(bool a, bool b, bool c) { + // Either a and b are both false or c is true, but not both. + if ((a == false && b == false) != (c == true)) { + return true; // Replace with your solution + } else { + return false; + } +} + +bool task5(bool a, int b) { + // a is false and b is zero. + if (a == false && b == false) { + return true; + } else { + return false; // Replace with your solution + } +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_2/task_2/solutions.cpp b/Informatik_I/Exercise_2/task_2/solutions.cpp deleted file mode 100644 index e206698..0000000 --- a/Informatik_I/Exercise_2/task_2/solutions.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "solutions.h" - -// Fill out each function with the appropriate expression - -bool task1(int a, int b) { - // a greater than b and the difference between a and b is smaller than 15. - if (a > b && (a - b) < 15) { - return true; - } else { - return false; - } -} - -bool task2(int a) { - // a is an even natural number greater than 3. - if (a > 3 && a % 2 == 0) { - return true; - } else { - return false; - } -} - -bool task3(int a, int b, int c) { - // a is at most 5 times greater than b (but can also be smaller than b) - // and at least 5 times greater than c. - if (a <= 5 * b && a >= 5 * c) { - return true; - } else { - return false; - } -} - -bool task4(bool a, bool b, bool c) { - // Either a and b are both false or c is true, but not both. - if ((a == false && b == false) != (c == true)) { - return true; // Replace with your solution - } else { - return false; - } -} - -bool task5(bool a, int b) { - // a is false and b is zero. - if (a == false && b == false) { - return true; - } else { - return false; // Replace with your solution - } -} diff --git a/Informatik_I/Exercise_2/task_3a/README.md b/Informatik_I/Exercise_2/task_3a/README.md deleted file mode 100644 index 48b8c19..0000000 --- a/Informatik_I/Exercise_2/task_3a/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Task - -_Fibonacci numbers_ are the integers in the following sequence: $0, 1, 1, 2, 3, 5, 8, 13, 21, ...$. Each number is the sum of the two previous numbers. - -_Fibonacci primes_ are Fibonacci numbers that are also prime numbers. Write a program that asks the user for an integer $m$ and then computes and prints all Fibonacci primes between $0$ and $m$ (including). Print each number on a new line. - -Finally, on a new line print the total number of Fibonacci primes found. - -## Example - -If your program is asked to print the Fibonacci primes between $0$ and $14$ the output should look something like this: - -``` -2 -3 -5 -13 -Found 4 Fibonacci primes -``` - -**Important:** using anything other than `int` (e.g., `unsigned int`, floating point numbers, `long`, or double `long`) is forbidden. diff --git a/Informatik_I/Exercise_2/task_3a/main.cpp b/Informatik_I/Exercise_2/task_3a/README.org similarity index 52% rename from Informatik_I/Exercise_2/task_3a/main.cpp rename to Informatik_I/Exercise_2/task_3a/README.org index dc3e20a..a30da58 100644 --- a/Informatik_I/Exercise_2/task_3a/main.cpp +++ b/Informatik_I/Exercise_2/task_3a/README.org @@ -1,3 +1,30 @@ +#+TITLE: Task 3a: Fibonacci primes + +* Task + +/Fibonacci numbers/ are the integers in the following sequence: \(0, 1, 1, 2, 3, 5, 8, 13, 21, ...\). Each number is the sum of the two previous numbers. + +/Fibonacci primes/ are Fibonacci numbers that are also prime numbers. Write a program that asks the user for an integer \(m\) and then computes and prints all Fibonacci primes between \(0\) and \(m\) (including). Print each number on a new line. + +Finally, on a new line print the total number of Fibonacci primes found. + +** Example + +If your program is asked to print the Fibonacci primes between $0$ and $14$ the output should look something like this: + +#+begin_src shell +2 +3 +5 +13 +Found 4 Fibonacci primes +#+end_src + +*Important:* using anything other than =int= (e.g., =unsigned int=, floating point numbers, =long=, or double =long=) is forbidden. + +* Solutions + +#+begin_src cpp #include int main() { @@ -45,3 +72,8 @@ int main() { // End message std::cout << count << "\n"; } +#+end_src + +-—--- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_2/task_3b/README.md b/Informatik_I/Exercise_2/task_3b/README.md deleted file mode 100644 index 40cfeff..0000000 --- a/Informatik_I/Exercise_2/task_3b/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# Mistakes - -- The variable `j` goes into overflow which is not allowed! - -# Fibonacci overflow check - -## Background - -_Fibonacci numbers_ are the integers in the following sequence: $0, 1, 1, 2, 3, 5, 8, 13, 21, ...$, where each number is the sum of the two previous numbers. - -## Task - -Fibonacci numbers grow fast, and can thus easily exceed the value range of 32-bit `int`. Think of a general way how you can check if the result of an addition would exceed the range of a 32-bit `int` (i.e. overflow) **without actually performing the addition causing the overflow.** - -Remember that we consider **signed integers.** Because only half of the numbers are positive, this leaves us with 31 bits to store the actual positive number value. - -Write a program that asks the user for an integer $n$ and then prints the first $n$ Fibonacci numbers, each number on a new line. Use an `int` (we assume 32 bits, including the sign) to represent the current Fibonacci number. **Most importantly:** exit the print loop as soon as you detect that an overflow _would occur._ - -Finally, again on a new line, output the count $c$ of Fibonacci numbers previously printed, and the initial input $n$ from the user, in the format: `c of n`. - -### Example: - -Let's (wrongly!) assume that $5$ cannot be represented using a 32 bit int. This means that $3$ is the largest 32-bit Fibonacci number. If your program is asked to print the first $4$ Fibonacci numbers the output should look as follows: - -``` -0 -1 -1 -2 -Printed 4 of 4 Fibonacci numbers -``` - -If you instead ask it to print the first 100 Fibonacci numbers the output should look as follows: - -``` -0 -1 -1 -2 -3 -Printed 5 of 100 Fibonacci numbers -``` - -**Important:** using anything other than `int` (e.g., `unsigned int`, floating point numbers, `long`, or double `long`) is forbidden. - -**Restrictions:** - -- The program **must not** rely on the knowledge of its final result. In particular, it is not allowed to hard-code - - the largest 32-bits Fibonacci number, or - - the number of digits that it has, or - - the total number of Fibonacci numbers representable with a 32-bit int -- Most importantly: do not perform additions that cause an overflow on 32 bit - -**Note:** It is straightfoward to compute the largest (signed) integer representable with 32 bits. You are also explicitly allowed to hard-code this value in your program. - ---- - -**Warning:** The autograder does not catch if an addition causes an overflow or if you do anything that's disallowed in the "Restrictions" section above, but you will receive 0 points when your TA corrects and catches this. diff --git a/Informatik_I/Exercise_2/task_3b/README.org b/Informatik_I/Exercise_2/task_3b/README.org new file mode 100644 index 0000000..b149a67 --- /dev/null +++ b/Informatik_I/Exercise_2/task_3b/README.org @@ -0,0 +1,94 @@ +#+TITLE: Task 3b: Fibonacci overflow check +#+AUTHOR: JirR02 + +* Background + +/Fibonacci numbers/ are the integers in the following sequence: \(0, 1, 1, 2, 3, 5, 8, 13, 21, ...\), where each number is the sum of the two previous numbers. + +* Task + +Fibonacci numbers grow fast, and can thus easily exceed the value range of 32-bit =int=. Think of a general way how you can check if the result of an addition would exceed the range of a 32-bit =int= (i.e. overflow) *without actually performing the addition causing the overflow.* + +Remember that we consider *signed integers.* Because only half of the numbers are positive, this leaves us with 31 bits to store the actual positive number value. + +Write a program that asks the user for an integer \(n\) and then prints the first $n$ Fibonacci numbers, each number on a new line. Use an =int= (we assume 32 bits, including the sign) to represent the current Fibonacci number. *Most importantly:* exit the print loop as soon as you detect that an overflow /would occur./ + +Finally, again on a new line, output the count \(c\) of Fibonacci numbers previously printed, and the initial input \(n\) from the user, in the format: =c of n=. + +** Example: + +Let's (wrongly!) assume that \(5\) cannot be represented using a 32 bit =int=. This means that \(3\) is the largest 32-bit Fibonacci number. If your program is asked to print the first \(4\) Fibonacci numbers the output should look as follows: + +#+begin_src shell +0 +1 +1 +2 +Printed 4 of 4 Fibonacci numbers +#+end_src + +If you instead ask it to print the first 100 Fibonacci numbers the output should look as follows: + +#+begin_src shell +0 +1 +1 +2 +3 +Printed 5 of 100 Fibonacci numbers +#+end_src + +*Important:* using anything other than =int= (e.g., =unsigned int=, floating point numbers, =long=, or double =long=) is forbidden. + +*Restrictions:* + +- The program **must not** rely on the knowledge of its final result. In particular, it is not allowed to hard-code + - the largest 32-bits Fibonacci number, or + - the number of digits that it has, or + - the total number of Fibonacci numbers representable with a 32-bit int +- Most importantly: do not perform additions that cause an overflow on 32 bit + +*Note:* It is straightfoward to compute the largest (signed) integer representable with 32 bits. You are also explicitly allowed to hard-code this value in your program. + +----- + +*Warning:* The autograder does not catch if an addition causes an overflow or if you do anything that's disallowed in the "Restrictions" section above, but you will receive 0 points when your TA corrects and catches this. + +* Mistakes + +- The variable =j= goes into overflow which is not allowed! + +* Solution + +#+begin_src cpp +#include + +int main() { + int a = 0; // First Fibonacci number + int b = 1; // Second Fibonacci number + int j = 0; // New Fibonacci number + int c = 0; // Number of Fibonacci numbers + int max = 2147483647; + int n; // Input integer + + std::cin >> n; + + for (int i = 0; i < n; ++i) { + + if (max - a < b) { // Check if the new Fibonacci number goes into overflow + break; + } else { // otherwise, calculate next Fibonacci number + std::cout << j << "\n"; + a = b; + b = j; + j = a + b; + ++c; + } + } + std::cout << c << " of " << n; // End Message +} +#+end_src + +—---- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_2/task_3b/main.cpp b/Informatik_I/Exercise_2/task_3b/main.cpp deleted file mode 100644 index 9f630af..0000000 --- a/Informatik_I/Exercise_2/task_3b/main.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include - -int main() { - int a = 0; // First Fibonacci number - int b = 1; // Second Fibonacci number - int j = 0; // New Fibonacci number - int c = 0; // Number of Fibonacci numbers - int max = 2147483647; - int n; // Input integer - - std::cin >> n; - - for (int i = 0; i < n; ++i) { - - if (max - a < b) { // Check if the new Fibonacci number goes into overflow - break; - } else { // otherwise, calculate next Fibonacci number - std::cout << j << "\n"; - a = b; - b = j; - j = a + b; - ++c; - } - } - std::cout << c << " of " << n; // End Message -} diff --git a/Informatik_I/Exercise_2/task_4/README.md b/Informatik_I/Exercise_2/task_4/README.md deleted file mode 100644 index 75038c8..0000000 --- a/Informatik_I/Exercise_2/task_4/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Task - -Write a program that inputs a non-negative integer `n` (but store it as `int`) and outputs the binary digits of `n` in the _correct_ order (i.e., starting with the most significant bit). Do not output the leading zeros or the sign. - -**Hint:** In order to find the largest integer $k$ such that $2^k \leq x$, you can utilize that $k$ is the smallest integer such that $2^k > \frac{x}{2}$. This observation is particularly useful to avoid an overflow for the expression $2^k$ when searching for the most significant bit to represent $x$. - -**Restrictions:** - -- Libraries: only the iostream standard library header is allowed; using arrays, string or cmath is not permitted. -- Operators: you may not use bitshift operators to manipulate the numbers. - ---- - -**Warning:** The autograder does not catch if you do anything that's disallowed in the "Restrictions" section above, but you will receive 0 points when your TA corrects and catches this. diff --git a/Informatik_I/Exercise_2/task_4/README.org b/Informatik_I/Exercise_2/task_4/README.org new file mode 100644 index 0000000..ddb9cef --- /dev/null +++ b/Informatik_I/Exercise_2/task_4/README.org @@ -0,0 +1,54 @@ +#+TITLE: Task 4: From decimal to binary representation +#+AUTHOR: JirR02 + +* Task + +Write a program that inputs a non-negative integer =n= (but store it as =int=) and outputs the binary digits of =n= in the /correct/ order (i.e., starting with the most significant bit). Do not output the leading zeros or the sign. + +*Hint:* In order to find the largest integer \(k\) such that \(2^k \leq x\), you can utilize that \(k\) is the smallest integer such that \(2^k > \frac{x}{2}\). This observation is particularly useful to avoid an overflow for the expression \(2^k\) when searching for the most significant bit to represent \(x\). + +*Restrictions:* + +- Libraries: only the iostream standard library header is allowed; using arrays, string or cmath is not permitted. +- Operators: you may not use bitshift operators to manipulate the numbers. + +----- + +*Warning:* The autograder does not catch if you do anything that's disallowed in the "Restrictions" section above, but you will receive 0 points when your TA corrects and catches this. + +* Solution + +#+begin_src cpp +#include + +int main() { + int i = 0; // Input integer + int d = 0; // Input Number + int a = 0; // Part of binary number + int b = 0; // Number to divide + int count = 0; + + std::cin >> i; + d = i; + b = i; + + if (i < 0) { + return 0; + } else if (i == 0) { + std::cout << 0; + } else { + while (d != 0) { + d = d / 2; + ++count; + } + for (; count > 0; --count) { + for (int j = count; j > 1; --j) { + b = b / 2; + } + a = b % 2; + std::cout << a; + b = i; + } + } +} +#+end_src diff --git a/Informatik_I/Exercise_2/task_4/main.cpp b/Informatik_I/Exercise_2/task_4/main.cpp deleted file mode 100644 index a838e6d..0000000 --- a/Informatik_I/Exercise_2/task_4/main.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include - -int main() { - int i = 0; // Input integer - int d = 0; // Input Number - int a = 0; // Part of binary number - int b = 0; // Number to divide - int count = 0; - - std::cin >> i; - d = i; - b = i; - - if (i < 0) { - return 0; - } else if (i == 0) { - std::cout << 0; - } else { - while (d != 0) { - d = d / 2; - ++count; - } - for (; count > 0; --count) { - for (int j = count; j > 1; --j) { - b = b / 2; - } - a = b % 2; - std::cout << a; - b = i; - } - } -} diff --git a/Informatik_I/Exercise_3/Task_1/README.md b/Informatik_I/Exercise_3/Task_1/README.md deleted file mode 100644 index 3c8fc57..0000000 --- a/Informatik_I/Exercise_3/Task_1/README.md +++ /dev/null @@ -1,24 +0,0 @@ -_This task is a mixed text/programming task. You need to update the content of loop.cpp according to the instruction provided in the file. For the code part, please check the autograder output._ - -# Task - -Considering the snippet - -```cpp -int n; -std::cin >> n; -int f = 1; -if (n > 0) { - do { - f = f * n; - --n; - } while (n > 0); -} -std::cout << f << std::endl; -``` - -1. Describe what it computes. -1. Decide which of the other two kind of loops would fit better than the one it is currently using, and describe why. -1. Rewrite the snippet into the loop you specified in (2). This part is autograded. - -**Important**: The use of goto statements is prohibited. diff --git a/Informatik_I/Exercise_3/Task_1/loop.cpp b/Informatik_I/Exercise_3/Task_1/README.org similarity index 52% rename from Informatik_I/Exercise_3/Task_1/loop.cpp rename to Informatik_I/Exercise_3/Task_1/README.org index e55485c..ad31810 100644 --- a/Informatik_I/Exercise_3/Task_1/loop.cpp +++ b/Informatik_I/Exercise_3/Task_1/README.org @@ -1,3 +1,34 @@ +#+TITLE: Task 1: Loop mix-up: Snippet 1 +#+AUTHOR: JirR02 + +/This task is a mixed text/programming task. You need to update the content of loop.cpp according to the instruction provided in the file. For the code part, please check the autograder output./ + +* Task + +Considering the snippet + +#+begin_src cpp +int n; +std::cin >> n; +int f = 1; +if (n > 0) { + do { + f = f * n; + --n; + } while (n > 0); +} +std::cout << f << std::endl; +#+end_src + +1. Describe what it computes. +1. Decide which of the other two kind of loops would fit better than the one it is currently using, and describe why. +1. Rewrite the snippet into the loop you specified in (2). This part is autograded. + +*Important*: The use of goto statements is prohibited. + +* Solution + +#+begin_src cpp #include "loop.h" #include @@ -41,3 +72,8 @@ void loop() { std::cout << f << std::endl; } +#+end_src + +-—--- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_3/Task_2/README.md b/Informatik_I/Exercise_3/Task_2/README.md deleted file mode 100644 index 0e2c1d5..0000000 --- a/Informatik_I/Exercise_3/Task_2/README.md +++ /dev/null @@ -1,23 +0,0 @@ -_This task is a mixed text/programming task. You need to update the content of loop.cpp according to the instruction provided in the file. For the code part, please check the autograder output._ - -# Task - -Considering the snippet - -```cpp -for (;;) { - int i1, i2; - std::cin >> i1 >> i2; - std::cout << i1 + i2 << "\n"; - int again; - std::cout << "Again? (0/1)\n"; - std::cin >> again; - if (again == 0) break; -} -``` - -1. Describe what it computes. - -1. Decide which of the other two kind of loops would fit better than the one it is currently using, and describe why. - -1. Rewrite the snippet into the loop you specified in (2). This part is autograded. Note: print the control message "Again? (0/1)" using the same format used in the snippet. diff --git a/Informatik_I/Exercise_3/Task_2/loop.cpp b/Informatik_I/Exercise_3/Task_2/README.org similarity index 55% rename from Informatik_I/Exercise_3/Task_2/loop.cpp rename to Informatik_I/Exercise_3/Task_2/README.org index b6f1551..174ebe7 100644 --- a/Informatik_I/Exercise_3/Task_2/loop.cpp +++ b/Informatik_I/Exercise_3/Task_2/README.org @@ -1,3 +1,33 @@ +#+TITLE: Task 2: Loop mix-up: Snippet 2 +#+AUTHOR: JirR02 + +/This task is a mixed text/programming task. You need to update the content of loop.cpp according to the instruction provided in the file. For the code part, please check the autograder output./ + +* Task + +Considering the snippet + +#+begin_src cpp +for (;;) { + int i1, i2; + std::cin >> i1 >> i2; + std::cout << i1 + i2 << "\n"; + int again; + std::cout << "Again? (0/1)\n"; + std::cin >> again; + if (again == 0) break; +} +#+end_src + +1. Describe what it computes. + +1. Decide which of the other two kind of loops would fit better than the one it is currently using, and describe why. + +1. Rewrite the snippet into the loop you specified in (2). This part is autograded. Note: print the control message "Again? (0/1)" using the same format used in the snippet. + +* Solution + +#+begin_src cpp #include "loop.h" #include @@ -46,3 +76,8 @@ void loop() { std::cin >> again; } } +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_3/Task_3/README.md b/Informatik_I/Exercise_3/Task_3/README.md deleted file mode 100644 index 3cf0ee2..0000000 --- a/Informatik_I/Exercise_3/Task_3/README.md +++ /dev/null @@ -1,27 +0,0 @@ -_This task is a mixed text/programming task. You need to update the content of loop.cpp according to the instructions provided in the file. For the code part, please check the autograder output._ - -# Task - -Consider the following program: - -```cpp -int n; -std::cin >> n; - -int x = 1; -if (n > 0) { - bool e = true; - do { - if (--n == 0) { - e = false; - } - x *= 2; - } while (e); -} -std::cout << x << std::endl; -``` - -1. Describe the output of the program as a function of its input n. -1. For which values of `n` do you expect a correct output `x`? Explain why. -1. Show that this program terminates for all values of `n` found in (2). Hint: Make an argument based on the following idea. First prove that the program terminates for the `n=0` and `n=1`. Then show that it terminates for any other `n` knowing that it terminates for `n-1`. This creates a domino effect where the fact that the program terminates for `n=1` proves that the program must also terminate for `n=2`, and this in turn proves that the program must terminate for `n=3`, and so on. This technique is called "proof by induction". -1. Provide a more elegant implementation of this function using another type of loop. This part is autograded. diff --git a/Informatik_I/Exercise_3/Task_3/README.org b/Informatik_I/Exercise_3/Task_3/README.org new file mode 100644 index 0000000..0941384 --- /dev/null +++ b/Informatik_I/Exercise_3/Task_3/README.org @@ -0,0 +1,92 @@ +#+TITLE: Task 3: Loop Analysis + +/This task is a mixed text/programming task. You need to update the content of loop.cpp according to the instructions provided in the file. For the code part, please check the autograder output./ + +* Task + +Consider the following program: + +#+begin_src cpp +int n; +std::cin >> n; + +int x = 1; +if (n > 0) { + bool e = true; + do { + if (--n == 0) { + e = false; + } + x *= 2; + } while (e); +} +std::cout << x << std::endl; +#+end_src + +1. Describe the output of the program as a function of its input \(n\). +1. For which values of \(n\) do you expect a correct output \(x\)? Explain why. +1. Show that this program terminates for all values of \(n\) found in (2). Hint: Make an argument based on the following idea. First prove that the program terminates for the \(n=0\) and \(n=1\). Then show that it terminates for any other \(n\) knowing that it terminates for \(n-1\). This creates a domino effect where the fact that the program terminates for \(n=1\) proves that the program must also terminate for \(n=2\), and this in turn proves that the program must terminate for \(n=3\), and so on. This technique is called "proof by induction". +1. Provide a more elegant implementation of this function using another type of loop. This part is autograded. + +* Solution + +#+begin_src cpp +#include "loop.h" +#include + +// Fill out the file with the required answers + +/* + + Subtask 1: Describe the output of the program as a function of its input n. + + This code snippte computes the powers of 2 with a positive exponential. The + exponential is the input by the user. + +*/ + +/* + + Subtask 2: For which values of n do you expect a correct output x? Explain + why. + + For a exponential between 0 and 30. Anything below zero would result in the + wrong answer (1) and anything above 30 would result in an overflow. In + addition, if we imporved the code to calculate the powers of 2 with negative + exponents, it would not work since the result of the powers of 2 with negative + exponents are variables of type float or double and the code snippet is + working with integers. + +*/ + +/* + + Subtask 3: Show that this program terminates for all values of n found in (2). + + If the input is 31, the output is -2147483648. + If the input is -1, the output is 1. + +*/ + +/* + Subtask 4: Provide a more elegant implementation of this function using + another type of loop. +*/ + +void loop() { + + int n; + std::cin >> n; + + int x = 1; + + for (; n > 0; --n) + x *= 2; + + std::cout << x << std::endl; +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_3/Task_3/loop.cpp b/Informatik_I/Exercise_3/Task_3/loop.cpp deleted file mode 100644 index 402360e..0000000 --- a/Informatik_I/Exercise_3/Task_3/loop.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "loop.h" -#include - -// Fill out the file with the required answers - -/* - - Subtask 1: Describe the output of the program as a function of its input n. - - This code snippte computes the powers of 2 with a positive exponential. The - exponential is the input by the user. - -*/ - -/* - - Subtask 2: For which values of n do you expect a correct output x? Explain - why. - - For a exponential between 0 and 30. Anything below zero would result in the - wrong answer (1) and anything above 30 would result in an overflow. In - addition, if we imporved the code to calculate the powers of 2 with negative - exponents, it would not work since the result of the powers of 2 with negative - exponents are variables of type float or double and the code snippet is - working with integers. - -*/ - -/* - - Subtask 3: Show that this program terminates for all values of n found in (2). - - If the input is 31, the output is -2147483648. - If the input is -1, the output is 1. - -*/ - -/* - Subtask 4: Provide a more elegant implementation of this function using - another type of loop. -*/ - -void loop() { - - int n; - std::cin >> n; - - int x = 1; - - for (; n > 0; --n) - x *= 2; - - std::cout << x << std::endl; -} diff --git a/Informatik_I/Exercise_3/Task_4a/README.md b/Informatik_I/Exercise_3/Task_4a/README.md deleted file mode 100644 index 5e56323..0000000 --- a/Informatik_I/Exercise_3/Task_4a/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Task - -The number $\pi$ can be defined through various infinite sums. The accuracy increases with the number of terms. Considering the following sum, that we call sum 1: - -$$\frac{\pi}{4} = \sum_{j=0}^{m-1} \frac{(-1)^j}{2j + 1} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + ...$$ - -Note that $m$ is the number of the terms in the sum. For example, $m=2$ refers to the sum of the terms $1$ (for $j=0$) and $-\frac{1}{3}$ (for $j=1$). This examples yields a value of $4 \cdot (1-\frac{1}{3})$ for $\pi$. - -Write a program that computes and outputs an approximation of Pi, based on sum 1. The input for your program is the number of **terms** $m$ of sum 1 that should be considered in the calculation. The output is the approximation of $\pi$. - -## Input - -A number $m \geq 1$. - -## Output - -The approximation of $\pi$ given by $4 \sum_{j=0}^{m-1} \frac{(-1)^j}{2j + 1}$, rounded to 6 significant digits. Note that 6 significant digits is the default precision of C++ for printing floating-point values. Use a variable of type double to calculate the sum. Note that that $x^0$ is 1 (if $x \neq 0$). - -**Important**: the use of functions from the math library (e.g., pow) is prohibited. diff --git a/Informatik_I/Exercise_3/Task_4a/README.org b/Informatik_I/Exercise_3/Task_4a/README.org new file mode 100644 index 0000000..b7de096 --- /dev/null +++ b/Informatik_I/Exercise_3/Task_4a/README.org @@ -0,0 +1,61 @@ +#+TITLE: Task 4a: Approximation of Pi: Sum 1 +#+AUTHOR: JirR02 + +* Task + +The number \(\pi\) can be defined through various infinite sums. The accuracy increases with the number of terms. Considering the following sum, that we call sum 1: + +$$\frac{\pi}{4} = \sum_{j=0}^{m-1} \frac{(-1)^j}{2j + 1} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + ...$$ + +Note that \(m\) is the number of the terms in the sum. For example, \(m=2\)$ refers to the sum of the terms \(1\) (for \(j=0\)) and \(-\frac{1}{3}\) (for \(j=1\)). This examples yields a value of \(4 \cdot (1-\frac{1}{3})\) for \(\pi\). + +Write a program that computes and outputs an approximation of Pi, based on sum 1. The input for your program is the number of **terms** $m$ of sum 1 that should be considered in the calculation. The output is the approximation of \(\pi\). + +** Input + +A number \(m \geq 1\). + +** Output + +The approximation of \(\pi\) given by \(4 \sum_{j=0}^{m-1} \frac{(-1)^j}{2j + 1}\), rounded to 6 significant digits. Note that 6 significant digits is the default precision of C++ for printing floating-point values. Use a variable of type double to calculate the sum. Note that \(x^0\) is 1 (if \(x \neq 0\)). + +**Important**: the use of functions from the math library (e.g., pow) is prohibited. + +* Solution + +#+begin_src cpp +#include + +double power(double n, double e) { // Self defined function for exponent + int res = 1; + for (; e > 0; --e) { + res *= n; + } + return res; +} + +int main() { + double m; // User Input + double pi = 0; // Pi + float res; // Outputed result with 6 significant digits + + std::cin >> m; + + if (m < 1) { // Check if Input is greater than 1. + return 0; + } else { + for (int i = 0; i < m; ++i) { + pi = pi + 4 * ((power(-1, i)) / ((2 * i) + 1)); // calculate Pi + } + + res = (float)(pi); // round to 6 significant digits + std::cout << res; + + return 0; + } +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_3/Task_4a/main.cpp b/Informatik_I/Exercise_3/Task_4a/main.cpp deleted file mode 100644 index 8a1ae6a..0000000 --- a/Informatik_I/Exercise_3/Task_4a/main.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include - -double power(double n, double e) { // Self defined function for exponent - int res = 1; - for (; e > 0; --e) { - res *= n; - } - return res; -} - -int main() { - double m; // User Input - double pi = 0; // Pi - float res; // Outputed result with 6 significant digits - - std::cin >> m; - - if (m < 1) { // Check if Input is greater than 1. - return 0; - } else { - for (int i = 0; i < m; ++i) { - pi = pi + 4 * ((power(-1, i)) / ((2 * i) + 1)); // calculate Pi - } - - res = (float)(pi); // round to 6 significant digits - std::cout << res; - - return 0; - } -} diff --git a/Informatik_I/Exercise_3/Task_4b/README.md b/Informatik_I/Exercise_3/Task_4b/README.md deleted file mode 100644 index 751ae02..0000000 --- a/Informatik_I/Exercise_3/Task_4b/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# Task - -The number $\pi$ can be defined through various infinite sums. The accuracy increases with the number of terms. Considering the following sum, which we call sum 2: - -$$\frac{\pi}{2} = 1 + \sum_{j = 1}^{m - 1} \frac{\prod_{i=1}^j i}{\prod_{i=1}^j (2i + 1)} = 1 + \frac{1}{3} + \frac{1 \cdot 2}{3 \cdot 5} + \frac{1 \cdot 2 \cdot 3}{3 \cdot 5 \cdot 7} + ...$$ - -Write a program that computes and outputs an approximation of Pi, based on sum 2. The input for your program is the number of **terms** $m$ (including 1) to be included in the calculation to be done. The output is the approximation of $\pi$. - -**Optional**: After you have solved this and the previous task, think about which formula gives a more precise approximation of -, sum 1 or sum 2 ? What are the drawbacks? Write your thoughts in a comment below the code. - -## Input - -A natural number $m$ ($m \geq 1$). - -## Output - -The approximation of $\pi$ given by $m$ terms, rounded to 6 significant digits. Note that 6 significant digits is the default precision of C++ for printing floating-point values. Use a double variable to store the sum. - -**Important**: the use of functions from the math library (e.g., pow) is prohibited. diff --git a/Informatik_I/Exercise_3/Task_4b/README.org b/Informatik_I/Exercise_3/Task_4b/README.org new file mode 100644 index 0000000..5abad7f --- /dev/null +++ b/Informatik_I/Exercise_3/Task_4b/README.org @@ -0,0 +1,66 @@ +#+TITLE: Task 4b: Approximation of Pi: Sum 2 +#+AUTHOR: JirR02 + +* Task + +The number \(\pi\) can be defined through various infinite sums. The accuracy increases with the number of terms. Considering the following sum, which we call sum 2: + +$$\frac{\pi}{2} = 1 + \sum_{j = 1}^{m - 1} \frac{\prod_{i=1}^j i}{\prod_{i=1}^j (2i + 1)} = 1 + \frac{1}{3} + \frac{1 \cdot 2}{3 \cdot 5} + \frac{1 \cdot 2 \cdot 3}{3 \cdot 5 \cdot 7} + ...$$ + +Write a program that computes and outputs an approximation of Pi, based on sum 2. The input for your program is the number of **terms** $m$ (including 1) to be included in the calculation to be done. The output is the approximation of \(\pi\). + +**Optional**: After you have solved this and the previous task, think about which formula gives a more precise approximation of \(\pi\), sum 1 or sum 2 ? What are the drawbacks? Write your thoughts in a comment below the code. + +* Input + +A natural number \(m\) (\(m \geq 1\)). + +* Output + +The approximation of $\pi$ given by $m$ terms, rounded to 6 significant digits. Note that 6 significant digits is the default precision of C++ for printing floating-point values. Use a double variable to store the sum. + +**Important**: the use of functions from the math library (e.g., =pow=) is prohibited. + +* Solution + +#+begin_src cpp +#include + +double productsumnum(double n) { + double res = 1; + for (int j = 1; j <= n; ++j) { + res *= j; + } + return res; +} + +double productsumden(double n) { + double res = 1; + for (int j = 1; j <= n; ++j) { + res *= (2 * j + 1); + } + return res; +} + +int main() { + + double m; // User Input + double pi = 2; // Pi + float res; // Outputed result with 6 significant digits + + std::cin >> m; + + for (int i = 1; i < m; ++i) { + pi += (2 * (productsumnum(i) / productsumden(i))); + } + + res = (float)(pi); + std::cout << res; + + return 0; +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_3/Task_4b/main.cpp b/Informatik_I/Exercise_3/Task_4b/main.cpp deleted file mode 100644 index f6f8717..0000000 --- a/Informatik_I/Exercise_3/Task_4b/main.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include - -double productsumnum(double n) { - double res = 1; - for (int j = 1; j <= n; ++j) { - res *= j; - } - return res; -} - -double productsumden(double n) { - double res = 1; - for (int j = 1; j <= n; ++j) { - res *= (2 * j + 1); - } - return res; -} - -int main() { - - double m; // User Input - double pi = 2; // Pi - float res; // Outputed result with 6 significant digits - - std::cin >> m; - - for (int i = 1; i < m; ++i) { - pi += (2 * (productsumnum(i) / productsumden(i))); - } - - res = (float)(pi); - std::cout << res; - - return 0; -} diff --git a/Informatik_I/Exercise_4/Task_1/README.md b/Informatik_I/Exercise_4/Task_1/README.md deleted file mode 100644 index 0c161bc..0000000 --- a/Informatik_I/Exercise_4/Task_1/README.md +++ /dev/null @@ -1,19 +0,0 @@ -_This task is a text-based task but automatically checked. You are required to write your answers into solutions.txt by replacing the question marks with the correct solution. Please, do not change the structure of solutions.txt and be consistent with its syntax (comment-lines start with #)_ - -# Task - -We examine the normalized binary representation of floating point numbers in the normalized floating point system $F*(2,4,-3,3)$. - -1. Convert the following decimal numbers to the normalized binary representation. For each number, choose the appropriate exponent $e$ and round to the nearest value if you cannot represent the exact value. If the exact number falls exactly midway between two bracketing finite floating point representations, round to the number with an even least significant bit. - - - $0.75_{10}$ - - $3.1416_{10}$ - - $2.718_{10}$ - - $7_{10}$ - - $0.11_{10}$ - -1. For each number of (2), convert the binary representation back to their decimal form, and determine the absolute rounding error of the conversion. - -1. Calculate $2.718_{10} + 3.1416_{10} + 0.11_{10}$ in the binary representation. What do you observe? - -**Note**: The question of how to round floating point numbers is non-trivial. The IEEE standard lists 5 different modes of rounding of which we only mentioned the most common one at the beginning of this exercise. If you are interested to learn more, you can access the most recent standard through the ETH network. diff --git a/Informatik_I/Exercise_4/Task_1/README.org b/Informatik_I/Exercise_4/Task_1/README.org new file mode 100644 index 0000000..003a742 --- /dev/null +++ b/Informatik_I/Exercise_4/Task_1/README.org @@ -0,0 +1,90 @@ +#+TITLE: Task 1: Floating-Point Number Representation + +/This task is a text-based task but automatically checked. You are required to write your answers into solutions.txt by replacing the question marks with the correct solution. Please, do not change the structure of solutions.txt and be consistent with its syntax (comment-lines start with #)/ + +* Task + +We examine the normalized binary representation of floating point numbers in the normalized floating point system $F*(2,4,-3,3)$. + +1. Convert the following decimal numbers to the normalized binary representation. For each number, choose the appropriate exponent $e$ and round to the nearest value if you cannot represent the exact value. If the exact number falls exactly midway between two bracketing finite floating point representations, round to the number with an even least significant bit. + + - \(0.75_{10}\) + - \(3.1416_{10}\) + - \(2.718_{10}\) + - \(7_{10}\) + - \(0.11_{10}\) + +1. For each number of (2), convert the binary representation back to their decimal form, and determine the absolute rounding error of the conversion. + +1. Calculate \(2.718_{10} + 3.1416_{10} + 0.11_{10}\) in the binary representation. What do you observe? + +**Note**: The question of how to round floating point numbers is non-trivial. The IEEE standard lists 5 different modes of rounding of which we only mentioned the most common one at the beginning of this exercise. If you are interested to learn more, you can access the most recent standard through the ETH network. + +* Solution + +#+begin_src shell +# NOTE: Lines starting with # are comments. Spaces are ignored. +# Replace the question marks, with your answer, following the instructions +# provided for each subtask. + + +######################## Subtask 1 ############################ +# Subtask 1a: convert 0.75. +# In the given system, this is equal to "1.100 * 2^-1". The solution +# is written as "1.100*2^-1", without spaces and without quotation marks. + +1a) 1.100*2^-1 + +# Subtask 1b: convert 3.1416 + +1b) 1.101*2^1 + +# Subtask 1c: convert 2.718 + +1c) 1.011*2^1 + +# Subtask 1d: convert 7 + +1d) 1.110*2^2 + +# Subtask 1e: convert 0.11 + +1e) 1.000*2^-3 + +######################## Subtask 2 ############################ +# Convert the first number of previous Sub-Task back to decimal form. +# For each number you are required to write the decimal number and the +# conversion error (each on a different line). +# For your convenience, the first number is already converted. + + +2a-decimal) 0.75 +2a-error) 0 + +2b-decimal) 3.25 +2b-error) 0.1084 + +2c-decimal) 2.75 +2c-error) 0.032 + +2d-decimal) 7 +2d-error) 0 + +2e-decimal) 0.125 +2e-error) 0.015 + +######################## Subtask 3 ############################ + +# Calculate the result of the addition and indicate the result in the +# same format as in the first sub-task ("siginificand*2^exp", without +# quotation marks). Then, write your observation as a comment right below. + +3) 1.100*2^2 + +# Write your observations here +# The Decimal System cannot be represented accurately by the binary system. There will always be an error. When adding the number converted from the decimal to the binary sytem, the error becomes greater. +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_4/Task_1/solutions.txt b/Informatik_I/Exercise_4/Task_1/solutions.txt deleted file mode 100644 index 4aae30f..0000000 --- a/Informatik_I/Exercise_4/Task_1/solutions.txt +++ /dev/null @@ -1,60 +0,0 @@ -# NOTE: Lines starting with # are comments. Spaces are ignored. -# Replace the question marks, with your answer, following the instructions -# provided for each subtask. - - -######################## Subtask 1 ############################ -# Subtask 1a: convert 0.75. -# In the given system, this is equal to "1.100 * 2^-1". The solution -# is written as "1.100*2^-1", without spaces and without quotation marks. - -1a) 1.100*2^-1 - -# Subtask 1b: convert 3.1416 - -1b) 1.101*2^1 - -# Subtask 1c: convert 2.718 - -1c) 1.011*2^1 - -# Subtask 1d: convert 7 - -1d) 1.110*2^2 - -# Subtask 1e: convert 0.11 - -1e) 1.000*2^-3 - -######################## Subtask 2 ############################ -# Convert the first number of previous Sub-Task back to decimal form. -# For each number you are required to write the decimal number and the -# conversion error (each on a different line). -# For your convenience, the first number is already converted. - - -2a-decimal) 0.75 -2a-error) 0 - -2b-decimal) 3.25 -2b-error) 0.1084 - -2c-decimal) 2.75 -2c-error) 0.032 - -2d-decimal) 7 -2d-error) 0 - -2e-decimal) 0.125 -2e-error) 0.015 - -######################## Subtask 3 ############################ - -# Calculate the result of the addition and indicate the result in the -# same format as in the first sub-task ("siginificand*2^exp", without -# quotation marks). Then, write your observation as a comment right below. - -3) 1.100*2^2 - -# Write your observations here -# The Decimal System cannot be represented accurately by the binary system. There will always be an error. When adding the number converted from the decimal to the binary sytem, the error becomes greater. diff --git a/Informatik_I/Exercise_4/Task_2/README.md b/Informatik_I/Exercise_4/Task_2/README.md deleted file mode 100644 index 075c13c..0000000 --- a/Informatik_I/Exercise_4/Task_2/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# Task - -Consider a parabola $(\m{P})$ defined as $y = g(x)$, with $g(x) = 0.9 \cdot x^2 + 1.3 \cdot x - 0.7$. - -Write a program that determines if a point $(x,y)$ lies on parabola $(\m{P})$ or not. The input is provided by two decimal numbers in the sequence $x,y$. The program must output `yes`, if the point lies on the parabola, otherwise `no`. Use datatype `double` for all variables and numbers used in the calculation of $g(x)$. - -You will notice that a straight forward approach (comparing for equality) does not work, i.e., for some points that clearly should be on parabola $g$ such an approach returns result `no`. - -_Hint_: Look at the difference between the exact values of the function and the values that your program calculates. Change the program so that it works properly for all points the submission system uses as test input without hard-coding the points. Expect an epsilon within the range $\[ 10^{-6}, 10^{-3}]\$. Experiment yourself to find the epsilon required to pass the test cases. - -**Note**: Output only with `std::cout << "no" << std::endl;` or `std::cout << "yes" << std::endl;`, as the autograder will only accept output that exactly matches `yes\n` or `no\n`. For all other messages, use `std::cerr` as in: - -```cpp -std::cerr << "This is a test message\n" -``` - -Those will be ignored by the autograder. diff --git a/Informatik_I/Exercise_4/Task_2/README.org b/Informatik_I/Exercise_4/Task_2/README.org new file mode 100644 index 0000000..7aa018c --- /dev/null +++ b/Informatik_I/Exercise_4/Task_2/README.org @@ -0,0 +1,54 @@ +#+TITLE: Task 2: Point on Parabola? +#+AUTHOR: JirR02 + +* Task + +Consider a parabola \((\m{P})\) defined as \(y = g(x)\), with \(g(x) = 0.9 \cdot x^2 + 1.3 \cdot x - 0.7\). + +Write a program that determines if a point \((x,y)\) lies on parabola \((\m{P})\) or not. The input is provided by two decimal numbers in the sequence \(x,y\). The program must output =yes=, if the point lies on the parabola, otherwise =no=. Use datatype =double= for all variables and numbers used in the calculation of \(g(x)\). + +You will notice that a straight forward approach (comparing for equality) does not work, i.e., for some points that clearly should be on parabola $g$ such an approach returns result =no=. + +/Hint/: Look at the difference between the exact values of the function and the values that your program calculates. Change the program so that it works properly for all points the submission system uses as test input without hard-coding the points. Expect an epsilon within the range \([ 10^{-6}, 10^{-3}]\)$. Experiment yourself to find the epsilon required to pass the test cases. + +**Note**: Output only with =std::cout << "no" << std::endl;= or =std::cout << "yes" << std::endl;=, as the autograder will only accept output that exactly matches =yes\n= or =no\n=. For all other messages, use =std::cerr= as in: + +#+begin_src cpp +std::cerr << "This is a test message\n" +#+end_src + +Those will be ignored by the autograder. + +* Solution + +#+begin_src cpp +#include + +int main() { + + double x = 0; // x inputed by user + double yin = 0; // y inputed by user + double ycon = 0; // y control + double emax = 0.0001; + double emin = -0.0001; + + std::cin >> x; + std::cin >> yin; + + ycon = 0.9 * x * x + 1.3 * x - 0.7; + + std::cerr << ycon; + std::cerr << yin - ycon; + + if (yin == ycon || (yin - ycon <= emax && yin - ycon >= emin)) + std::cout << "yes"; + else + std::cout << "no"; + + return 0; +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_4/Task_2/main.cpp b/Informatik_I/Exercise_4/Task_2/main.cpp deleted file mode 100644 index ed92b97..0000000 --- a/Informatik_I/Exercise_4/Task_2/main.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include - -int main() { - - double x = 0; // x inputed by user - double yin = 0; // y inputed by user - double ycon = 0; // y control - double emax = 0.0001; - double emin = -0.0001; - - std::cin >> x; - std::cin >> yin; - - ycon = 0.9 * x * x + 1.3 * x - 0.7; - - std::cerr << ycon; - std::cerr << yin - ycon; - - if (yin == ycon || (yin - ycon <= emax && yin - ycon >= emin)) - std::cout << "yes"; - else - std::cout << "no"; - - return 0; -} diff --git a/Informatik_I/Exercise_4/Task_3/README.md b/Informatik_I/Exercise_4/Task_3/README.md deleted file mode 100644 index bcc579b..0000000 --- a/Informatik_I/Exercise_4/Task_3/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Task - -Implement the following rounding function that rounds a 64-bit floating point number (type `double`) to the nearest 32-bit integer (type `int`). You may assume that the type `double` complies with the IEEE standard 754. The function is only required to work correctly if the nearest integer is in the value range of the type `int`, otherwise, the return value of the function is undefined. - -**Note: Usage of library rounding functions (standard or others) is not allowed.** - -```cpp -// PRE: x is roundable to a number in the value range of type @int@ -// POST: return value is the integer nearest to x, or the one further -// away from 0 if x lies right in between two integers. -int round_number(double x); -``` - -Write your solution in `rounding.h`. - -_Hint_: In `C++`, when you convert a `float` or `double` to an `int`, the fractional part gets cut off (truncated). Think about how you can use the truncated number to solve the exercise. diff --git a/Informatik_I/Exercise_4/Task_3/README.org b/Informatik_I/Exercise_4/Task_3/README.org new file mode 100644 index 0000000..41e8fe5 --- /dev/null +++ b/Informatik_I/Exercise_4/Task_3/README.org @@ -0,0 +1,41 @@ +#+TITLE: Task 3: Rounding +#+AUTHOR: JirR02 + +* Task + +Implement the following rounding function that rounds a 64-bit floating point number (type =double=) to the nearest 32-bit integer (type =int=). You may assume that the type =double= complies with the IEEE standard 754. The function is only required to work correctly if the nearest integer is in the value range of the type =int=, otherwise, the return value of the function is undefined. + +**Note: Usage of library rounding functions (standard or others) is not allowed.** + +#+begin_src cpp +// PRE: x is roundable to a number in the value range of type @int@ +// POST: return value is the integer nearest to x, or the one further +// away from 0 if x lies right in between two integers. +int round_number(double x); +#+end_src + +Write your solution in =rounding.h=. + +/Hint/: In =C++=, when you convert a =float= or =double= to an =int=, the fractional part gets cut off (truncated). Think about how you can use the truncated number to solve the exercise. + +* Solution + +#+begin_src cpp +#pragma once + +// PRE: x is roundable to a number in the value range of type int +// POST: return value is the integer nearest to x, or the one further +// away from 0 if x lies right in between two integers. +int round_number(double x) { + int res; + if (x < 0) + res = x - 0.5; + else + res = x + 0.5; + return res; +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_4/Task_3/rounding.h b/Informatik_I/Exercise_4/Task_3/rounding.h deleted file mode 100644 index 5a14ad0..0000000 --- a/Informatik_I/Exercise_4/Task_3/rounding.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -// PRE: x is roundable to a number in the value range of type int -// POST: return value is the integer nearest to x, or the one further -// away from 0 if x lies right in between two integers. -int round_number(double x) { - int res; - if (x < 0) - res = x - 0.5; - else - res = x + 0.5; - return res; -} diff --git a/Informatik_I/Exercise_4/Task_4/README.md b/Informatik_I/Exercise_4/Task_4/README.md deleted file mode 100644 index 2caf2b7..0000000 --- a/Informatik_I/Exercise_4/Task_4/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Task - -Write a program that performs the binary expansion for a given decimal input number $x$, where $0 \leq x < 2$. Use the algorithm presented in the lecture. The program must output the first $16$ digits of the number in the format: $b_0, b_1, b_2, ... , b_15$. - -_Important_ Always print all $16$ digits, even the trailing zeros. Do not normalize or round the number. - -You can structure your program into functions to avoid code repetition. Do not forget to annotate functions with pre- and post conditions. diff --git a/Informatik_I/Exercise_4/Task_4/README.org b/Informatik_I/Exercise_4/Task_4/README.org new file mode 100644 index 0000000..37022a0 --- /dev/null +++ b/Informatik_I/Exercise_4/Task_4/README.org @@ -0,0 +1,47 @@ +#+TITLE: Task 4: Binary Expansion +#+AUTHOR: JirR02 + +* Task + +Write a program that performs the binary expansion for a given decimal input number \(x\), where \(0 \leq x < 2\). Use the algorithm presented in the lecture. The program must output the first \(16\) digits of the number in the format: \(b_0, b_1, b_2, ... , b_15\). + +/Important/ Always print all \(16\) digits, even the trailing zeros. Do not normalize or round the number. + +You can structure your program into functions to avoid code repetition. Do not forget to annotate functions with pre- and post conditions. + +* Solution + +#+begin_src cpp +#include + +int main() { + + float i; + int n; + float d; + + std::cin >> i; + + if (i < 0 || i > 2) + return 0; + else { + n = i; + d = i - n; + + std::cout << n << "."; + + n = d; + d = 2 * (d - n); + + for (int j = 1; j <= 15; ++j) { + n = d; + d = 2 * (d - n); + std::cout << n; + } + } +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_4/Task_4/main.cpp b/Informatik_I/Exercise_4/Task_4/main.cpp deleted file mode 100644 index 839fde0..0000000 --- a/Informatik_I/Exercise_4/Task_4/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include - -int main() { - - float i; - int n; - float d; - - std::cin >> i; - - if (i < 0 || i > 2) - return 0; - else { - n = i; - d = i - n; - - std::cout << n << "."; - - n = d; - d = 2 * (d - n); - - for (int j = 1; j <= 15; ++j) { - n = d; - d = 2 * (d - n); - std::cout << n; - } - } -} diff --git a/Informatik_I/Exercise_5/Task_1/README.md b/Informatik_I/Exercise_5/Task_1/README.md deleted file mode 100644 index f0d9a24..0000000 --- a/Informatik_I/Exercise_5/Task_1/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# Task - -A perpetual calendar can be used to determine the weekday (Monday, ..., Sunday) of any given date. You may for example know that the Berlin wall came down on November 9, 1989, but what was the weekday? It was a Thursday. Or what is the weekday of the 1000th anniversary of the Swiss confederation, to be celebrated on August 1, 2291? It will be a Saturday. The task of this exercise is to write a program that outputs the weekday of a given input date. - -Your program will read the date from the input. The input is given as three integer values in the following order: Day, month, year. First the program must validate the input. Pay attention to special cases of February (leap years!) also, the date must be greater or equal to the reference date. If a date is invalid output invalid date. If the date is valid, calculate the weekday of this day. This can be done by calculating how many days lie between the date in question and a reference date whose weekday is known. As reference date use Monday, 1st January 1900. Finally, output the weekday as one word in English. - -**Approach**: The goal of this exercise is to learn the usage of functions. For that, we split the program into the following sub tasks given as function declarations. Your task is to **implement the provided functions** in the calendar.cpp file, so that they perform the action that is specified in their post condition. - -**Important: There is a well-known mathematical function to calculate the weekday of a date. Using this function is an incorrect solution as it defeats the purpose of this exercise.** - -```cpp -// PRE: a year greater or equal than 1900 -// POST: returns whether that year was a leap year -bool is_leap_year(int year); - -// PRE: a year greater or equal than 1900 -// POST: returns the number of days in that year -int count_days_in_year(int year); - -// PRE: a month between 1 and 12 and a year greater or equal than 1900 -// POST: returns the number of days in the month of that year -int count_days_in_month(int month, int year); - -// PRE: n/a -// POST: returns whether the given values represent a valid date -bool is_valid_date(int day, int month, int year); - -// PRE: the given values represent a valid date -// POST: returns the number of days between January 1, 1900 and this date (excluding this date) -int count_days(int day, int month, int year); - -// PRE: the given values represent a (potentially invalid) date -// POST: prints the weekday if the date is valid or "invalid date" otherwise. -// Everything must be printed in lowercase. -void print_weekday(int day, int month, int year); -``` - -To complete the task, you have to provide the definition of the aforementioned functions. - -The `calendar.cpp` file contains skeletons of the functions to be implemented. The `main.cpp` file contains testing functions and the main function. In the main function, a menu is printed to select the function that has to be tested. - -**Important** the main is not editable. Required functions must be implemented in `calendar.cpp`. - -**Additional notes:** - -1. For function arguments that do **not** fulfill the precondition, the behavior is undefined. - -1. There are a few opportunities here to use switch statements. Use them if they result in better readable code. - -1. A leap year is defined as follows: It is an integer multiple of 4, except for years evenly divisible by 100, which are not leap years unless evenly divisible by 400. (Source: [Wikipedia](https://en.wikipedia.org/wiki/Leap_year)) diff --git a/Informatik_I/Exercise_5/Task_1/README.org b/Informatik_I/Exercise_5/Task_1/README.org new file mode 100644 index 0000000..e18a38b --- /dev/null +++ b/Informatik_I/Exercise_5/Task_1/README.org @@ -0,0 +1,152 @@ +#+TITLE: Task 1: Perpetual calendar +#+AUTHOR: JirR02 + +* Task + +A perpetual calendar can be used to determine the weekday (Monday, ..., Sunday) of any given date. You may for example know that the Berlin wall came down on November 9, 1989, but what was the weekday? It was a Thursday. Or what is the weekday of the 1000th anniversary of the Swiss confederation, to be celebrated on August 1, 2291? It will be a Saturday. The task of this exercise is to write a program that outputs the weekday of a given input date. + +Your program will read the date from the input. The input is given as three integer values in the following order: Day, month, year. First the program must validate the input. Pay attention to special cases of February (leap years!) also, the date must be greater or equal to the reference date. If a date is invalid output invalid date. If the date is valid, calculate the weekday of this day. This can be done by calculating how many days lie between the date in question and a reference date whose weekday is known. As reference date use /Monday, 1st January 1900/. Finally, output the weekday as one word in English. + +**Approach**: The goal of this exercise is to learn the usage of functions. For that, we split the program into the following sub tasks given as function declarations. Your task is to **implement the provided functions** in the calendar.cpp file, so that they perform the action that is specified in their post condition. + +**Important: There is a well-known mathematical function to calculate the weekday of a date. Using this function is an incorrect solution as it defeats the purpose of this exercise.** + +#+begin_src cpp +// PRE: a year greater or equal than 1900 +// POST: returns whether that year was a leap year +bool is_leap_year(int year); + +// PRE: a year greater or equal than 1900 +// POST: returns the number of days in that year +int count_days_in_year(int year); + +// PRE: a month between 1 and 12 and a year greater or equal than 1900 +// POST: returns the number of days in the month of that year +int count_days_in_month(int month, int year); + +// PRE: n/a +// POST: returns whether the given values represent a valid date +bool is_valid_date(int day, int month, int year); + +// PRE: the given values represent a valid date +// POST: returns the number of days between January 1, 1900 and this date (excluding this date) +int count_days(int day, int month, int year); + +// PRE: the given values represent a (potentially invalid) date +// POST: prints the weekday if the date is valid or "invalid date" otherwise. +// Everything must be printed in lowercase. +void print_weekday(int day, int month, int year); +#+end_src + +To complete the task, you have to provide the definition of the aforementioned functions. + +The =calendar.cpp= file contains skeletons of the functions to be implemented. The =main.cpp= file contains testing functions and the main function. In the main function, a menu is printed to select the function that has to be tested. + +**Important** the main is not editable. Required functions must be implemented in =calendar.cpp=. + +**Additional notes:** + +1. For function arguments that do **not** fulfill the precondition, the behavior is undefined. + +1. There are a few opportunities here to use switch statements. Use them if they result in better readable code. + +1. A leap year is defined as follows: It is an integer multiple of 4, except for years evenly divisible by 100, which are not leap years unless evenly divisible by 400. (Source: [[https://en.wikipedia.org/wiki/Leap_year][Wikipedia]]) + +* Solution + +#+begin_src cpp +#include "calendar.h" +#include + +// PRE: a year greater or equal than 1900 +// POST: returns whether that year was a leap year +bool is_leap_year(int year) { + if (year >= 1900) { + if (year % 4 == 0 && year % 100 != 0) + return true; + else if (year % 4 == 0 && year % 400 == 0) + return true; + } + return false; +} + +// PRE: a year greater or equal than 1900 +// POST: returns the number of days in that year +int count_days_in_year(int year) { + if (year >= 1900) { + if (is_leap_year(year) == true) + return 366; + return 365; + } + return 0; +} + +// PRE: a month between 1 and 12 and a year greater or equal than 1900 +// POST: returns the number of days in the month of that year +int count_days_in_month(int month, int year) { + if (year >= 1900 && month > 0 && month <= 12) { + if (is_leap_year(year) == true) { + if (month % 2 != 0 && month != 2 && month <= 7) + return 31; + else if (month % 2 == 0 && month > 7) + return 31; + else if (month == 2) + return 29; + else + return 30; + } else { + if (month % 2 != 0 && month != 2 && month <= 7) + return 31; + else if (month % 2 == 0 && month > 7) + return 31; + else if (month == 2) + return 28; + else + return 30; + } + } + return 0; +} + +// PRE: n/a +// POST: returns whether the given values represent a valid date +bool is_valid_date(int day, int month, int year) { + if (day > 0 && day <= count_days_in_month(month, year) && month > 0 && + month <= 12 && year >= 1900) + return true; + return false; +} + +// PRE: the given values represent a valid date +// POST: returns the number of days between January 1, 1900 and this date +// (excluding this date) +int count_days(int day, int month, int year) { + int res_day = 0; + if (is_valid_date(day, month, year) == true) { + for (int j = 1900; j < year; ++j) { + res_day += count_days_in_year(j); + } + for (int j = 1; j < month; ++j) { + res_day += count_days_in_month(j, year); + } + res_day += (day - 1); + } + return res_day; +} + +// PRE: the given values represent a (potentially invalid) date +// POST: prints the weekday if the date is valid or "invalid date" otherwise. +// Everything must be printed in lowercase. +void print_weekday(int day, int month, int year) { + if (is_valid_date(day, month, year) == true) { + std::string days[7] = {"sunday", "monday", "tuesday", "wednesday", + "thursday", "friday", "saturday"}; + std::cout << days[((count_days(day, month, year) + 1) % 7)]; + } else + std::cout << "invalid date"; +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_5/Task_1/calendar.cpp b/Informatik_I/Exercise_5/Task_1/calendar.cpp deleted file mode 100644 index a7e2406..0000000 --- a/Informatik_I/Exercise_5/Task_1/calendar.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include "calendar.h" -#include - -// PRE: a year greater or equal than 1900 -// POST: returns whether that year was a leap year -bool is_leap_year(int year) { - if (year >= 1900) { - if (year % 4 == 0 && year % 100 != 0) - return true; - else if (year % 4 == 0 && year % 400 == 0) - return true; - } - return false; -} - -// PRE: a year greater or equal than 1900 -// POST: returns the number of days in that year -int count_days_in_year(int year) { - if (year >= 1900) { - if (is_leap_year(year) == true) - return 366; - return 365; - } - return 0; -} - -// PRE: a month between 1 and 12 and a year greater or equal than 1900 -// POST: returns the number of days in the month of that year -int count_days_in_month(int month, int year) { - if (year >= 1900 && month > 0 && month <= 12) { - if (is_leap_year(year) == true) { - if (month % 2 != 0 && month != 2 && month <= 7) - return 31; - else if (month % 2 == 0 && month > 7) - return 31; - else if (month == 2) - return 29; - else - return 30; - } else { - if (month % 2 != 0 && month != 2 && month <= 7) - return 31; - else if (month % 2 == 0 && month > 7) - return 31; - else if (month == 2) - return 28; - else - return 30; - } - } - return 0; -} - -// PRE: n/a -// POST: returns whether the given values represent a valid date -bool is_valid_date(int day, int month, int year) { - if (day > 0 && day <= count_days_in_month(month, year) && month > 0 && - month <= 12 && year >= 1900) - return true; - return false; -} - -// PRE: the given values represent a valid date -// POST: returns the number of days between January 1, 1900 and this date -// (excluding this date) -int count_days(int day, int month, int year) { - int res_day = 0; - if (is_valid_date(day, month, year) == true) { - for (int j = 1900; j < year; ++j) { - res_day += count_days_in_year(j); - } - for (int j = 1; j < month; ++j) { - res_day += count_days_in_month(j, year); - } - res_day += (day - 1); - } - return res_day; -} - -// PRE: the given values represent a (potentially invalid) date -// POST: prints the weekday if the date is valid or "invalid date" otherwise. -// Everything must be printed in lowercase. -void print_weekday(int day, int month, int year) { - if (is_valid_date(day, month, year) == true) { - std::string days[7] = {"sunday", "monday", "tuesday", "wednesday", - "thursday", "friday", "saturday"}; - std::cout << days[((count_days(day, month, year) + 1) % 7)]; - } else - std::cout << "invalid date"; -} diff --git a/Informatik_I/Exercise_5/Task_2/README.md b/Informatik_I/Exercise_5/Task_2/README.md deleted file mode 100644 index 63bf4d5..0000000 --- a/Informatik_I/Exercise_5/Task_2/README.md +++ /dev/null @@ -1,8 +0,0 @@ -_This task is a text-based task. You do not need to write any program/C++ file: the answer should be written in functions.cpp._ - -Consider the functions implemented in `functions.cpp`. For each function, add proper pre- and post-conditions. - -- If no pre-condition is needed, you can simply write "n/a". -- The post-condition does not have to be a mathematical formula, e.g. it can be an informal description, but it must completely characterize the results and effects of the functions depending on the provided parameters. - -**Note**: For the purposes of this task, you can ignore overflows. diff --git a/Informatik_I/Exercise_5/Task_2/README.org b/Informatik_I/Exercise_5/Task_2/README.org new file mode 100644 index 0000000..127f58f --- /dev/null +++ b/Informatik_I/Exercise_5/Task_2/README.org @@ -0,0 +1,57 @@ +#+TITLE: Task 2: Pre- and post-conditions + +/This task is a text-based task. You do not need to write any program/C++ file: the answer should be written in functions.cpp./ + +Consider the functions implemented in =functions.cpp=. For each function, add proper pre- and post-conditions. + +- If no pre-condition is needed, you can simply write "n/a". +- The post-condition does not have to be a mathematical formula, e.g. it can be an informal description, but it must completely characterize the results and effects of the functions depending on the provided parameters. + +**Note**: For the purposes of this task, you can ignore overflows. + +* Solution + +#+begin_src cpp +// PRE: x > 0 +// POST: returns n^x +int f1(int n, int x) { + int res = 1; + for (; x > 0; x--) { + res *= n; + } + return res; +} + +// PRE: n > 0 +// POST: returns number of devisions by 10 with n +int f2(int n) { + int i = 0; + while (n > 0) { + n = n / 10; + ++i; + } + return i; +} + +// PRE: n > 1 +// POST: returns a bool to determine if n is prime +bool f3(int n) { + int i = 2; + for (; n % i != 0; ++i); + return n == i; +} + +// PRE: n is square number +// POST: returns root of n +int f4(int n) { + int i = 0; + while (i * i != n) { + ++i; + } + return i; +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_5/Task_2/functions.cpp b/Informatik_I/Exercise_5/Task_2/functions.cpp deleted file mode 100644 index 6388bf8..0000000 --- a/Informatik_I/Exercise_5/Task_2/functions.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// PRE: x > 0 -// POST: returns n^x -int f1(int n, int x) { - int res = 1; - for (; x > 0; x--) { - res *= n; - } - return res; -} - -// PRE: n > 0 -// POST: returns number of devisions by 10 with n -int f2(int n) { - int i = 0; - while (n > 0) { - n = n / 10; - ++i; - } - return i; -} - -// PRE: n > 1 -// POST: returns a bool to determine if n is prime -bool f3(int n) { - int i = 2; - for (; n % i != 0; ++i); - return n == i; -} - -// PRE: n is square number -// POST: returns root of n -int f4(int n) { - int i = 0; - while (i * i != n) { - ++i; - } - return i; -} diff --git a/Informatik_I/Exercise_5/Task_3/README.md b/Informatik_I/Exercise_5/Task_3/README.md deleted file mode 100644 index 818d83b..0000000 --- a/Informatik_I/Exercise_5/Task_3/README.md +++ /dev/null @@ -1,28 +0,0 @@ -_This task is a text based task. You do not need to write any program/C++ file: the answer should be written in main.md (and might include code fragments if questions ask for them)._ - -# Task: - -What are the problems (if any) with the following functions? Fix them and find appropriate [pre-](https://en.wikipedia.org/wiki/Precondition) and [postconditions](https://en.wikipedia.org/wiki/Postcondition). - -1. function is_even: - -```cpp - -bool is_even(int i) { - if (i % 2 == 0) return true; -} -``` - -1. function invert: - -```cpp -double invert(int x) { - double result; - if (x != 0) { - result = 1.0 / x; - } - return result; -} -``` - -**Hint**: The C++ compiler does not protect you from certain types of errors. Therefore, even if you run a program in Code Expert, it is not guaranteed that the behaviour you observe is the “real” one. We have prepared a [program tracing handout](https://lec.inf.ethz.ch/ifmp/2023/guides/tracing/intro.html) that shows how to execute a program with a pen and paper and which conditions indicate bugs in the executed program not caught by the C++ compiler. diff --git a/Informatik_I/Exercise_5/Task_3/README.org b/Informatik_I/Exercise_5/Task_3/README.org new file mode 100644 index 0000000..ef903fb --- /dev/null +++ b/Informatik_I/Exercise_5/Task_3/README.org @@ -0,0 +1,74 @@ +#+TITLE: Fixing Functions + +/This task is a text based task. You do not need to write any program/C++ file: the answer should be written in main.md (and might include code fragments if questions ask for them)./ + +* Task: + +What are the problems (if any) with the following functions? Fix them and find appropriate [[https://en.wikipedia.org/wiki/Precondition][pre-]] and [[https://en.wikipedia.org/wiki/Postcondition][postconditions]]. + +1. function is_even: + +#+begin_src cpp +bool is_even(int i) { + if (i % 2 == 0) return true; +} +#+end_src + +1. function invert: + + #+begin_src cpp + +double invert(int x) { + double result; + if (x != 0) { + result = 1.0 / x; + } + return result; +} + #+end_src + +**Hint**: The C++ compiler does not protect you from certain types of errors. Therefore, even if you run a program in Code Expert, it is not guaranteed that the behaviour you observe is the “real” one. We have prepared a [[https://lec.inf.ethz.ch/ifmp/2023/guides/tracing/intro.html][programming tracing handout]] that shows how to execute a program with a pen and paper and which conditions indicate bugs in the executed program not caught by the C++ compiler. + +* Solution + +#+begin_src markdown +Please write your solution here. +For your convenience we have added a template for your answers below. + +Note: Remember to also describe the problem of the function. + +# Function `c++|is_even`: + +The problem with this function is that it does not return a bool if the number `i` is uneven. + +```c++ +// PRE: n/a +// POST: returns true if i is even. If not it returns false. +bool is_even(int i) { + if (i % 2 == 0) return true; + else return false; +} +``` + +# Function `c++|invert`: + +The problem with this function is + +```c++ +// PRE: x is positive or negative but not zero. +// POST: returns inverse with respect to multiplication of x. +double invert(int x) { + // TODO: Fix code below. + if (x != 0) { + return 1.0 / x; + } + else + std::cout << "0 has no inverse!"; +} +``` + +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_5/Task_3/main.md b/Informatik_I/Exercise_5/Task_3/main.md deleted file mode 100644 index 067c331..0000000 --- a/Informatik_I/Exercise_5/Task_3/main.md +++ /dev/null @@ -1,35 +0,0 @@ -Please write your solution here. -For your convenience we have added a template for your answers below. - -Note: Remember to also describe the problem of the function. - -# Function `c++|is_even`: - -The problem with this function is that it does not return a bool if the number `i` is uneven. - -```c++ -// PRE: n/a -// POST: returns true if i is even. If not it returns false. -bool is_even(int i) { - if (i % 2 == 0) return true; - else return false; -} -``` - -# Function `c++|invert`: - -The problem with this function is - -```c++ -// PRE: x is positive or negative but not zero. -// POST: returns inverse with respect to multiplication of x. -double invert(int x) { - // TODO: Fix code below. - if (x != 0) { - return 1.0 / x; - } - else - std::cout << "0 has no inverse!"; -} -``` - diff --git a/Informatik_I/Exercise_5/Task_4/README.md b/Informatik_I/Exercise_5/Task_4/README.org similarity index 54% rename from Informatik_I/Exercise_5/Task_4/README.md rename to Informatik_I/Exercise_5/Task_4/README.org index 8790993..32a906e 100644 --- a/Informatik_I/Exercise_5/Task_4/README.md +++ b/Informatik_I/Exercise_5/Task_4/README.org @@ -1,64 +1,139 @@ -Task +#+TITLE: Task 4: Run-length encoding +#+AUTHOR: JirR02 -Run-length encoding is a simple data compression technique that represents $N$ consecutive identical values $W$ (a run) by a tuple ($N,W$). This method is applied for image compression, for instance. Example: +* Task -![Encoding and Decoding](./pictures/encode_decode.png) +Run-length encoding is a simple data compression technique that represents \(N\) consecutive identical values \(W\) (a run) by a tuple (\(N,W\)). This method is applied for image compression, for instance. Example: -Write a program that implements run-length encoding and decoding of a byte sequence as described above. By a byte, we mean an integer value in the range $\[ 0; 255 \]$. Use the stepwise refinement method to implement the program. **Your solution must consist of at least two functions, encode and decode. Please implement them in `run_length.cpp`.** +[[./pictures/encode_decode.png]] + +Write a program that implements run-length encoding and decoding of a byte sequence as described above. By a byte, we mean an integer value in the range \([ 0; 255 ]\). Use the stepwise refinement method to implement the program. **Your solution must consist of at least two functions, encode and decode. Please implement them in =run_length.cpp=.** The _input_ is structured as follows: -1. One integer that determines whether to encode: $0$ or decode: $1$. -1. Byte sequence to be encoded or decoded (of arbitrary length). If a value outside the range $\[ 0; 255 \]$(except $-1$) is entered, output `error` and stop the en- or decoding. +1. One integer that determines whether to encode: \(0\) or decode: \(1\). +1. Byte sequence to be encoded or decoded (of arbitrary length). If a value outside the range \([ 0; 255 ]\) (except $-1$) is entered, output =error= and stop the en- or decoding. 1. Integer -1 signaling the end of the byte sequence. Any extra input should be ignored. For the example above, the inputs are: **Encode:** -```sh +#+begin_src shell 0 42 42 85 85 85 85 172 172 172 13 13 42 -1 -``` +#+end_src **Decode:** -```sh +#+begin_src shell 1 2 42 4 85 3 172 2 13 1 42 -1 -``` +#+end_src _The output_ is expected on a single line in the following format: -1. A start value to indicate the begin of the sequence: either $0$ for decoded values or $1$ for encoded values. +1. A start value to indicate the begin of the sequence: either \(0\) for decoded values or \(1\) for encoded values. 1. The values that make up the encoded or decoded byte sequence. -1. The value $-1$ to indicate the end of the sequence. +1. The value \(-1\) to indicate the end of the sequence. I.e., you can 'reuse' the output as the input. **Note 1):** As the encoded sequence must be a _byte_ sequence, runs of length 256 or longer need to be split into multiple runs of length 255 at most. -**Note 2):** The first input element (the integer that determines wether to encode or decode), is already consumed by the `main`, that calls either the encode or decode function. +**Note 2):** The first input element (the integer that determines wether to encode or decode), is already consumed by the =main=, that calls either the encode or decode function. -**Note 3):** Your output should not be followed by new line (i.e., do not use `std::endl` or `\n` at the end of your printout) +**Note 3):** Your output should not be followed by new line (i.e., do not use =std::endl= or =\n= at the end of your printout) **Note 4):** The program will print your output (the result of the decoding or encoding), surrounded by asterisks. You don't have to worry about them, the autograder can safely recognize your solution -**Note 5):** Output only what is strictly required (the encoded or decoded sequence). The autograder will only accept output that exactly matches the expected result. For all other messages, use `std::cerr` as in: +**Note 5):** Output only what is strictly required (the encoded or decoded sequence). The autograder will only accept output that exactly matches the expected result. For all other messages, use =std::cerr= as in: -```cpp +#+begin_src cpp std::cerr << "This is a test message\n" -``` +#+end_src Those will be ignored by the autograder. **Special cases**: While decoding a byte sequence two special cases can occur. These must be handled as follows: -1. If a byte sequence ends in the middle of a tuple, stop printing the output of en- or decoding and output `error`. -1. Tuples of run-length 0 are possible. For such tuples, output only the leading indicator ($0$/$1$) and the trailing $-1$. +1. If a byte sequence ends in the middle of a tuple, stop printing the output of en- or decoding and output =error=. +1. Tuples of run-length 0 are possible. For such tuples, output only the leading indicator (\(0\)/\(1\)) and the trailing \(-1\). -**Hint**: You can enter multiple numbers at once separated with a space on the console, e.g, you can copy and paste the above examples, and sequentially read them using multiple `std::cin >> _var_` calls. +**Hint**: You can enter multiple numbers at once separated with a space on the console, e.g, you can copy and paste the above examples, and sequentially read them using multiple =std::cin >> _var_= calls. Also note that, even though the program's output and the user input are both shown in the same console, they are processed separately internally, so you do not have to worry that the two will mix: if your program outputs something to the console before reading another value, it will only read the user input and not the previous output value. See the Calculator code in the Lecture 4 handout for an example of reading input and producing output in a loop. Finally, part of the correctness for this task is the termination of your code, so pay attention to this. The autograder may not catch these kinds of mistakes. **Restrictions**: using a vector, an array or a similar data structure in any part of your code is not allowed and would result in 0 points. + +* Solution + +#+begin_src cpp +#include "run_length.h" + +void encode() { + int i; + int c; + int count; + std::cin >> i; + std::cout << 1 << " "; + while (i != -1) { + count = 0; + c = i; + while (i == c && i >= 0 && i <= 255) { + ++count; + std::cin >> i; + if (count == 255) { + break; + } + } + if (i < -1 || i > 255) { + if (count == 0) { + std::cout << "error"; + return; + } else { + std::cout << count << " "; + std::cout << c << " "; + std::cout << "error"; + return; + } + } + std::cout << count << " "; + std::cout << c << " "; + } + std::cout << -1; +} + +void decode() { + int i; + int count; + std::cin >> count; + std::cin >> i; + std::cout << 0 << " "; + while (count != -1) { + if (i < -1 || i > 255) { + std::cout << "error"; + return; + } + if (count < -1 || count > 255) { + std::cout << "error"; + return; + } + for (int j = 0; j < count; ++j) { + std::cout << i << " "; + } + std::cin >> count; + if (count != -1) + std::cin >> i; + if (i == -1) { + std::cout << "error"; + return; + } + } + std::cout << -1; +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Informatik_I/Exercise_5/Task_4/run_length.cpp b/Informatik_I/Exercise_5/Task_4/run_length.cpp deleted file mode 100644 index 899b780..0000000 --- a/Informatik_I/Exercise_5/Task_4/run_length.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include "run_length.h" - -void encode() { - int i; - int c; - int count; - std::cin >> i; - std::cout << 1 << " "; - while (i != -1) { - count = 0; - c = i; - while (i == c && i >= 0 && i <= 255) { - ++count; - std::cin >> i; - if (count == 255) { - break; - } - } - if (i < -1 || i > 255) { - if (count == 0) { - std::cout << "error"; - return; - } else { - std::cout << count << " "; - std::cout << c << " "; - std::cout << "error"; - return; - } - } - std::cout << count << " "; - std::cout << c << " "; - } - std::cout << -1; -} - -void decode() { - int i; - int count; - std::cin >> count; - std::cin >> i; - std::cout << 0 << " "; - while (count != -1) { - if (i < -1 || i > 255) { - std::cout << "error"; - return; - } - if (count < -1 || count > 255) { - std::cout << "error"; - return; - } - for (int j = 0; j < count; ++j) { - std::cout << i << " "; - } - std::cin >> count; - if (count != -1) - std::cin >> i; - if (i == -1) { - std::cout << "error"; - return; - } - } - std::cout << -1; -} diff --git a/Projekt_1/Task_1/guess_a_number.cpp b/Projekt_1/Task_1/guess_a_number.cpp deleted file mode 100644 index 5568e0a..0000000 --- a/Projekt_1/Task_1/guess_a_number.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include -#include -#include "guess_a_number.h" - -// NOTE: You cannot change this file, and you don't need to understand its -// content in order to solve your task. Feel free to look around, however, -// in case you're interested. - -const std::string action = std::getenv("ACTION"); - -// This function returns a randomly chosen integer from the interval [1, max]. -int randomly_choose_a_number(int max) { - return std::rand() % max + 1; -} - -int choose_a_number(int max) { - if (action == "run") { - std::cout << "?\n"; - // Just here to achieve the same output behaviour, in terms of newlines, - // when a user replaces - // std::cin >> number_to_guess; - // by - // number_to_guess = choose_a_number(MAX); - - return randomly_choose_a_number(max); - } else { - int guess; - std::cin >> guess; - - return guess; - } -} diff --git a/Projekt_1/Task_1/guess_a_number.h b/Projekt_1/Task_1/guess_a_number.h deleted file mode 100644 index dee2d61..0000000 --- a/Projekt_1/Task_1/guess_a_number.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef PROJECT_H -#define PROJECT_H - -// NOTE: You cannot change this file. In "only" contains declarations and -// short descriptions of the functionality we provided to you. - -// This function returns a randomly chosen integer from the interval [0, max]. -int randomly_choose_a_number(int max); - -// This function returns a number from the interval [1, max]. -// The number is randomly chosen if we're in interactive mode and parameter -// choose_randomly is true, and read from the keyboard (std::cin) otherwise. -int choose_a_number(int max); - -#endif \ No newline at end of file diff --git a/Projekt_1/Task_1/main.cpp b/Projekt_1/Task_1/main.cpp deleted file mode 100644 index 4506b2d..0000000 --- a/Projekt_1/Task_1/main.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include -#include "guess_a_number.h" - -int main() { - // Declare the required variables - int number_to_guess; // The number to guess - int guess; // The guessed number - - // Pick the number to guess - std::cout << "Number to guess: "; - number_to_guess = choose_a_number(3); // Randomly choose a number from the interval [1, 3] - - // Save number inputted by user into variable guess - std::cin >> guess; - std::cout << "Your guess: "; - - if (guess == number_to_guess) { - std::cout << "Congratulations, you correctly guessed " << number_to_guess << "!"; - } else { - std::cout << "Sorry, but " << guess << " is wrong, " << number_to_guess << " was the number to guess."; - } -} diff --git a/Projekt_1/Task_2/guess_a_number.cpp b/Projekt_1/Task_2/guess_a_number.cpp deleted file mode 100644 index 91d5091..0000000 --- a/Projekt_1/Task_2/guess_a_number.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include -#include -#include -#include "guess_a_number.h" - -// NOTE: You cannot change this file, and you don't need to understand its -// content in order to solve your task. Feel free to look around, however, -// in case you're interested. - -const std::string action = std::getenv("ACTION"); - -void print_attempts_left(int attempts_left) { - std::cout << "You have " << attempts_left << " attempt(s) left.\n"; -} - -void print_you_won(int correct_guess) { - std::cout << "Congratulations, you correctly guessed " << correct_guess << "!\n"; -} - -void print_wrong_guess(int wrong_guess) { - std::cout << "Sorry, but " << wrong_guess << " is wrong.\n"; -} - -void print_you_lost(int number_to_guess, int attempts) { - std::cout << "You lost after " << attempts << " attempt(s) :-( The number to guess was " << number_to_guess << ".\n"; -} - -// This function returns a randomly chosen integer from the interval [1, max]. -int randomly_choose_a_number(int max) { - return std::rand() % max + 1; -} - -int choose_a_number(int max) { - if (action == "run") { - std::cout << "?\n"; - // Just here to achieve the same output behaviour, in terms of newlines, - // when a user replaces - // std::cin >> number_to_guess; - // by - // number_to_guess = choose_a_number(MAX); - - return randomly_choose_a_number(max); - } else { - int guess; - std::cin >> guess; - - return guess; - } -} diff --git a/Projekt_1/Task_2/guess_a_number.h b/Projekt_1/Task_2/guess_a_number.h deleted file mode 100644 index de25c19..0000000 --- a/Projekt_1/Task_2/guess_a_number.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef PROJECT_H -#define PROJECT_H - - -// NOTE: You cannot change this file. It "only" contains declarations and -// short descriptions of the functionality we provided to you. - - -// This function outputs the number of attempts that are left. -// -// Example: the function call print_attempts_left(3) results in the output -// "You have 3 attempt(s) left". -void print_attempts_left(int attempts_left); - -// This function outputs the winning message. -// -// Example: the function call print_you_won(9) results in the output -// "Congratulations, you correctly guessed 9!". -void print_you_won(int correct_guess); - -// This function outputs a message telling the user that their guess was wrong. -// -// Example: the function call print_wrong_guess(1) results in the output -// "Sorry, but 1 is wrong.". -void print_wrong_guess(int wrong_guess); - -// This function outputs the losing message. -// -// Example: the function call print_you_lost(2, 5) results in the output -// "You lost after 5 attempts :-( The number to guess was 2.". -void print_you_lost(int number_to_guess, int attempts); - - -// This function returns a randomly chosen integer from the interval [0, max]. -int randomly_choose_a_number(int max); - -// This function returns a number from the interval [1, max]. -// The number is randomly chosen if we're in interactive mode and parameter -// choose_randomly is true, and read from the keyboard (std::cin) otherwise. -int choose_a_number(int max); - - -// Master implementation for part 1: reads the next guess from the keyboard -// and stores it in the passed variable. -// -// Example: given the function call PART1_read_next_guess(my_guess) and -// assuming that the player enters 1, variable my_guess will afterwards -// have the value 1. -void PART1_read_next_guess(int& guess); - -// Master implementation for part 2: compares guess to number_to_guess, -// outputs a result-depending message (correct/wrong) and updates -// variable play to false if the guess was correct. -// -// Example: given the function call -// PART2_handle_guess(1, 2, continue_playing), a wrong-guess message -// will be outputted. -// -// Example: given the function call -// PART2_handle_guess(2, 2, continue_playing), a correct-guess message -// will be output and variable continue_playing will be set to false. -void PART2_handle_guess(int guess, int number_to_guess, bool& play); - -// Master implementation for part 3: increments the number of guessing -// attempts the player made (variable attempts), and if the maximum -// number of guesses has been made, outputs a corresponding message and -// sets variable play to false. -// -// Example: given the function call -// PART3_finish_round(2, 10, performed_attempts, continue_playing), and -// assuming that performed_attempts has a value of 5, then the only -// effect of the function call is that performed_attempts will be updated -// to 6. -// -// Example: given the function call -// PART3_finish_round(2, 10, performed_attempts, continue_playing), and -// assuming that performed_attempts has a value of 9, then -// performed_attempts will be incremented to 10, a you-lost message will -// be output and continue_playing will be set to false. -void PART3_finish_round(int number_to_guess, int max_attempts, int& attempts, bool& play); - -#endif \ No newline at end of file diff --git a/Projekt_1/Task_2/main.cpp b/Projekt_1/Task_2/main.cpp deleted file mode 100644 index b0fbb30..0000000 --- a/Projekt_1/Task_2/main.cpp +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include "guess_a_number.h" - -int main() { - int number_to_guess; // The number to guess - int max_attempts; // The guessed number - - std::cout << "Number to guess: "; - number_to_guess = choose_a_number(10); // Randomly choose a number from the interval [1, 10] - - std::cout << "Number of attempts: "; - std::cin >> max_attempts; - - // Make sure that the player has at least one attempt - if (max_attempts < 1) max_attempts = 1; - - int attempts = 0; // Attempts made so far - bool play = true; // false once the game is over - - while (play) { - print_attempts_left(max_attempts - attempts); - - // *** Part 1: input the next guess **************************************** - int guess; // The user's guess - //PART1_read_next_guess(guess); - std::cout << "Your guess: "; - std::cin >> guess; - - // *** Part 2: handle the guess the user made ***************************** - //PART2_handle_guess(guess, number_to_guess, play); - if (guess == number_to_guess) { - print_you_won(guess); - play = false; - } else { - print_wrong_guess(guess); - } - - // *** Part 3: finish up the round **************************************** - if (play) { - //PART3_finish_round(number_to_guess, max_attempts, attempts, play); - attempts += 1; - if (attempts == max_attempts) { - print_you_lost(number_to_guess, attempts); - play = false; - } - } - } -} diff --git a/Projekt_2/README.md b/Projekt_2/README.md deleted file mode 100644 index 6b2170c..0000000 --- a/Projekt_2/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# Projekt 2: Hangman - -## Layers - -### Start (Optional) - -Beim Starten des Spiels soll ein Welcome screen erscheinen mit den Optionen, das Spiel zu starten und das Spiel zu beenden. Damit der Welcome screen gut aussieht soll es Terminal Art beinhalten. Nach dem Start Vorgang wird der Anzahl der Spieler gefragt. -Daraus entstehen 2 Szenarien: - -1. Falls es im Einzelspieler Modus ist, wird ein Wort aus der Liste ausgesucht. -1. Falls im Mehrspieler Modus, darf der andere Spieler ein Wort zum Raten auswählen. - -- [ ] Start input -- [ ] End input -- [ ] Invalid Input -- [ ] Single or Multiplayer -- [ ] Terminal Art - -### Game - -Das zu ratende Wort wird verdeckt im Terminal gezeigt. Es wird dann ein Input als Buchstabe verlangt. Wenn der Input zu lang oder ein invalid character ist, wird der Spieler nochmals dazu aufgefordert, ein Buchstabe einzugeben. -Daraus entstehen 2 Szenarien: - -1. Ist der Buchstabe in der Zahl enthalten, wird der Buchstabe aufgedeckt und ein positiver Satz erscheint im Terminal. -1. Ist der Buchstabe falsch, so wird ein Leben abgezogen und ein negativer Satz wird ausgespuckt. - -Während des ganzen Spiels wird der Terminal Art aktualisiert. - -- [ ] Wort verdeckt im Terminal anzeigen -- [ ] Input von einem Buchstaben verlangen -- [ ] Input kontrollieren -- [ ] Buchstabe kontrollieren -- [ ] Positiver Satz -- [ ] Buchstabe aufdecken -- [ ] Negativer Satz -- [ ] (Optional) Terminal Art - -### End - -Es entstehen daraus zwei Endszenarien: - -1. Wurden alle Buchstaben eraten, so wird ein Gewinner Satz ausgesprochen und gefragt ob das Spiel neugestartet werden soll. -1. Wurden alle Versuche verbraucht, so wird ein verlierer Satz ausgesprochen, das Wort aufgelöst und gefragt, ob das Spiel neugestartet werden soll. - -Falls das Programm geschlossen wird, wird ein Abschiedssatz gezeigt. - -- [ ] Gewinner Satz -- [ ] Verlierer Satz -- [ ] (Optional) Fragen für eine neue Runde -- [ ] Abschiedssatz diff --git a/Projekt_2/hangman.cpp b/Projekt_2/hangman.cpp deleted file mode 100644 index eec1e37..0000000 --- a/Projekt_2/hangman.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include "hangman.h" -#include "termcolor.h" - - -// NOTE: You cannot change this file, and you don't need to understand its -// content in order to solve your task. Feel free to look around, however, -// in case you're interested. - - -const string action = std::getenv("ACTION"); -const string words[] = { - #include "words.csv" - "sentinel" -}; - -string color(string c) { - return action == "run" ? c : ""; -} - -string chooseWord() { - string word; - if (action == "test" || action == "submit") { - std::cin >> word; - } else { - int i = rand() % (sizeof(words)/sizeof(*words) - 1); // don't take the last word (which is 'sentinel') - word = words[i]; - std::cout << "A random (english) word with " << word.length() << " characters has been chosen." << std::endl; - return word; - } - return word; -} - -string createWorkingCopy(string word){ - string result = word; - for (unsigned int i = 0; i < result.length(); ++i) { - result.at(i) = '_'; - } - return result; -} - -void showHangman(int wrongGuesses) { - std::cout - << "\n" -// << "

Attempts left: " << maxWrongGuesses - wrongGuesses << "

\n" - << "\n" - << "
" << std::endl; -} - -void printGameState(int maxWrongGuesses, int wrongGuesses){ - std::cout << color(gray) << "\nAttempts left: " << (maxWrongGuesses - wrongGuesses) << color(reset) << "\n"; -} - -void printWorkingCopy(string workingCopy){ - std::cout << color(blue) << "[ " ; - for (unsigned int i = 0; i < workingCopy.length(); ++i) { - std::cout << workingCopy.at(i) << " "; - } - std::cout << "]\n" << color(reset); -} - -void printYouLost(string word){ - std::cout << "The word was: " << color(white) << word << color(red) << "\nYou lost!\n" << color(reset); -} - -void printYouWon(string word){ - std::cout << "\n"; - printWorkingCopy(word); - std::cout << color(green) << "You won!\n" << color(reset); -} \ No newline at end of file diff --git a/Projekt_2/hangman.h b/Projekt_2/hangman.h deleted file mode 100644 index a1d26cc..0000000 --- a/Projekt_2/hangman.h +++ /dev/null @@ -1,97 +0,0 @@ -#ifndef HANGMAN_H -#define HANGMAN_H - -#include -#include - -using std::string; - -// NOTE: You cannot change this file. It "only" contains declarations and -// short descriptions of the functionality we provided to you. - - -/** - * This function returns a random english word. Use this to generate a new - * word to guess. It is imperative that you use this function to get a word, - * otherwise, the auto-grader will not work properly when testing or - * submitting your project. - */ -string chooseWord(); - -/** - * This function creates a "working copy" based on a given word. It returns a - * string with the same amount of characters than the word, but all of them - * are initially set to "_" (underscore) - */ -string createWorkingCopy(string word); - -/** - * You may call this function to render a little hangman figure in the HTML view. - * This is completely optional, the tests don't rely on this function being - * called. As argument, the function takes the number of wrong guesses and - * selects the correct hangman picture to show. - */ -void showHangman(int wrongGuesses); - -/** - * This function prints the number of remaining attempts (based on the provided - * number of wrong guesses. Call this method before each attempt. - * - * Example: The call 'printGameState(2)' will output: "Attempts left: 4" - * because MAX_WRONG_GUESSES is 6, and 6 - 2 = 4 - */ -void printGameState(int maxWrongGuesses, int wrongGuesses); - -/** - * This function prints the partly uncovered word (the working copy) in the - * desired format. - * - * Example: If workingCopy is "_xp_rt", a call to printWorkingCopy(workingCopy) - * will print "[ _ x p _ r t ]" - this is the format that is expected by the - * autograder. - */ -void printWorkingCopy(string workingCopy); - -/** - * This function must be called if the game was lost (that is, on the 6th - * wrong guess). - * - * Example: If the correct word was "expert", its outputs - * "The word was: expert - * You lost!" - */ -void printYouLost(string word); - -/** - * This function must be called if the game was won (that is, the word was - * guessed with less than 6 wrong guesses). - * - * Example: If the correct word was "expert", its outputs - * "[ e x p e r t ] - * You won!" - */ -void printYouWon(string word); - - -// THE FOLLOWING FUNCTIONS CAN BE USED INTERACTIVELY TO IMPLEMENT THE INDIVIDUAL -// PARTS, BUT THEY DONT'T WORK DURING SUBMISSION - -/** - * Part 1: Ask the user to enter a character and update parameter 'guess' - */ -void PART1_readCharacter(char& guess); - -/** - * Part 2: Set the guessed character in the working copy. Updates parameter - * 'workingCopy' and sets parameter 'found' to either true or false - */ -void PART2_updateWorkingCopy(string word, char guess, string& workingCopy, bool& found); - -/** - * Part 3: Check if game is finished and update wrongGuesses variable. - * Print the approriate messages in the console. Updates parameters 'done' and - * 'wrongGuesses' - */ -void PART3_updateGameState(string word, string workingCopy, bool found, int maxWrongGuesses, bool& done, int& wrongGuesses); - -#endif \ No newline at end of file diff --git a/Projekt_2/main.cpp b/Projekt_2/main.cpp deleted file mode 100644 index 3cb805b..0000000 --- a/Projekt_2/main.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include -#include -#include "hangman.h" - -using std::string; - -int main() { - // Word the player needs to guess (randomly selected) - string word = chooseWord(); - //string word = "success"; - - // Initialise the "uncovered" word that is shown to the player: the uncovered - // word is obtained by replacing each letter from the original word (variable - // word) with an underscore (i.e. _). - string workingCopy = createWorkingCopy(word); - - // This variable indicates whether or not the game is over - bool done = false; - - int wrongGuesses = 0; // Number of wrong guesses - int maxWrongGuesses = 6; // Maximum number of wrong guesses (don't change) - - // Draw the empty gallow - showHangman(0); - - // Game loop (each iteration is a round of the game) - while (!done) { - printGameState(maxWrongGuesses, wrongGuesses); - printWorkingCopy(workingCopy); - - - /** Part 1: input next guess **********************************************/ - char guess = '\0'; - // TODO: replace the following line with your implementation - //PART1_readCharacter(guess); - std::cout << "Your guess: "; - std::cin >> guess; - - - /** Part 2: update working copy *******************************************/ - bool found = false; - // TODO: replace the following line with your implementation - //PART2_updateWorkingCopy(word, guess, workingCopy, found); - for (int i = 0; i != word.length(); i++) { - if (guess == word.at(i)) { - found = true; - workingCopy.at(i) = guess; - } - } - - - - /** Part 3: update game state *********************************************/ - // TODO: replace the following line with your implementation - //PART3_updateGameState(word, workingCopy, found, maxWrongGuesses, done, wrongGuesses); - if (workingCopy == word) { - done = true; - printYouWon(word); - } else if (found == false) { - wrongGuesses += 1; - } - if (wrongGuesses == maxWrongGuesses) { - done = true; - printYouLost(word); - } - } - - return 0; -} diff --git a/Projekt_2/termcolor.h b/Projekt_2/termcolor.h deleted file mode 100644 index e77c713..0000000 --- a/Projekt_2/termcolor.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef TERMCOLOR_H -#define TERMCOLOR_H - - -// NOTE: You cannot change this file, and you don't need to understand its -// content in order to solve your task. Feel free to look around, however, -// in case you're interested. - - -const auto red = "\033[31;1m"; -const auto green = "\033[32;1m"; -const auto yellow = "\033[33;1m"; -const auto blue = "\033[34;1m"; -const auto magenta = "\033[35;1m"; -const auto cyan = "\033[36;1m"; -const auto gray = "\033[39;2m"; -const auto white = "\033[39;1m"; -const auto reset = "\033[0m"; - -#endif \ No newline at end of file diff --git a/Projekt_2/words.csv b/Projekt_2/words.csv deleted file mode 100644 index 99ae514..0000000 --- a/Projekt_2/words.csv +++ /dev/null @@ -1,100 +0,0 @@ -"available", -"exaggerate", -"ancestor", -"architect", -"neighborhood", -"curriculum", -"promotion", -"opera", -"frequency", -"excavation", -"guarantee", -"reflection", -"benefit", -"development", -"average", -"ghostwriter", -"unlikely", -"disturbance", -"initiative", -"hospitality", -"mastermind", -"eyebrow", -"consciousness", -"operational", -"vehicle", -"housewife", -"capital", -"execution", -"terrify", -"disagree", -"exclusive", -"equinox", -"essential", -"imperial", -"publicity", -"secretary", -"nationalist", -"attention", -"established", -"magnitude", -"orientation", -"contraction", -"intention", -"seminar", -"forecast", -"manufacturer", -"reception", -"fabricate", -"mosquito", -"cooperative", -"parachute", -"exotic", -"demonstrate", -"production", -"spontaneous", -"minimum", -"abolish", -"holiday", -"formation", -"admission", -"handicap", -"continuous", -"presentation", -"constituency", -"unique", -"violation", -"radical", -"notebook", -"custody", -"dictionary", -"comprehensive", -"dominant", -"requirement", -"opponent", -"business", -"national", -"manufacture", -"nominate", -"liberal", -"continuation", -"galaxy", -"interest", -"ignorant", -"indirect", -"illustrate", -"proportion", -"projection", -"philosophy", -"acceptable", -"aluminium", -"continental", -"potential", -"vegetarian", -"elephant", -"advantage", -"recording", -"agenda", -"electronics", -"engagement", -"lonely", \ No newline at end of file diff --git a/README.md b/README.org similarity index 65% rename from README.md rename to README.org index 17d60be..a39fc3c 100644 --- a/README.md +++ b/README.org @@ -1,15 +1,16 @@ -# ETH Informatik Projekte +#+TITLE: ETH Computer Science Projects +#+AUTHOR: JirR02 In this respository the computer science project of the ETH of D-ITET 2024 are managed. They can be used for inspiration. -The projects are uploaded on [Code Expert](https://expert.ethz.ch/enrolled/AS24/itet0/exercises). +The projects are uploaded on [[https://expert.ethz.ch/enrolled/AS24/itet0/exercises][Code Expert]]. -## DISCLAIMER!!! +* DISCLAIMER!!! I assume no liability for possible errors in the code (it certainly has a few in it, since I write it myself). Bugs can be reported via Discord, WhatsApp, Mail and Moodle. ---- +----- Made by JirR02 in Switzerland 🇨🇭 diff --git a/Vorkurs/Projekt_1/Task_1/README.org b/Vorkurs/Projekt_1/Task_1/README.org new file mode 100644 index 0000000..37e22cd --- /dev/null +++ b/Vorkurs/Projekt_1/Task_1/README.org @@ -0,0 +1,127 @@ +#+TITLE: Project 1: Guess A Number (Task 1) +#+AUTHOR: JirR02 + + +* About this task + +** Project overview + +The goal of the first project is to program a simple number guessing game: the player needs to correctly guess a number, chosen from an interval \([1,N]\), with at most \{K\} guesses. + +In the lecture, a first version of the game was presented, in which the player had only one chance of guessing the correct number. In order to implement the full game, you will have to extend this version by allowing the player to guess up to \(K\) times. + +The first project consists of two tasks: *task 1* /(this task)/ is to reimplement the first version of the game that was presented in the lecture, *task 2* is to implement the full game. + +** General development advice + +Develop your program step-by-step, and save, run and compile it often. I.e. implement a single feature, such as inputting the guess, or comparing the guess and the correct number, and then compile and run the program to see if your code (still) works as intended. Small changes and repeated testing make it easier for you to observe problems, to work out what causes them, and to finally solve them. + +** Fulfilling requirements and testing programs + +A particular goal of this task is to make you understand how strongly connected requirements and testing (and thus grading submissions) are. E.g. if the task description requires output of the shape "I␣saw␣\(n\)␣cat(s).", where $n$ is a number and ␣ represents blanks/whitespaces, your program will not be considered correct if it outputs a text that is "basically the same", but does not precisely match the requirements. E.g. the following outputs, while very close to the expected output, do not match the shape specified above: "i␣saw␣3␣cat(s).", "I␣saw␣3␣cats.", "I␣saw␣1␣cat.", "I␣saw␣2␣cat(s)" and "i␣saw␣2␣␣cat(s)␣.". + +Meeting such requirements precisely is necessary for testing: we automatically (at least to some extent) test correctness of your programs by comparing the expected output to the output produced by your program. Since these comparisons are performed by a computer, it is much much easier to do them syntactically, i.e. letter-by-letter. + +However, being able to precisely fulfil requirements is more generally important, in particular when working with customers: imagine you order a black smartphone, but then get delivered a dark blue one (same make and model). Although "basically the same", it's just not what you ordered. The same holds for software — it's the details that matter. + +** Your task + +To solve this task, proceed as follows: + +1. Look at the template program, in particular main.cpp, and see what's already there (e.g. variable declarations) and what's still missing. The latter is hinted at by TODO comments. +1. The template already contains code for picking the number to guess. By default, the number is randomly choosen from the interval \([1,3]\): + +#+begin_src cpp +number_to_guess = choose_a_number(3); +#+end_src + +/During development/, you might want to change this line: e.g. read the number from the keyboard: + +#+begin_src cpp +std::cin >> number_to_guess; +#+end_src + +or even hard-code (i.e. fix) a specific number, e.g. + +#+begin_src cpp +number_to_guess = 3; +#+end_src + +However, in order to run the automatic tests, and /when submitting your final version/, your program /must/ either read the word from the keyboard or use the ~choose_a_number~ function. + +1. Now address the first TODO comment: by outputting the text "Your␣guess:␣" (as before, ␣ denotes a blank/whitespace character), followed by inputting the guess from the keyboard into variable guess. +2. Now address the second TODO comment: by comparing the two numbers for equality. If they are, output the line + +#+begin_src shell +Congratulations,␣you␣correctly␣guessed␣X! +#+end_src + +where X is the correctly guessed number. Since the output is expected to be a /line/, don't forget to end it with either ~\n~ or ~std::endl~. + +If the guess was wrong, however, output the line + +#+begin_src shell +Sorry,␣but␣Y␣is␣wrong,␣X␣was␣the␣number␣to␣guess. +#+end_src + +where Y is the incorrectly guessed number. + +** Examples + +As an illustration, consider the following example in- and outputs of two games (in which the number to guess was randomly chosen). A successfully completed game: + +#+begin_src shell +Number to guess: ? +Your guess: 3 +Congratulations, you correctly guessed 3! +#+end_src + +And a lost game: + +#+begin_src shell +Number to guess: ? +Your guess: 2 +Sorry, but 2 is wrong, 1 was the number to guess. +#+end_src + +** Testing your program + +You can always test your program manually: click the "play" button in the bottom panel, run your program and see if it behaves as expected. + +Relevant for your final submission, however, is if it passes the automated tests: to run those, click the "chemistry flask" button in the bottom panel and wait for the output to appear. If your program passes all tests — everything is green and your score is 100% — then your program is ready to be submitted. + +Otherwise, /carefully/ compare the expected output to the actual output to find out what went wrong. + +*Reminder*: The devil is in the detail! Pay attention to whitespace and newline characters, and in general check that your output fulfils all requirements, even the "boring" ones. + +** Submitting your solution + +Finally, submit your solution (your program) by clicking the corresponding button in the top right corner of the Code Expert IDE (open Task/History first). Your program will be tested automatically, and your score will be shown in the "History" view, which can be opened by clicking on the corresponding tab on the right of the Code Expert IDE. Note that you can submit arbitrarily often (before the exercise deadline, of course), and your last submission will be considered for grading. + +For this task, all tests need to pass in order to successfully solve this task. This should be rather easy, though, since there isn't much that can go wrong. + +You can also see the results for your submission on the "Enrolled Courses" tab of Code Expert, as green or red percentage values to the left of the task's name. + +* Solution + +#+begin_src cpp +#include +#include "guess_a_number.h" + +int main() { + int number_to_guess; // The number to guess + int guess; // The guessed number + + std::cout << "Number to guess: "; + number_to_guess = choose_a_number(3); + + std::cin >> guess; + std::cout << "Your guess: "; + + if (guess == number_to_guess) { + std::cout << "Congratulations, you correctly guessed " << number_to_guess << "!"; + } else { + std::cout << "Sorry, but " << guess << " is wrong, " << number_to_guess << " was the number to guess."; + } +} +#+end_src diff --git a/Vorkurs/Projekt_1/Task_2/README.org b/Vorkurs/Projekt_1/Task_2/README.org new file mode 100644 index 0000000..e29608e --- /dev/null +++ b/Vorkurs/Projekt_1/Task_2/README.org @@ -0,0 +1,161 @@ +#+TITLE: Project 1: Guess the Number (Task 2) +#+AUTHOR: JirR02 + +* Project overview + +The goal of the first project is to program a simple number guessing game: the player needs to correctly guess a number, chosen from an interval\([1,N]\), with at most \(K\)guesses. + +In the lecture, a first version of the game was presented, in which the player had only one chance of guessing the correct number. In order to implement the full game, you will have to extend this version by allowing the player to guess up to \(K\) times. + +The first project consists of two tasks: *task 1* was to reimplement the first version of the game that was presented in the lecture, *task 2* /(this task)/ is to implement the full game. + +* Stepwise development + +The program template of task 2 differs from that of task 1 in two important ways: + +1. A goal of task 1 was to show you how important — and potentially cumbersome — it is to precisely fulfil output requirements and to pass the automated tests. This is no longer the focus of task 2, and you are therefore given functions such as =print_you_won(...)= that generate the expected output for you. + +1. The final program consists of three major parts, and the template has three corresponding "holes" where you have to fill in code: inputting the next guess, checking the guess, and finishing the current round (we refer to each guess as one round of the game). + +To make it easier for you to develop your solution step by step, you are given a "master implementation" for these steps, e.g =PART1_read_next_guess(...)=, which you must replace with your own code. Use the following workflow: + +1. Run the tests: everything should be fine (thanks to the master implementations) + +1. Comment the first master implementation; now all tests should fail + +1. Write your own code that replaces the commented master implementation + +1. Once all tests pass again, continue by commenting and replacing the next master implementation + +1. Once you have replaced all master implementations with your own code (and all tests pass), your solution is ready to be submitted. *Read the remarks at the end of this text!* + +* Your task + +As mentioned above, you can develop the final solution step by step, by iteratively replacing each call to a =STEP...= master implementation by your own code. + +** Step 1: input the next guess + +1. Find the code line + + #+begin_src cpp + PART1_read_next_guess(guess); + #+end_src + + and comment it, i.e. change it to + + #+begin_src cpp + // PART1_read_next_guess(guess); + #+end_src + +1. As a replacement for the commented master implementation, write code that outputs "Your␣guess:␣" (as before, ␣ denotes a blank/whitespace character), and then inputs the next guess from the keyboard into variable guess. + +1. Run the tests, they should all pass again + +** Step 2: handle the guess the user made + +1. Find and comment the code line + + #+begin_src cpp + PART2_handle_guess(guess, number_to_guess, play); + #+end_src + +1. Write code that compares the user-made guess with the number to guess: if the two are equal, call =print_you_won(guess)= to generate a you-won message, and set variable =play= to =false= to end the game. Otherwise, call =print_wrong_guess(guess)= to generate a wrong-guess message (and let the game continue). + +** Step 3: handle the guess the user made + +1. Find and comment the code line + +#+begin_src cpp +PART3_finish_round(number_to_guess, max_attempts, attempts, play); +#+end_src + +1. Write code that increments the number of attempts the user made by 1. Furthermore, write code that 1. checks if the maximum number of attempts has been reached, and if so, 2. call print_you_lost(number_to_guess, attempts) and set play to false. + +* Examples + +As an illustration, consider the following example in- and outputs of two games (in which the number to guess was randomly chosen). A successfully completed game: + +#+begin_src shell +Number to guess: ? +Number of attempts: 3 +You have 3 attempt(s) left. +Your guess: 7 +Sorry, but 7 is wrong. +You have 2 attempt(s) left. +Your guess: 3 +Congratulations, you correctly guessed 3! +#+end_src + +And a lost game: + +#+begin_src shell +Number to guess: ? +Number of attempts: 2 +You have 2 attempt(s) left. +Your guess: 123 +Sorry, but 123 is wrong. +You have 1 attempt(s) left. +Your guess: 321 +Sorry, but 321 is wrong. +You lost after 2 attempt(s) :-( The number to guess was 2. +#+end_src + +* Submitting your solution + +*Important*: you /must/ replace all three master implementations (calls to functions =PART1/2/3=) with your own code! Your submission /will not be accepted/ if it still uses the master implementations, regardless of how many tests pass when /you/ run them. + +----- +* Solutions + +#+begin_src cpp +#include +#include "guess_a_number.h" + +int main() { + int number_to_guess; + int max_attempts; + + std::cout << "Number to guess: "; + number_to_guess = choose_a_number(10); + + std::cout << "Number of attempts: "; + + if (max_attempts < 1) max_attempts = 1; + + int attempts = 0; // Attempts made so far + bool play = true; // false once the game is over + + while (play) { + print_attempts_left(max_attempts - attempts); + + // *** Part 1: input the next guess **************************************** + int guess; // The user's guess + //PART1_read_next_guess(guess); + std::cout << "Your guess: "; + std::cin >> guess; + + // *** Part 2: handle the guess the user made ***************************** + //PART2_handle_guess(guess, number_to_guess, play); + if (guess == number_to_guess) { + print_you_won(guess); + play = false; + } else { + print_wrong_guess(guess); + } + + // *** Part 3: finish up the round **************************************** + if (play) { + //PART3_finish_round(number_to_guess, max_attempts, attempts, play); + attempts += 1; + if (attempts == max_attempts) { + print_you_lost(number_to_guess, attempts); + play = false; + } + } + } +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Vorkurs/Projekt_2/README.org b/Vorkurs/Projekt_2/README.org new file mode 100644 index 0000000..c777d47 --- /dev/null +++ b/Vorkurs/Projekt_2/README.org @@ -0,0 +1,258 @@ +#+TITLE: Project 2: Hangman +#+AUTHOR: JirR02 + +* Project Overview + +The goal of this project is to implement a version of the popular guessing game known as Hangman (German: Galgenmännchen). The rules of the game are simple: the first player picks a word which the second player has to guess character by character — with a limited amount of guesses. + +When played on paper, a snapshot of the game typically looks as follows: + +[[./game.png]] + +or your version, we focus on the essence of the game: + +1. Choosing a word and initialising the game +1. Repeatedly guessing characters, and uncovering them if they occur in the chosen word +1. Eventually announcing that the player won ... or lost + +** A primer on strings and chars + +In =C++= (and in most other programming languages), sequences of characters, such as the word the player needs to guess, can be represented as strings. Strings will be introduced properly in your later, regular computer science course; for now, you only need to know the following about strings in order to implement Hangman: + +1. Strings and operations thereon are provided by the *string* library: + + #+begin_src cpp + #include + using std::string; + #+end_src + + The first line allows us to use the =c++= *string* library, the second line allows us to directly use =string= as a data type, instead of having to write =std::string= everywhere. + +1. A variable named 'word' of type string can be declared as follows: + + #+begin_src cpp + string word; + #+end_src + +1. String-typed variables can be set as follows: + + - By using string literals, which are enclosed in quotation marks: + + #+begin_src cpp + word = "potato"; + #+end_src + + - By reading a string from the keyboard: + + #+begin_src cpp + std::cin >> word; + #+end_src + + - By assigning it another string + + #+begin_src cpp + word = chooseWord(); + #+end_src + + The function chooseWord() returns a string value which is then assigned to the variable word. + +1. The length (type unsigned int) of a string can be determined by using the length function, which returns the number of characters in the string: + + + #+begin_src cpp + string word = "hangman"; + std::cout << word.length(); // outputs: 7 + #+end_src + +1. The nth character (type char) of a string can be accessed using the at function: + + #+begin_src cpp + string word = "hangman"; + std::cout << word.at(0); // Output: h (the first character) + std::cout << word.at(6); // Output: n (the last character) + #+end_src + + Note that the first character is at position 0 and the last character at position length() - 1! + + The nth character can also be replaced by using the at function, e.g. + + #+begin_src cpp + string workingCopy = "_______"; + workingCopy.at(3) = 'n'; + std::cout << workingCopy; // Output: __n____ + #+end_src + + where '_' denotes a single character (of type char). + +1. Similar to whole strings, you can also declare variables for single characters (type char) and read them from the keyboard: + + #+begin_src cpp + char guess; + std::cin >> guess; + #+end_src + +** Stepwise development + +The program template that you start with has been developed using the /stepwise refinement/ technique, and just like for project 1, task 2, contains master implementations (functions =PART1=... etc.) that you must replace with your own code. + +We also provide you with output-generating functions (e.g. =printYouWon()=) that make it easier for you to please the tests (and thus the autograder). + +As before, we suggest that you develop your program step-by-step, and run or test it often. I.e. implement a single part, such as reading the next guess from the keyboard or updating the working copy, and then run and test the program to see if it (still) works as intended. + +** Implementing the game + +Your job is to implement three major parts of the actual algorithm to play the game. As before, each part can be implemented separately. + +The following variables are already declared in the template given to you: + +- =string= word: This variable contains the word that must be guessed + +- =string= workingCopy: This variable is initialized with a string that has the same size as the string word. Each character in this string is initialized with an underscore (_). + +- =bool= done: If this variable is set to true the program will not play another round of the game (both in the case of winning and losing). + +- =int= wrongGuesses: This variable is initialized with 0 and must be incremented by one every time a guessed character doesn't occur in the word to guess. + +- =int= maxWrongGuesses: This variable is initialized with constant 6. Don't change it. + +- =bool= found: This variable indicates whether (true) or not (false) the guessed character occurs in the word to guess. + +*Note:* Each of the following parts is already implemented in a master implementation function (=PART=...), which you need to replace with your own code. The corresponding places in the code are marked by TODO comments. + +*** Part 1 + +This part is about reading the next guess from the keyboard. + +Comment out the call to =PART1_readCharacter= and replace it by an implementation that performs the following steps: + +1. Output the text " =Your guess:= " +1. Read a single character from the keyboard into variable guess. + +You already know how to output text; see the string primer above (point 6) for how to input a single character. + +*** Part 2 + +This part involves checking if the guessed character occurs in the word, and updating the =workingCopy= accordingly: by replacing the underlines at the respective position(s) by the guessed character. Variable found indicates if the guessed character was found in the word. + +Comment out the call to =PART2_updateWorkingCopy= and replace it by an implementation that performs the requested operation. + +*Example (found):* If variable word is set to "success", variable =workingCopy= still contains the initial underlines ("=_______=") and the current guess is '=c=', then two actions must be performed: + +1. Variable found must be set to =true=, because '=c=' occurs in the word "success" +1. All occurrences of the letter '=c=' must be uncovered in the working copy, thus variable =workingCopy= must be changed to have the content "=__cc___=" + +*Example (not found):* If variable word is set to "success", variable =workingCopy= still contains the initial underlines ("=_______=") and the current guess is '=x=', then the following is important: + +1. Variable found must remain =false= (because '=x=' does not occur in "success" +1. Variable =workingCopy= must not be changed. + +*** Part 3 + +This part is about determining if the game continues, or if it is already won or lost. + +Comment out the call to =PART3_updateGameState= and replace it by an equivalent implementation of your own, as described next. + +If the player made a correct guess and we uncovered at least one further character in the working copy (in which case variable found has value =true=), and if variable =workingCopy= now equals variable word, then the game has been won. Two things must happen in this case: + +1. Set variable done to true, to indicate that the game must not continue. +1. Call =printYouWon(word)=, which will output the result of the game (in a format required by the autograder). + +Otherwise, if the player guessed incorrectly (in which case variable found is =false=), variable =wrongGuesses= must be incremented by one. If this variable is afterwards equal to =maxWrongGuesses= then the game is lost, in which case the following two things must happen: + +1. Set variable done to =true=, to indicate that the game must not continue. +1. Call =printYouLost(word)=, which will output the result of the game (in a format required by the autograder). + +In all other situations, just make sure that variable done remains =false=. This ensures that the game continues. + +** Submitting your solution + +*Important:* you must replace all three master implementations (calls to functions =PART1/2/3=) with your own code! Your submission /will not be accepted/ if it still uses the master implementations, regardless of how many tests pass when you run them. + +To successfully complete this project, your solution needs to pass 12 out of 17 tests, i.e. you don't need to score 100%. + +** Hints + +- Checking for equality of strings can be done using the ==== operator, the same way you would check equality of numbers or booleans. +- Pimp your implementation by calling =showHangman(i)= to draw the gallows after =i= incorrect guesses (for i between 0 and 6) +- You don't need to account for German umlauts, French accents etc. (such as ö or é) +- You do not need to handle duplicated guesses in any special way. E.g. if the player guesses X twice, then either nothing happens the second time around (if X occurs in the word) or the player loses a point each time (if X does not occur in the word). +- If you're interested (and brave enough), you can find more information about strings at https://en.cppreference.com/w/cpp/string + + +* Solution + +#+begin_src cpp +#include +#include +#include "hangman.h" + +using std::string; + +int main() { + // Word the player needs to guess (randomly selected) + string word = chooseWord(); + //string word = "success"; + + // Initialise the "uncovered" word that is shown to the player: the uncovered + // word is obtained by replacing each letter from the original word (variable + // word) with an underscore (i.e. _). + string workingCopy = createWorkingCopy(word); + + // This variable indicates whether or not the game is over + bool done = false; + + int wrongGuesses = 0; // Number of wrong guesses + int maxWrongGuesses = 6; // Maximum number of wrong guesses (don't change) + + // Draw the empty gallow + showHangman(0); + + // Game loop (each iteration is a round of the game) + while (!done) { + printGameState(maxWrongGuesses, wrongGuesses); + printWorkingCopy(workingCopy); + + + /** Part 1: input next guess **********************************************/ + char guess = '\0'; + // TODO: replace the following line with your implementation + //PART1_readCharacter(guess); + std::cout << "Your guess: "; + std::cin >> guess; + + + /** Part 2: update working copy *******************************************/ + bool found = false; + // TODO: replace the following line with your implementation + //PART2_updateWorkingCopy(word, guess, workingCopy, found); + for (int i = 0; i != word.length(); i++) { + if (guess == word.at(i)) { + found = true; + workingCopy.at(i) = guess; + } + } + + + + /** Part 3: update game state *********************************************/ + // TODO: replace the following line with your implementation + //PART3_updateGameState(word, workingCopy, found, maxWrongGuesses, done, wrongGuesses); + if (workingCopy == word) { + done = true; + printYouWon(word); + } else if (found == false) { + wrongGuesses += 1; + } + if (wrongGuesses == maxWrongGuesses) { + done = true; + printYouLost(word); + } + } + + return 0; +} +#+end_src + +----- + +Made by JirR02 in Switzerland 🇨🇭 diff --git a/Vorkurs/Projekt_2/game.png b/Vorkurs/Projekt_2/game.png new file mode 100644 index 0000000000000000000000000000000000000000..3775ea841bf03a1e2e690a10123a4056b026f54d GIT binary patch literal 1956 zcmZ`)c{Cg77EhI`wZ&ATW2Vn4CSS0Y;CQzB&Z_9QnVGKyrxRa(9&Q= zEmbOMC_xAkUYnt<%2H7+N}SlDf==qpdwFkuR!tcER}jq;b#rd<-vUE+g70$U61X%dA?Uw z>usfShT@SA0#)&-kdtmt@Gb*(2X^i7w$qc%l7ZKjzu@Wsx+#F{A@O%OVi# z1l)+Br|$w}6%Ot9C4?Jn>;68ZXUL^kcvsO`MnQb1l+ze_9B_uVF4%t$)l|~7Ztup< zXZ+GD!V;Qh(!Tnrp^I*pVxnUMSrx?l{?KSLmdE_Ku7dVwtxP263iYi@z~ zO*ljay#8->#C7aRXKE6h>?YVT_?#*duY0fs5y!RKQy|r#J>5h5MJ}+jDeXAmABWJd z3$@-D*aqjy@%vYAh@*##8i^<{umGsQcXA*{gjkC%!^sB}ltp*fE9I78sUrlvpfr#m zoA^Dv5-EWDC5sxRmgoTmTa85E0cbRRyWb8n8GuqaykPySI=T+0k4N0$E}pe0_p_ zr$r0N6=OcPRagr}SEiG`YF{Fbupq6I$C3QToW4{r2^YsJ z>cURM|TAdl&@9k`5J-jnyUb^Kj&Cmn& z<46m)N=hWP9V~o(=F-y4z|jQ%p^gAJE4zbN;0nE9!;cVzN;55+aU}IAlS7Bl8+J3; zPtFqw431bO&5wFQ9W3;*WcS&akjnc|_Ds;)_cZ*`va$H*u-3_t%y$l&#;@Er){oLP z)nbt~jb_>(oU}4F4>hS!0-;bcX%am;*@OO0y=3_FiSH!TrR&D<( zOF|w zB@v9N%>(vJZ#njB*1t&*O&5@9c>Z4WN3s(8R%_ff3?$Ec)}m&F51Q-=gyG|Db%TDf z;7|RQViL@he-5-KJ?t4;#@L(hU0SK0#p%FO#Z{Mt8t?}T8@J!cJgCpbWNDJ{JyFnI zJp+VNxNyVGHJ9Q@V(_tTavdl7LK%m$UO zG4Rwo(`%!*;?tWAhB)HmRjOM`&#nK{`{5A^9@QWA-3b^JoA%;|$aH20#+L<6<^@Np zfbBFjd=XMMF|h{Q26M{#rjwnR%(04cew^Xl&*f5u2yGe@IFbGf&BCf=|6UZ4o_N6Yrtx+G&hvTM_1FT1~lZ5ku8OAQ+&$3Qo`36P2-;~N&6ad>W9muh1L0X9O2Sw zm@nMSt3L`lKg4NX*x=D&Q)S3LrVoF6EOHGjl+xL>Y|r}ic;_c1%K83kh;@8Yvx+YZ z9?1Bo3qpP*UxWyEOGY=+^i4;IynQI|p4fEG4_sM#*OWVxm8!Tmw0EYcB|6}prXz03Z-(Qc4n9GrBmHejw Nn3IQNlf%XAKLM10x|9F_ literal 0 HcmV?d00001