Ad
Code
Diff
  • #include <random>
    
    std::uniform_real_distribution<long double> dis(0.,1.); // Default is double
    std::random_device rd;
    std::mt19937 gen(rd());
    
    long double pi_estimate(long long n, int seed=0) {
        gen.seed(seed);
        long long inside=0;
        for (auto i=0; i!=n; ++i) if (std::pow(dis(gen),2)+std::pow(dis(gen),2) < 1.) ++inside;
        return (4.*inside)/n; 
    }
    • import random
    • #include <random>
    • def pi_estimate(n, seed=0):
    • random.seed(seed)
    • n_inside = sum(True for i in range(n) if random.random()**2 + random.random()**2 < 1)
    • return 4 * (n_inside / n)
    • std::uniform_real_distribution<long double> dis(0.,1.); // Default is double
    • std::random_device rd;
    • std::mt19937 gen(rd());
    • long double pi_estimate(long long n, int seed=0) {
    • gen.seed(seed);
    • long long inside=0;
    • for (auto i=0; i!=n; ++i) if (std::pow(dis(gen),2)+std::pow(dis(gen),2) < 1.) ++inside;
    • return (4.*inside)/n;
    • }

Description is not accurate: if you pass by value, you cannot return both a bool (whether the vector is ordered or not) and a sorted vector ????

Code
Diff
  • #include <vector>
    #include <algorithm>
    #include <utility>
    
    bool Ordering(const std::vector<int> &num) {
      if (num.size()<=1) return true;
      return std::none_of(std::next(num.cbegin()),num.end(),
                          [prev=num[0]](int val) mutable {
                            return val<std::exchange(prev,val);
                          });
    }
    • using namespace std;
    • int Ordering(vector<int> num) //1,0,3
    • {
    • vector <int> result;
    • for(int i = 0 ; i < num.size() ; i++)
    • {
    • sort(num.begin() , num.end());
    • result.push_back(num[i]);
    • }
    • return result;
    • }
    • #include <vector>
    • #include <algorithm>
    • #include <utility>
    • bool Ordering(const std::vector<int> &num) {
    • if (num.size()<=1) return true;
    • return std::none_of(std::next(num.cbegin()),num.end(),
    • [prev=num[0]](int val) mutable {
    • return val<std::exchange(prev,val);
    • });
    • }
Code
Diff
  • #include <string>
    #include <string_view>
    #include <vector>
    #include <numeric>
    
    std::string Jointup(const std::vector<std::string> &name , const std::string_view delim = " , "){
      if (name.empty()) return "";
      return std::accumulate(std::next(name.begin()),name.end(),
                             name.front(),
                             [&](auto &s, auto &n){return s.append(delim).append(n);});
    }
    • using namespace std;
    • string Jointup(vector<string> name , char symbol = ", "){
    • string result;
    • for(int i = 0 ; i < name.size() ; i++ )
    • {
    • result += name[i];
    • if(i != name.size() - 1)
    • {
    • result+= symbol;
    • }
    • }
    • return result;
    • #include <string>
    • #include <string_view>
    • #include <vector>
    • #include <numeric>
    • std::string Jointup(const std::vector<std::string> &name , const std::string_view delim = " , "){
    • if (name.empty()) return "";
    • return std::accumulate(std::next(name.begin()),name.end(),
    • name.front(),
    • [&](auto &s, auto &n){return s.append(delim).append(n);});
    • }

Prefer to remove the 'using std::' stuff

generateRandomNumber: Should not initialize rd and mtt etc... for each generation call => make it static. Same with the base string

hasDuplicateDigits: using bitset instead of std::vector<bool> ... avoid like to allocate on a simple test. And use accumulate ?

isNumeric: prefer to use '::isdigit' in std::all_of (defined in <cctype>). Uses locale, but who cares ??

checkGuess: std::pair is defined in <utility>; and prefer to directly initialize the return structure with a binding if one likes...

acceptGuess :
made a default max counter of attempts
reworked the main loop (do{ ..... } while ()); note an invalid attempt is an attempt so one should increment the #attempts anyway

.. and last : use fmt/format (or std::format in C++20), with predefined messages out of the code lines, for further translation

Code
Diff
  • #include <fmt/format.h>
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    #include <vector>
    #include <bitset>
    #include <algorithm>
    #include <cmath>
    #include <cctype>
    #include <random>
    
    
    static const std::string msgs[]={
      "Enter your guess (a 4-digit number with non-repeating digits): ",
      "Correct numbers: {} Correct position: {}",
      "Congratulations! You guessed the number {} correctly in {} attempts!",
      "Oups.. You could not guess the number in {} attempts!",
      "Invalid input. Please enter a 4-digit number with non-repeating digits."
    };
    
    // Initialize random number generator outside functions
    static std::random_device rd;  // Obtain a random number from hardware
    static std::mt19937 g(rd());   // Seed the generator
    
    std::string generateRandomNumber() {
        static std::string base{"0123456789"}; 
    
        // Shuffle digits
        std::shuffle(base.begin(), base.end(), g);
    
        // Return the first 4 digits as a string
        return base.substr(0,4);
    }
    
    bool hasDuplicateDigits(const std::string &number) {
        return std::accumulate(number.cbegin(),number.cend(), std::bitset<10>{0},
                             [](auto &bs,auto c) {return bs.set(c-'0');}
                             ).count()!=number.size();
    }
    
    bool isNumeric(const std::string &s) {
        return std::all_of(s.begin(), s.end(), ::isdigit);
    }
    
    std::string getUserGuess(std::istream &in = std::cin, std::ostream &out = std::cout) {
        std::string guess;
        out << msgs[0];
        in >> guess;
        return guess;
    }
    
    std::pair<int, int> checkGuess(const std::string &randomNumber, const std::string &userGuess) {
        std::pair<int, int> ret {0,0};
      
        for (int i = 0; i < 4; ++i) {
            if (randomNumber[i] == userGuess[i]) {
                ++std::get<0>(ret), ++std::get<1>(ret);
            } else if (std::count(randomNumber.begin(), randomNumber.end(), userGuess[i])) {
                ++std::get<0>(ret);
            }
        }
    
        return ret;
    }
    
    int acceptGuess(const std::string &expected, std::istream &in = std::cin, std::ostream &out = std::cout, int maxattempts=20) {
        int attempts = 0;
        std::pair status{0,0};
        do {
            std::string userGuess = getUserGuess(in, out);
            if (userGuess.length() != 4 || hasDuplicateDigits(userGuess) || !isNumeric(userGuess)) {
                out << msgs[4] << std::endl;
            } else {
              status = checkGuess(expected, userGuess);
              out << fmt::format(msgs[1],status.first,status.second) << std::endl;
            }
            attempts++;
        } while (status.second!=4 && attempts<maxattempts);
        
        if (attempts==maxattempts)
           out << fmt::format(msgs[3],attempts)<< std::endl;
        else 
           out << fmt::format(msgs[2],expected,attempts)<< std::endl;
        return attempts;
    }
    
    int _main(std::istream &in = std::cin, std::ostream &out = std::cout) {
        // Seed rand since random_shuffle _probably_ uses it.
        srand(static_cast<unsigned>(time(0)));
        std::string randomNumber = generateRandomNumber();
        acceptGuess(randomNumber, in, out);
        return 0;
    }
    
    • #include <fmt/format.h>
    • #include <iostream>
    • #include <cstdlib>
    • #include <ctime>
    • #include <vector>
    • #include <bitset>
    • #include <algorithm>
    • #include <cmath>
    • #include <cctype>
    • #include <random>
    • using std::cin;
    • using std::cout;
    • using std::endl;
    • using std::istream;
    • using std::make_pair;
    • using std::mt19937;
    • using std::ostream;
    • using std::pair;
    • using std::random_device;
    • using std::string;
    • using std::vector;
    • string generateRandomNumber() {
    • vector<char> digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    • // Initialize random number generator
    • random_device rd; // Obtain a random number from hardware
    • mt19937 g(rd()); // Seed the generator
    • static const std::string msgs[]={
    • "Enter your guess (a 4-digit number with non-repeating digits): ",
    • "Correct numbers: {} Correct position: {}",
    • "Congratulations! You guessed the number {} correctly in {} attempts!",
    • "Oups.. You could not guess the number in {} attempts!",
    • "Invalid input. Please enter a 4-digit number with non-repeating digits."
    • };
    • // Initialize random number generator outside functions
    • static std::random_device rd; // Obtain a random number from hardware
    • static std::mt19937 g(rd()); // Seed the generator
    • std::string generateRandomNumber() {
    • static std::string base{"0123456789"};
    • // Shuffle digits
    • shuffle(digits.begin(), digits.end(), g);
    • std::shuffle(base.begin(), base.end(), g);
    • // Return the first 4 digits as a string
    • return string(digits.begin(), digits.begin() + 4);
    • return base.substr(0,4);
    • }
    • bool hasDuplicateDigits(const string &number) {
    • vector<bool> seen(10, false);
    • for (const auto c : number) {
    • if (seen[c - '0']) return true;
    • seen[c - '0'] = true;
    • }
    • return false;
    • bool hasDuplicateDigits(const std::string &number) {
    • return std::accumulate(number.cbegin(),number.cend(), std::bitset<10>{0},
    • [](auto &bs,auto c) {return bs.set(c-'0');}
    • ).count()!=number.size();
    • }
    • bool isNumeric(const string &s) {
    • return all_of(s.begin(), s.end(), [](char c){ return isdigit(c); });
    • bool isNumeric(const std::string &s) {
    • return std::all_of(s.begin(), s.end(), ::isdigit);
    • }
    • string getUserGuess(istream &in = cin, ostream &out = cout) {
    • string guess;
    • out << "Enter your guess (a 4-digit number with non-repeating digits): ";
    • std::string getUserGuess(std::istream &in = std::cin, std::ostream &out = std::cout) {
    • std::string guess;
    • out << msgs[0];
    • in >> guess;
    • return guess;
    • }
    • pair<int, int> checkGuess(const string &randomNumber, const string &userGuess) {
    • int correctNumbers = 0;
    • int correctPosition = 0;
    • std::pair<int, int> checkGuess(const std::string &randomNumber, const std::string &userGuess) {
    • std::pair<int, int> ret {0,0};
    • for (int i = 0; i < 4; ++i) {
    • if (randomNumber[i] == userGuess[i]) {
    • correctNumbers++;
    • correctPosition++;
    • } else if (count(randomNumber.begin(), randomNumber.end(), userGuess[i])) {
    • correctNumbers++;
    • ++std::get<0>(ret), ++std::get<1>(ret);
    • } else if (std::count(randomNumber.begin(), randomNumber.end(), userGuess[i])) {
    • ++std::get<0>(ret);
    • }
    • }
    • return make_pair(correctNumbers, correctPosition);
    • return ret;
    • }
    • int acceptGuess(const string &expected, istream &in = cin, ostream &out = cout) {
    • int acceptGuess(const std::string &expected, std::istream &in = std::cin, std::ostream &out = std::cout, int maxattempts=20) {
    • int attempts = 0;
    • while (true) {
    • string userGuess = getUserGuess(in, out);
    • std::pair status{0,0};
    • do {
    • std::string userGuess = getUserGuess(in, out);
    • if (userGuess.length() != 4 || hasDuplicateDigits(userGuess) || !isNumeric(userGuess)) {
    • out << "Invalid input. Please enter a 4-digit number with non-repeating digits." << endl;
    • continue;
    • out << msgs[4] << std::endl;
    • } else {
    • status = checkGuess(expected, userGuess);
    • out << fmt::format(msgs[1],status.first,status.second) << std::endl;
    • }
    • auto [corNum, corPos] = checkGuess(expected, userGuess);
    • out << "Correct numbers: " << corNum << " Correct position: " << corPos << endl;
    • attempts++;
    • if (corPos == 4) {
    • out << "Congratulations! You guessed the number " << expected << " correctly in " << attempts << " attempts!" << endl;
    • break;
    • }
    • }
    • } while (status.second!=4 && attempts<maxattempts);
    • if (attempts==maxattempts)
    • out << fmt::format(msgs[3],attempts)<< std::endl;
    • else
    • out << fmt::format(msgs[2],expected,attempts)<< std::endl;
    • return attempts;
    • }
    • int _main(istream &in = cin, ostream &out = cout) {
    • int _main(std::istream &in = std::cin, std::ostream &out = std::cout) {
    • // Seed rand since random_shuffle _probably_ uses it.
    • srand(static_cast<unsigned>(time(0)));
    • string randomNumber = generateRandomNumber();
    • std::string randomNumber = generateRandomNumber();
    • acceptGuess(randomNumber, in, out);
    • return 0;
    • }

Actuallly ... accumulates returns... what you specify ??

Code
Diff
  • #include <vector>
    #include <numeric>
    
    template <typename T> using add_t=decltype(T() + T());
    
    template <typename T = double>
    add_t<T> sum(const std::vector<T>& v) {
      return std::accumulate(v.cbegin(),v.cend(),add_t<T>{0});
    }
    • #include <vector>
    • #include <numeric>
    • template <typename T> using add_t=decltype(T() + T());
    • template <typename T = double>
    • decltype(T() + T()) sum(const std::vector<T>& v) {
    • decltype(T() + T()) res = 0;
    • for (const T &num : v) res += num;
    • return res;
    • add_t<T> sum(const std::vector<T>& v) {
    • return std::accumulate(v.cbegin(),v.cend(),add_t<T>{0});
    • }
Code
Diff
  • #include <vector>
    #include <numeric>
    std::vector<int> gradient(const std::vector<int> &v) {
      std::vector<int> dv(v.size());
      std::adjacent_difference(v.cbegin(),v.cend(),dv.begin());
      dv.erase(dv.begin());
      return dv;
    }
    • #include <vector>
    • #include <numeric>
    • std::vector<int> gradient(const std::vector<int> &v) {
    • std::vector<int> dv;
    • for (int i = 1; i < int(v.size()); i++)
    • dv.push_back(v[i]-v[i-1]);
    • std::vector<int> dv(v.size());
    • std::adjacent_difference(v.cbegin(),v.cend(),dv.begin());
    • dv.erase(dv.begin());
    • return dv;
    • }
Fundamentals
Strings
Code
Diff
  • #include <string>
    #include <numeric>
    std::string digest(const std::string& param) {
        return param.empty()? 
                   param
                 : std::accumulate(std::next(param.cbegin()),param.cend(),
                                   std::string(1,param[0]),
                                   [](auto &s, auto c) {return s.append(" ").append(1,c);});
    }
    • #include <string>
    • #include <fmt/ranges.h>
    • using namespace std;
    • string digest(const string& param) {
    • string ans = "";
    • if(param == "") {
    • return ans;
    • }
    • if(param[0] == ' ') {
    • ans = " ";
    • } else {
    • ans = param.substr(0, 1);
    • }
    • for(int i = 1; i < param.length(); i++) {
    • if(param[i] == ' ') {
    • ans += " ";
    • } else {
    • ans += " " + param.substr(i, 1);
    • }
    • }
    • return ans;
    • #include <numeric>
    • std::string digest(const std::string& param) {
    • return param.empty()?
    • param
    • : std::accumulate(std::next(param.cbegin()),param.cend(),
    • std::string(1,param[0]),
    • [](auto &s, auto c) {return s.append(" ").append(1,c);});
    • }
Code
Diff
  • #include <numeric>
    #include <stdint.h>
    #include <vector>
    #include <range/v3/numeric/accumulate.hpp>
    
    int64_t add_arr(const std::vector<int32_t> &arr) {
      return ranges::accumulate(arr, (int64_t)0);
    }
    • #include<numeric>
    • #include<stdint.h>
    • #include<vector>
    • #include <numeric>
    • #include <stdint.h>
    • #include <vector>
    • #include <range/v3/numeric/accumulate.hpp>
    • int64_t add_arr(const std::vector<int32_t> &arr) {
    • return std::reduce(arr.cbegin(), arr.cend(), 0);
    • return ranges::accumulate(arr, (int64_t)0);
    • }
Code
Diff
  • #include <string>
    #include <algorithm>
    
    class Password{
        public:
            static bool atLeastOneOf(const std::string& pw,std::string_view sv);
            static bool testPassword(const std::string& password);
    };
    bool Password::atLeastOneOf(const std::string& pw,std::string_view sv) {
      return std::any_of(pw.begin(),pw.end(),[&](char c){return sv.find(c)!=sv.npos;});
    }
    
    bool Password::testPassword(const std::string& password) {
      return password.size()>7
        &&   atLeastOneOf(password,"ABCDEFGHIJKLMNOPQRSTUVWXZ")
        &&   atLeastOneOf(password,"0123456789")
        &&   atLeastOneOf(password,"!\"#$%&'()*+'-./;:<>=?");
      
    //  return cap && spec && digit && number;
    }
    • #include <string>
    • #include <algorithm>
    • class Password{
    • public:
    • static bool hasCap(const std::string& password);
    • static bool hasSpec(const std::string& password);
    • static bool hasDigit(const std::string& password);
    • static bool hasLength(const std::string& password);
    • static bool atLeastOneOf(const std::string& pw,std::string_view sv);
    • static bool testPassword(const std::string& password);
    • };
    • bool Password::hasCap(const std::string& password)
    • {
    • bool result = false;
    • for(auto symbol : password)
    • {
    • if(symbol >= 'A' && symbol <= 'Z')
    • {
    • result = true;
    • break;
    • }
    • }
    • return result;
    • }
    • bool Password::hasSpec(const std::string& password)
    • {
    • bool result = false;
    • const std::string specials("!\"#$%&'()*+'-./;:<>=?");
    • for(auto spec : specials)
    • {
    • if(password.find(spec) != -1)
    • {
    • result = true;
    • break;
    • }
    • }
    • return result;
    • }
    • bool Password::hasDigit(const std::string& password)
    • {
    • bool result = false;
    • for(auto symbol : password)
    • {
    • if(symbol >= '0' && symbol <= '9')
    • {
    • result = true;
    • break;
    • }
    • }
    • return result;
    • }
    • bool Password::hasLength(const std::string& password)
    • {
    • return password.length() > 7;
    • bool Password::atLeastOneOf(const std::string& pw,std::string_view sv) {
    • return std::any_of(pw.begin(),pw.end(),[&](char c){return sv.find(c)!=sv.npos;});
    • }
    • bool Password::testPassword(const std::string& password)
    • {
    • bool cap = Password::hasCap(password);
    • bool spec = Password::hasSpec(password);
    • bool digit = Password::hasDigit(password);
    • bool number = Password::hasLength(password);
    • bool Password::testPassword(const std::string& password) {
    • return password.size()>7
    • && atLeastOneOf(password,"ABCDEFGHIJKLMNOPQRSTUVWXZ")
    • && atLeastOneOf(password,"0123456789")
    • && atLeastOneOf(password,"!\"#$%&'()*+'-./;:<>=?");
    • return cap && spec && digit && number;
    • // return cap && spec && digit && number;
    • }
Code
Diff
  • void timeOut(){for(;;);}
    • void timeOut(){for(;;){}}
    • void timeOut(){for(;;);}
Fundamentals
Strings
Code
Diff
  • #include <string>
    #include <numeric>
    
    auto digest(const std::string& param) {
      if (param.empty()) return param; // Oh... should check there !!
      return std::accumulate(std::next(param.cbegin()),param.cend(),
                             std::string(1,param[0]), // Char initializer
                             [](auto &s, auto c) {
                               return s+std::string{{' ',c}}; // initializer_list string initializer
                             });
    }
    • std::string digest(const std::string& param) {
    • std::string result;
    • result.reserve(param.size() * 2); // Ensure exactly one memory allocation
    • for (char letter: param) {
    • result.push_back(letter);
    • result.push_back(' ');
    • }
    • result.pop_back();
    • return result;
    • #include <string>
    • #include <numeric>
    • auto digest(const std::string& param) {
    • if (param.empty()) return param; // Oh... should check there !!
    • return std::accumulate(std::next(param.cbegin()),param.cend(),
    • std::string(1,param[0]), // Char initializer
    • [](auto &s, auto c) {
    • return s+std::string{{' ',c}}; // initializer_list string initializer
    • });
    • }

Just wanted to try & test this one :-)

Code
Diff
  • #include <string>
    #include <array>
    #include <stdexcept>
    
    template <typename T>
    std::string calculator(int op, T x, T y) {
      try {
    
        std::array<std::function<T(T, T)>,5> ops{{
          std::plus<>{},
          std::minus<>{},
          std::multiplies<>{},
          [&](T x, T y) {if (y!=0) return x/y; else throw std::range_error{"Illegal divide by 0"};},
          [&](T x, T y) {if (y!=0) return x%y; else throw std::range_error{"Illegal modulus % 0"};},
        }};
      
        return std::to_string(ops.at(op-1)(x,y)); // 'at()' will throw !!
          
      } catch (const std::out_of_range& e) {
        return "Invalid Input!";
      } catch (const std::range_error& e) {
        return "Invalid Input!";
      }
    }
    
    • #include <functional>
    • #include <string>
    • #include <array>
    • using namespace std;
    • #include <stdexcept>
    • template <typename T>
    • string calculator(int op, T x, T y) {
    • static array<std::function<T(T, T)>,5> ops{
    • plus<>{},minus<>{},multiplies<>{},divides<>{},modulus<>{},
    • };
    • static array<std::function<string()>, 2> func{
    • [&]() {return to_string(ops[op-1](x, y));},
    • [&]() {return "Invalid Input!";},
    • };
    • std::string calculator(int op, T x, T y) {
    • try {
    • return (op < 1 || op > 5 || (!y && (op == 4 || op == 5))) ? func[1]() : func[0]();
    • std::array<std::function<T(T, T)>,5> ops{{
    • std::plus<>{},
    • std::minus<>{},
    • std::multiplies<>{},
    • [&](T x, T y) {if (y!=0) return x/y; else throw std::range_error{"Illegal divide by 0"};},
    • [&](T x, T y) {if (y!=0) return x%y; else throw std::range_error{"Illegal modulus % 0"};},
    • }};
    • return std::to_string(ops.at(op-1)(x,y)); // 'at()' will throw !!
    • } catch (const std::out_of_range& e) {
    • return "Invalid Input!";
    • } catch (const std::range_error& e) {
    • return "Invalid Input!";
    • }
    • }
Code
Diff
  • #include <functional>
    #include <string>
    #include <array>
    using namespace std;
    
    template <typename T>
    string calculator(int op, T x, T y) {
      static array<std::function<T(T, T)>,5> ops{
        plus<>{},minus<>{},multiplies<>{},divides<>{},modulus<>{},
      };
      static array<std::function<std::string()>, 2> func{
        [&]() {return std::to_string(ops[op-1](x, y));},
        [&]() {return "Invalid Input!";},
      };
      
      return func[op < 1 || op > 5 || (!y && (op == 4 || op == 5))]();
    }
    • #include <functional>
    • #include <string>
    • #include <array>
    • using namespace std;
    • string calculator(int op, int x, int y) {
    • static array<std::function<int(int, int)>, 5> ops{
    • plus<int>(),
    • minus<int>(),
    • multiplies<int>(),
    • divides<int>(),
    • modulus<int>(),
    • template <typename T>
    • string calculator(int op, T x, T y) {
    • static array<std::function<T(T, T)>,5> ops{
    • plus<>{},minus<>{},multiplies<>{},divides<>{},modulus<>{},
    • };
    • if (op < 1 || op > 5 || (!y && (op == 4 || op == 5))) return "Invalid Input!";
    • return std::to_string(ops[op-1](x, y));
    • static array<std::function<std::string()>, 2> func{
    • [&]() {return std::to_string(ops[op-1](x, y));},
    • [&]() {return "Invalid Input!";},
    • };
    • return func[op < 1 || op > 5 || (!y && (op == 4 || op == 5))]();
    • }

IMHO it is strange to return true or false depending on a 'bool' condition

Code
Diff
  • using System;
    
    public class LeapYears
    {
      public static bool IsLeapYear(int year)
      {
        return year % 4 == 0 && !(year%100==0 && year % 400 != 0);
      }
    }
    • using System;
    • public class LeapYears
    • {
    • public static bool IsLeapYear(int year)
    • {
    • // End of a century must be divisible by 400
    • if(year%100==0)
    • return year % 400 == 0;// Returns true if year divisible by 400, false otherwise
    • else if(year % 4 == 0)
    • return true;// Returns true if year divisible by 4 and not end of the century
    • else
    • return false;
    • return year % 4 == 0 && !(year%100==0 && year % 400 != 0);
    • }
    • }

Guess you could like this one too...

Code
Diff
  • #include <algorithm>
    struct ParenAccumulator{
      int count{};
      bool operator()(const char c) {
        count+=(c == '('?1:c == ')'?-1:0);
        return count<0; 
      }
      bool isBalanced() const {return count==0;}
    };
    bool isBalanced(const std::string& s) {
      ParenAccumulator par;
      return std::none_of(s.cbegin(),s.cend(),std::ref(par)) 
          && par.isBalanced(); 
    }
    • #include <algorithm>
    • bool isBalanced(const std::string& s) {
    • struct ParenAccumulator{
    • int count{};
    • if (std::any_of(s.cbegin(),s.cend(),[&](auto c){
    • bool operator()(const char c) {
    • count+=(c == '('?1:c == ')'?-1:0);
    • return count<0;
    • }))
    • return false;
    • return count==0;
    • return count<0;
    • }
    • bool isBalanced() const {return count==0;}
    • };
    • bool isBalanced(const std::string& s) {
    • ParenAccumulator par;
    • return std::none_of(s.cbegin(),s.cend(),std::ref(par))
    • && par.isBalanced();
    • }
Loading more items...