Exercise 7
Added Exercise 7 to Repository
This commit is contained in:
88
Informatik_I/Exercise_7/Task_2/README.org
Normal file
88
Informatik_I/Exercise_7/Task_2/README.org
Normal file
@@ -0,0 +1,88 @@
|
||||
#+title: Task 2: Bitstrings up to n
|
||||
|
||||
#+author: JirR02
|
||||
* Task
|
||||
:PROPERTIES:
|
||||
:CUSTOM_ID: task
|
||||
:END:
|
||||
Your task is implementing the function =all_bitstrings_up_to_n= in
|
||||
=solution.cpp= which generates all bitstrings up to length \(n\) in
|
||||
ascending order. The generated bitstrings are returned in a
|
||||
=std::vector<std::string>=.
|
||||
|
||||
*Note*: It is *mandatory* to use *recursive implementation* for this
|
||||
task.
|
||||
|
||||
* Input & Output
|
||||
:PROPERTIES:
|
||||
:CUSTOM_ID: input-output
|
||||
:END:
|
||||
The program first prompts you to enter the bitstring length \(n\). It
|
||||
then calls the function =all_bitstrings_up_to_n= and prints the returned
|
||||
bitstrings to the console.
|
||||
|
||||
** Example
|
||||
:PROPERTIES:
|
||||
:CUSTOM_ID: example
|
||||
:END:
|
||||
#+begin_src sh
|
||||
Bitstring length: 2
|
||||
Bitstrings up to length 2
|
||||
|
||||
0
|
||||
1
|
||||
00
|
||||
01
|
||||
10
|
||||
11
|
||||
#+end_src
|
||||
|
||||
*Note*: The empty line after Bitstrings up to length 2 is actually the
|
||||
bitstring of length \(0\).
|
||||
|
||||
*Note*: The autograder will only accept output that exactly matches the
|
||||
expected result. Therefore, do not output anything with =std::cout= in
|
||||
the =all_bitstrings_up_to_n= function. For debugging messages, use
|
||||
=std::cerr= as in:
|
||||
|
||||
#+begin_src cpp
|
||||
std::cerr << "This is a test message." << std::endl;
|
||||
#+end_src
|
||||
|
||||
Those will be ignored by the autograder.
|
||||
|
||||
* Solution
|
||||
:PROPERTIES:
|
||||
:CUSTOM_ID: solution
|
||||
:END:
|
||||
#+begin_src cpp
|
||||
#include "solution.h"
|
||||
using vec = std::vector<std::string>;
|
||||
using str = std::string;
|
||||
|
||||
void bitstring(vec &res, str ram, int l) {
|
||||
if (l == 0) {
|
||||
res.push_back(ram);
|
||||
return;
|
||||
}
|
||||
|
||||
bitstring(res, ram + "0", l - 1);
|
||||
bitstring(res, ram + "1", l - 1);
|
||||
}
|
||||
|
||||
void recursion(int count, int n, vec &res) {
|
||||
if (count > n)
|
||||
return;
|
||||
|
||||
bitstring(res, "", count);
|
||||
recursion(count + 1, n, res);
|
||||
}
|
||||
|
||||
vec all_bitstrings_up_to_n(int n) {
|
||||
vec res;
|
||||
|
||||
recursion(0, n, res);
|
||||
|
||||
return res;
|
||||
}
|
||||
#+end_src
|
Reference in New Issue
Block a user