How to resolve the algorithm Balanced brackets step by step in the C++ programming language

Published on 7 June 2024 03:52 AM

How to resolve the algorithm Balanced brackets step by step in the C++ programming language

Table of Contents

Problem Statement

Task:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Balanced brackets step by step in the C++ programming language

  • The first function generate takes an integer n and two optional parameters left and right that by default are [ and ] respectively. This function returns a string consisting of n copies of the left character followed by n copies of the right character. Then, it shuffles the elements of the string using the std::random_shuffle function. The resulting string is returned.

  • The second function balanced takes a string str, a left delimiter left and a right delimiter right, which by default are [ and ] respectively. Returns true if the string is balanced. A string is considered balanced if every left delimiter has a corresponding right delimiter, and every right delimiter has a corresponding left delimiter.

  • In the main function:

    • It seeds the random number generator of the C++ standard library using the current time using srand.
    • Then, it iterates from 0 to 8 to generate 9 strings with an increasing number of characters, and for each one, it displays if the string is balanced or not using the balanced function above.

Source code in the cpp programming language

#include <algorithm>
#include <iostream>
#include <string>

std::string generate(int n, char left = '[', char right = ']')
{
    std::string str(std::string(n, left) + std::string(n, right));
    std::random_shuffle(str.begin(), str.end());
    return str;
}

bool balanced(const std::string &str, char left = '[', char right = ']')
{
    int count = 0;
    for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
    {
        if (*it == left)
            count++;
        else if (*it == right)
            if (--count < 0) return false;
    }
    return count == 0;
}

int main()
{
    srand(time(NULL)); // seed rng
    for (int i = 0; i < 9; ++i)
    {
        std::string s(generate(i));
        std::cout << (balanced(s) ? " ok: " : "bad: ") << s << "\n";
    }
}


  

You may also check:How to resolve the algorithm Sierpinski triangle/Graphical step by step in the ATS programming language
You may also check:How to resolve the algorithm Bernoulli numbers step by step in the Go programming language
You may also check:How to resolve the algorithm Remove duplicate elements step by step in the Lasso programming language
You may also check:How to resolve the algorithm Factors of an integer step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm String case step by step in the Ursa programming language