Ad
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();
    • }

What about this one ????

:-)

OK for using iterators, but then.... use algorithm as well, no ? And... let the compiler optimize

Code
Diff
  • #include <algorithm>
    bool isBalanced(const std::string& s) {
      int count{};
      if (std::any_of(s.cbegin(),s.cend(),[&](auto c){
        count+=(c == '('?1:c == ')'?-1:0);
        return count<0;
      }))
        return false;
      
      return count==0;
    }
    • #include <algorithm>
    • bool isBalanced(const std::string& s) {
    • int count = 0;
    • int count{};
    • if (std::any_of(s.cbegin(),s.cend(),[&](auto c){
    • count+=(c == '('?1:c == ')'?-1:0);
    • return count<0;
    • }))
    • return false;
    • //using iterators seem to produce faster results
    • auto it = s.cbegin();
    • auto end = s.cend();
    • while (it != end) {
    • if (*it == '(')
    • count++; // can't exit early for (
    • else if ((*it== ')') && (--count < 0)) // short circuit booleans
    • return false; //exit early for mismatched )
    • it++;
    • }
    • return count == 0;
    • return count==0;
    • }
Code
Diff
  • bool isBalanced(const std::string& s) {
      int count = 0;
      for (const auto c: s) {
        if (count+= c=='(' ? +1: c==')'?-1:0; count <0)
          return false;
      }
      return count == 0;
    }
    • bool isBalanced(const std::string& s) {
    • int count = 0;
    • for (size_t i = 0; i < s.length(); i++) {
    • if (s[i] == '(') {
    • count++;
    • }
    • if (s[i] == ')') {
    • if (count <= 0) { return false; }
    • count--;
    • }
    • for (const auto c: s) {
    • if (count+= c=='(' ? +1: c==')'?-1:0; count <0)
    • return false;
    • }
    • return count == 0;
    • }

Assumes entry lists are sorted !!

Code
Diff
  • #include <list>
    
    auto merge_list(const std::list<int>& a, const std::list<int>& b) {
      std::list<int> o{a};
      for(auto i : b) o.insert(std::lower_bound(o.begin(), o.end(), i), i);
      return o;
    }
    • #include <algorithm>
    • #include <list>
    • #include <execution>
    • #include <iterator>
    • auto merge_list(const std::list<int>& a, const std::list<int>& b) {
    • std::list<int> o;
    • std::merge(
    • std::execution::seq,
    • a.begin(),
    • a.end(),
    • b.begin(),
    • b.end(),
    • std::back_inserter(o)
    • // std::less is default sort
    • );
    • std::list<int> o{a};
    • for(auto i : b) o.insert(std::lower_bound(o.begin(), o.end(), i), i);
    • return o;
    • }

Default sort comparator is std::less which is the one we want

Code
Diff
  • #include <algorithm>
    #include <list>
    #include <execution>
    #include <iterator>
    
    auto merge_list(const std::list<int>& a, const std::list<int>& b) {
      std::list<int> o;
      std::merge(
        std::execution::seq,
        a.begin(),
        a.end(),
        b.begin(),
        b.end(),
        std::back_inserter(o) 
        // std::less is default sort
      );
      return o;
    }
    • #include <algorithm>
    • #include <list>
    • #include <execution>
    • #include <iterator>
    • auto merge_list(const std::list<int>& a, const std::list<int>& b) {
    • std::list<int> o;
    • std::merge(
    • std::execution::seq,
    • a.begin(),
    • a.end(),
    • b.begin(),
    • b.end(),
    • std::back_insert_iterator<std::list<int>>(o),
    • [](const int a, const int b){
    • return a < b;
    • }
    • std::back_inserter(o)
    • // std::less is default sort
    • );
    • return o;
    • }

find a creative way to return .. THE MEANING OF LIFE

your function meaning_of_life_is() should return something to explain the meaning of life.

'something' can be a string, a char, an int, or any other stuff that we may push to output stream... to get the answer!!

Code
Diff
  • constexpr int fact(int n) {
        if (n < 2) return 1;
        return n * fact(n-1);
    }
    const int HOURS_IN_A_DAY      = 24;
    const int MINUTES_IN_AN_HOUR  = 60;
    const int SECONDS_IN_A_MINUTE = 60;
    constexpr int seconds_in_a_day() { return HOURS_IN_A_DAY * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE; };
    
    auto meaning_of_life_is() {
       return fact(10)/seconds_in_a_day();
    }
    • def meaning_of_life_is():
    • return """
    • go crazy with your imagination and return anything you like.
    • strings, numbers, ... just don't return None.
    • may the most creative answer win
    • """
    • constexpr int fact(int n) {
    • if (n < 2) return 1;
    • return n * fact(n-1);
    • }
    • const int HOURS_IN_A_DAY = 24;
    • const int MINUTES_IN_AN_HOUR = 60;
    • const int SECONDS_IN_A_MINUTE = 60;
    • constexpr int seconds_in_a_day() { return HOURS_IN_A_DAY * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE; };
    • auto meaning_of_life_is() {
    • return fact(10)/seconds_in_a_day();
    • }
Loading more items...