user2896120 user2896120 - 1 month ago 15
C++ Question

Printing section numbers using recursion

I have a function

void numbers(ostream& outs, const string& prefix, unsigned int levels);
that prints output to the ostream outs.

The output consists of the string prefix followed by "section numbers" of the form 1.1., 1.2., 1.3., and so on. The levels argument determines how may levels the section numbers have. For example, if levels is 2, then the section numbers have the form x.y. If levels is 3, then section numbers have the form x.y.z. The digits permitted in each level are always '1' through '9'. As an example, if prefix is the string "THERBLIG" and levels is 2, then the function would start by printing:


THERBLIG1.1.

THERBLIG1.2.

THERBLIG1.3.

and end by printing:

THERBLIG9.7.

THERBLIG9.8.

THERBLIG9.9.


The stopping case occurs when levels reaches zero (in which case the prefix is printed once by itself followed by nothing else).

My current code correctly prints out all the sections when level is 2, but when level is 3 it does not. How do I make my code more dynamic and universal so that it can take in any number as levels? (When levels is 3, the output should be 1.1.1, 1.1.2, 1.1.3....1.2.1..).

Here's my code:

void numbers(ostream& outs, const string& prefix, unsigned int levels){
if (levels > 1){

for (int i = 1; i <= 9; i++){
for (int k = 1; k <= 9; k++){
string s = prefix + char('0' + i);
s += '.';
s += char('0' + k);
s += '.';
outs<<s<<endl;
}

}
numbers(outs, prefix, levels - 1);
}

else{
levels = 0;
if (levels == 0){
cout<<prefix<<endl;
}
}
}

Answer

My suggestion using backtracking:

#include <iostream>
#include <string>
using namespace std;

void numbers(ostream& outs, const string& prefix, unsigned int levels){

    if (levels == 0) {
        outs << prefix << endl;
        return;
    }

   for (int i = 1; i <= 9; i++){
        string dot = (levels == 1 ? "" : "."); //handle the case the lowest level
        string s = prefix +  std::to_string(i) + dot;
        numbers(outs, s, levels - 1);
   }
}

int main() {
    int level = 3;
    numbers(cout, "", level);
    return 0;
}
Comments