How to resolve the algorithm Balanced brackets step by step in the C++ programming language
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 integern
and two optional parametersleft
andright
that by default are[
and]
respectively. This function returns a string consisting ofn
copies of theleft
character followed byn
copies of theright
character. Then, it shuffles the elements of the string using thestd::random_shuffle
function. The resulting string is returned. -
The second function
balanced
takes a stringstr
, a left delimiterleft
and a right delimiterright
, which by default are[
and]
respectively. Returnstrue
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
to8
to generate 9 strings with an increasing number of characters, and for each one, it displays if the string is balanced or not using thebalanced
function above.
- It seeds the random number generator of the C++ standard library using the current time using
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