JirR02 c6b006c2a1 Exercise 7
Added Exercise 7 to the repository
2025-04-07 08:43:53 +02:00
..
2025-04-07 08:43:53 +02:00

Task 2: Bitstrings up to n

Task

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

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

Bitstring length: 2
Bitstrings up to length 2

0
1
00
01
10
11

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:

std::cerr << "This is a test message." << std::endl;

Those will be ignored by the autograder.

Solution

#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;
}