Ad
Metaprogramming
  • added compile-time template
  • added random test for runtime function
  • replaced x * 2 with x << 1
Code
Diff
  • constexpr int doubleValue(int x) {
        return x << 1;
    }
    
    template<int x> struct Double {
      static constexpr int value = (x << 1);
    };
    • #include<iostream>
    • int doubleValue(int x) {
    • return x * 2;
    • constexpr int doubleValue(int x) {
    • return x << 1;
    • }
    • template<int x> struct Double {
    • static constexpr int value = (x << 1);
    • };

Trying to guess what the author meant

Code
Diff
  • function rgbToHsv(rgb) {
      let r = rgb[0], g = rgb[1], b = rgb[2];
      const v = Math.max(r, g, b) / 255;
      if (v == 0) return Array.of(0, 0, 0);
      r /= v;
      g /= v;
      b /= v;
      const s = 1 - Math.min(r, g, b) / 255;
      if (s == 0) return Array.of(0, 0, v * 100);
      r = 255 - (255 - r) / s;
      g = 255 - (255 - g) / s;
      b = 255 - (255 - b) / s;
      const peak = Math.max(r, g, b);
      let h = 0;
      if (r == peak) h = g < b ? 360 - b * 60 / 255 : g * 60 / 255;
      else if (g == peak) h = r > b ? 120 - r * 60 / 255 : 120 + b * 60 / 255;
      else h = r > g ? 240 + r * 60 / 255 : 240 - g * 60 / 255;
      return Array.of(Math.round(h), Math.round(s * 100), Math.round(v * 100));
    }
    • describe("Solution", function() {
    • it("should test for something", function() {
    • });
    • });
    • function rgbToHsv(rgb) {
    • let r = rgb[0], g = rgb[1], b = rgb[2];
    • const v = Math.max(r, g, b) / 255;
    • if (v == 0) return Array.of(0, 0, 0);
    • r /= v;
    • g /= v;
    • b /= v;
    • const s = 1 - Math.min(r, g, b) / 255;
    • if (s == 0) return Array.of(0, 0, v * 100);
    • r = 255 - (255 - r) / s;
    • g = 255 - (255 - g) / s;
    • b = 255 - (255 - b) / s;
    • const peak = Math.max(r, g, b);
    • let h = 0;
    • if (r == peak) h = g < b ? 360 - b * 60 / 255 : g * 60 / 255;
    • else if (g == peak) h = r > b ? 120 - r * 60 / 255 : 120 + b * 60 / 255;
    • else h = r > g ? 240 + r * 60 / 255 : 240 - g * 60 / 255;
    • return Array.of(Math.round(h), Math.round(s * 100), Math.round(v * 100));
    • }

Even shorter

Code
Diff
  • bool Or(bool a, bool b) {return a+b;}
    bool And(bool a, bool b) {return a*b;}
    bool Xor(bool a, bool b) {return a!=b;}
    bool Nor(bool a, bool b) {return !a*!b;}
    bool Nand(bool a, bool b) {return 1-a*b;}
    • bool Or(bool a, bool b) {
    • return a+b;
    • }
    • bool And(bool a, bool b) {
    • return a*b;
    • }
    • bool Xor(bool a, bool b) {
    • return a!=b;
    • }
    • bool Nor(bool a, bool b) {
    • return !(a+b);
    • }
    • bool Nand(bool a, bool b) {
    • return !(a*b);
    • }
    • bool Or(bool a, bool b) {return a+b;}
    • bool And(bool a, bool b) {return a*b;}
    • bool Xor(bool a, bool b) {return a!=b;}
    • bool Nor(bool a, bool b) {return !a*!b;}
    • bool Nand(bool a, bool b) {return 1-a*b;}

Some creative code

Code
Diff
  • #include <iostream>
    using namespace std;     
    int _main() {
      setlocale (LC_ALL, "RUS");
      int a=1, b=2, c=3, d=4, e=5;
      int result_int_1=(a+b+c+d+e)/5;
      int result_int_2=(1+2+3+4+5)/5;
      int result_int_3=15/5;
      int result_int_4=3;
      bool equal_1_2 = result_int_1 == result_int_2;
      bool equal_2_3 = result_int_1 == result_int_2;
      bool equal_3_4 = result_int_1 == result_int_2;
      cout << equal_1_2 << ' ' << equal_2_3 << ' ' << equal_3_4 << endl;
      if (equal_1_2 && equal_2_3 && equal_3_4) cout << "All results are same." << endl;
      return 0;
    }
    • #include <instream>
    • #include <iostream>
    • using namespace std;
    • int main()}
    • setlocale (LC ALL, "RUS")
    • int a=1 b=2 c=3 d=4 e=5
    • int result_int=(a+b+c+d+e)/5
    • int result_int=(1+2+3+4+5)/5
    • int result_int=15/5
    • int resulr_int=
    • int _main() {
    • setlocale (LC_ALL, "RUS");
    • int a=1, b=2, c=3, d=4, e=5;
    • int result_int_1=(a+b+c+d+e)/5;
    • int result_int_2=(1+2+3+4+5)/5;
    • int result_int_3=15/5;
    • int result_int_4=3;
    • bool equal_1_2 = result_int_1 == result_int_2;
    • bool equal_2_3 = result_int_1 == result_int_2;
    • bool equal_3_4 = result_int_1 == result_int_2;
    • cout << equal_1_2 << ' ' << equal_2_3 << ' ' << equal_3_4 << endl;
    • if (equal_1_2 && equal_2_3 && equal_3_4) cout << "All results are same." << endl;
    • return 0;
    • }
  • fixed return in Calculator()
  • division by zero in faiDivisione() now causes exception which is caught in Calculator()
  • grouped tests into Valid_Input_Test and Invalid_Input_Test
Code
Diff
  • #include <iostream>
    using namespace std;
    
    int faiAddizione(int x, int y);
    int faiSottrazione(int x, int y);
    int faiMoltiplicazione(int x, int y);
    int faiDivisione(int x, int y);
    int faiModulus(int x, int y);  
    
    
    string die() {
      return "Invalid Input!";
    }
    
    string Calculator(int choice, int x, int y) {
      cout << "Welcome to simple calculator!\n";
      cout << "1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Modulus\n";
      string res;
      try {
        switch (choice) {
            case 1 : res = to_string(faiAddizione(x, y)); break;
            case 2 : res = to_string(faiSottrazione(x, y)); break;
            case 3 : res = to_string(faiMoltiplicazione(x, y)); break;
            case 4 : res = to_string(faiDivisione(x, y)); break;
            case 5 : res = to_string(faiModulus(x, y)); break;
            default : res = die();
        }
      } catch (const exception &e) {
        res = die();
      }
      cout << res << endl;
      return res;
    }  
    
    int faiAddizione(int x, int y) {
      return x + y;
    }
    
    int faiSottrazione(int x, int y) {
      return x - y;
    }
    
    int faiDivisione(int x, int y) {
      if (y == 0) throw invalid_argument("Division by zero");
      return x / y;
    }
    
    int faiMoltiplicazione(int x, int y) {
      return x * y; 
    }
    
    int faiModulus(int x, int y) {
      return x % y;
    }
    
    • #include <iostream>
    • using namespace std;
    • int faiAddizione(int x, int y);
    • int faiSottrazione(int x, int y);
    • int faiMoltiplicazione(int x, int y);
    • int faiDivisione(int x, int y);
    • int faiModulus(int x, int y);
    • string die() {
    • return "Invalid Input!";
    • }
    • string Calculator(int choice, int x, int y) {
    • cout << "Welcome to simple calculator!
    • ";
    • cout << "1. Addition
    • 2. Subtraction
    • 3. Multiplication
    • 4. Division
    • 5. Modulus
    • ";
    • // YOU: Write code to finish this program (Input is given, don't use cin)
    • switch(choice){
    • case 1 : cout << faiAddizione(x, y);
    • break;
    • case 2 : cout << faiSottrazione(x, y);
    • break;
    • case 3 : cout << faiMoltiplicazione(x, y);
    • break;
    • case 4 : cout << faiDivisione(x, y);
    • break;
    • case 5 : cout << faiModulus(x,y);
    • break;
    • default : return die();
    • break;
    • cout << "Welcome to simple calculator!
    • ";
    • cout << "1. Addition
    • 2. Subtraction
    • 3. Multiplication
    • 4. Division
    • 5. Modulus
    • ";
    • string res;
    • try {
    • switch (choice) {
    • case 1 : res = to_string(faiAddizione(x, y)); break;
    • case 2 : res = to_string(faiSottrazione(x, y)); break;
    • case 3 : res = to_string(faiMoltiplicazione(x, y)); break;
    • case 4 : res = to_string(faiDivisione(x, y)); break;
    • case 5 : res = to_string(faiModulus(x, y)); break;
    • default : res = die();
    • }
    • } catch (const exception &e) {
    • res = die();
    • }
    • cout << res << endl;
    • return res;
    • }
    • int faiAddizione(int x, int y)
    • { return (x + y);
    • int faiAddizione(int x, int y) {
    • return x + y;
    • }
    • int faiSottrazione(int x, int y){
    • return (x - y);
    • int faiSottrazione(int x, int y) {
    • return x - y;
    • }
    • int faiDivisione(int x, int y){
    • if(y != 0){
    • return (x/y);
    • }
    • else
    • {
    • die();
    • return 0;
    • }
    • int faiDivisione(int x, int y) {
    • if (y == 0) throw invalid_argument("Division by zero");
    • return x / y;
    • }
    • int faiMoltiplicazione(int x, int y){
    • return (x * y);
    • int faiMoltiplicazione(int x, int y) {
    • return x * y;
    • }
    • int faiModulus(int x, int y){
    • return (x % y);
    • int faiModulus(int x, int y) {
    • return x % y;
    • }
  • removed returning -1 for an empty array
  • removed std::accumulate since it truncates all doubles to integers
  • fixed tests
Code
Diff
  • #include <vector>
    
    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;
    }
    • #include <vector>
    • #include <numeric>
    • #include <vector>
    • template <typename T = double>
    • int sum(const std::vector<T>& v) {
    • return v.size() == 0 ? -1
    • : std::accumulate(v.begin(), v.end(), 0);
    • decltype(T() + T()) sum(const std::vector<T>& v) {
    • decltype(T() + T()) res = 0;
    • for (const T &num : v) res += num;
    • return res;
    • }
Test Cases
Diff
  • Describe(Sample_Tests) {
      It(Int_Test) {
        Assert::That(sum({0,7,3,4,1,6,0,8,2,0,2,4}), Equals(37));
      }
      It(Double_Test) {
        Assert::That(sum({0.7,3.9,1.6,0.8,2.0,2.4}), EqualsWithDelta(11.4, 1e-8));
      }
      It(Empty_Test) {
        Assert::That(sum({}), Equals(0));
      }
    };
    • import codewars_test as test
    • # TODO Write tests
    • from solution import sum
    • import random
    • # test.assert_equals(actual, expected, [optional] message)
    • @test.describe("Example tests")
    • def test_group():
    • @test.it("Basic tests")
    • def basic_test_case():
    • test.assert_equals(sum([1]), 1)
    • test.assert_equals(sum([1,2,3]), 6)
    • test.assert_equals(sum([]), 0)
    • @test.it("Random tests")
    • def random_test_case():
    • for i in range(5):
    • test_array = []
    • test_array_length = random.randint(10, 100)
    • test_array_sum = 0
    • for j in range(test_array_length):
    • random_number = random.randint(0, 100)
    • test_array.append(random_number)
    • test_array_sum += random_number
    • test.assert_equals(sum(test_array), test_array_sum)
    • Describe(Sample_Tests) {
    • It(Int_Test) {
    • Assert::That(sum({0,7,3,4,1,6,0,8,2,0,2,4}), Equals(37));
    • }
    • It(Double_Test) {
    • Assert::That(sum({0.7,3.9,1.6,0.8,2.0,2.4}), EqualsWithDelta(11.4, 1e-8));
    • }
    • It(Empty_Test) {
    • Assert::That(sum({}), Equals(0));
    • }
    • };

KISS — Keep It Short and Simple

Code
Diff
  • #include <string>
    #include <vector>
    
    using std::string;
    using std::vector;
    
    vector<string> split(const string& str, char sep, bool strip = true) {
      vector<string> result;
      string buf;
      for (char c : str) {
        if (c == sep) {
          if (!strip || !buf.empty()) {
            result.push_back(buf);
            buf.clear();
          }
        } else buf.push_back(c);
      }
      if (!strip || !buf.empty()) result.push_back(buf);
      return result;
    }
    
    
    • #include <string>
    • #include <vector>
    • auto split(const std::string& str, char sep) {
    • auto result = std::vector<std::string>{};
    • std::string::size_type pos = 0, pos2 = 0;
    • while ((pos2 = str.find(sep, pos)) != std::string::npos) {
    • result.push_back(str.substr(pos, pos2 - pos));
    • pos = pos2 + 1;
    • using std::string;
    • using std::vector;
    • vector<string> split(const string& str, char sep, bool strip = true) {
    • vector<string> result;
    • string buf;
    • for (char c : str) {
    • if (c == sep) {
    • if (!strip || !buf.empty()) {
    • result.push_back(buf);
    • buf.clear();
    • }
    • } else buf.push_back(c);
    • }
    • result.push_back(str.substr(pos));
    • if (!strip || !buf.empty()) result.push_back(buf);
    • return result;
    • }

Next challenge is to mean long long array

Code
Diff
  • class Mean {
    public:
      static double meanAsDouble(const int x[], int n) {
        long long s = 0;
        for (int i = 0; i < n; ++i) s += x[i];
        return s / n + static_cast<double>(s % n) / n;
      }
      static int meanRounded(const int x[], int n) {
        long long s = 0;
        for (int i = 0; i < n; ++i) s += x[i];
        int part = s / n;
        int rem = s % n;
        int cm = n - rem;
        return part + (rem > cm || (rem == cm && part % 2));
      }
      static int meanTruncated(const int x[], int n) {
        long long s = 0;
        for (int i = 0; i < n; ++i) s += x[i];
        return s / n;
      }
    };
    
    • #include <numeric>
    • double Mean(double x[], int n){
    • return std::accumulate(x, x + n, 0) / n;
    • }
    • class Mean {
    • public:
    • static double meanAsDouble(const int x[], int n) {
    • long long s = 0;
    • for (int i = 0; i < n; ++i) s += x[i];
    • return s / n + static_cast<double>(s % n) / n;
    • }
    • static int meanRounded(const int x[], int n) {
    • long long s = 0;
    • for (int i = 0; i < n; ++i) s += x[i];
    • int part = s / n;
    • int rem = s % n;
    • int cm = n - rem;
    • return part + (rem > cm || (rem == cm && part % 2));
    • }
    • static int meanTruncated(const int x[], int n) {
    • long long s = 0;
    • for (int i = 0; i < n; ++i) s += x[i];
    • return s / n;
    • }
    • };

// FIXME

Code
Diff
  • using std::string;
    using std::vector;
    
    string sumPositive(const string &x, const string &y) {
      size_t m = x.size(), n = y.size();
      string res;
      short acc = 0;
      for (size_t i = 1; i <= m && i <= n; ++i) {
        acc += x[m-i] - '0';
        acc += y[n-i] - '0';
        res.push_back(acc % 10 + '0');
        acc /= 10;
      }
      for (size_t i = n + 1; i <= m; ++i) {
        acc += x[m-i] - '0';
        res.push_back(acc % 10 + '0');
        acc /= 10;
      }
      for (size_t i = m + 1; i <= n; ++i) {
        acc += y[n-i] - '0';
        res.push_back(acc % 10 + '0');
        acc /= 10;
      }
      if (acc > 0) res.push_back(acc + '0');
      size_t s = res.size();
      for (size_t i = 0; i < s / 2; ++i) {
        char c = res[i];
        res[i] = res[s-i-1];
        res[s-i-1] = c;
      }
      return res;
    }
    
    vector<string> getFibs(size_t n) {
      if (n == 0) return {};
      if (n == 1) return {"1"};
      string prev = "0";
      string curr = "1";
      vector<string> res = {"1"};
      for (size_t i = 2; i <= n; ++i) {
        string next = sumPositive(prev, curr);
        res.push_back(next);
        prev = curr;
        curr = next;
      }
      return res;
    }
    • get_fibs=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135, 308061521170129, 498454011879264, 806515533049393, 1304969544928657, 2111485077978050, 3416454622906707, 5527939700884757, 8944394323791464, 14472334024676221, 23416728348467685, 37889062373143906, 61305790721611591, 99194853094755497, 160500643816367088, 259695496911122585, 420196140727489673, 679891637638612258, 1100087778366101931, 1779979416004714189, 2880067194370816120, 4660046610375530309, 7540113804746346429, 12200160415121876738, 19740274219868223167, 31940434634990099905, 51680708854858323072, 83621143489848422977, 135301852344706746049, 218922995834555169026, 354224848179261915075]
    • using std::string;
    • using std::vector;
    • string sumPositive(const string &x, const string &y) {
    • size_t m = x.size(), n = y.size();
    • string res;
    • short acc = 0;
    • for (size_t i = 1; i <= m && i <= n; ++i) {
    • acc += x[m-i] - '0';
    • acc += y[n-i] - '0';
    • res.push_back(acc % 10 + '0');
    • acc /= 10;
    • }
    • for (size_t i = n + 1; i <= m; ++i) {
    • acc += x[m-i] - '0';
    • res.push_back(acc % 10 + '0');
    • acc /= 10;
    • }
    • for (size_t i = m + 1; i <= n; ++i) {
    • acc += y[n-i] - '0';
    • res.push_back(acc % 10 + '0');
    • acc /= 10;
    • }
    • if (acc > 0) res.push_back(acc + '0');
    • size_t s = res.size();
    • for (size_t i = 0; i < s / 2; ++i) {
    • char c = res[i];
    • res[i] = res[s-i-1];
    • res[s-i-1] = c;
    • }
    • return res;
    • }
    • vector<string> getFibs(size_t n) {
    • if (n == 0) return {};
    • if (n == 1) return {"1"};
    • string prev = "0";
    • string curr = "1";
    • vector<string> res = {"1"};
    • for (size_t i = 2; i <= n; ++i) {
    • string next = sumPositive(prev, curr);
    • res.push_back(next);
    • prev = curr;
    • curr = next;
    • }
    • return res;
    • }

What's new:

  • Imported separate std::-s instead of entire namespace std
  • Implemented testing using string IO
Code
Diff
  • #include <iostream>
    #include <cstdlib>
    #include <ctime>
    #include <vector>
    #include <algorithm>
    #include <cmath>
    #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
    
        // Shuffle digits
        shuffle(digits.begin(), digits.end(), g);
    
        // Return the first 4 digits as a string
        return string(digits.begin(), digits.begin() + 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 isNumeric(const string &s) {
        return all_of(s.begin(), s.end(), [](char c){ return isdigit(c); });
    }
    
    string getUserGuess(istream &in = cin, ostream &out = cout) {
        string guess;
        out << "Enter your guess (a 4-digit number with non-repeating digits): ";
        in >> guess;
        return guess;
    }
    
    pair<int, int> checkGuess(const string &randomNumber, const string &userGuess) {
        int correctNumbers = 0;
        int correctPosition = 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++;
            }
        }
    
        return make_pair(correctNumbers, correctPosition);
    }
    
    int acceptGuess(const string &expected, istream &in = cin, ostream &out = cout) {
        int attempts = 0;
        while (true) {
            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;
            }
            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;
            }
        }
        return attempts;
    }
    
    int _main(istream &in = cin, ostream &out = cout) {
        // Seed rand since random_shuffle _probably_ uses it.
        srand(static_cast<unsigned>(time(0)));
        string randomNumber = generateRandomNumber();
        acceptGuess(randomNumber, in, out);
        return 0;
    }
    
    • #include <iostream>
    • #include <cstdlib>
    • #include <ctime>
    • #include <vector>
    • #include <algorithm>
    • #include <cmath>
    • #include <random>
    • using namespace std;
    • 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
    • // Shuffle digits
    • shuffle(digits.begin(), digits.end(), g);
    • // Return the first 4 digits as a string
    • return string(digits.begin(), digits.begin() + 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 isNumeric(const string &s) {
    • return all_of(s.begin(), s.end(), [](char c){ return isdigit(c); });
    • }
    • string getUserGuess() {
    • string getUserGuess(istream &in = cin, ostream &out = cout) {
    • string guess;
    • cout << "Enter your guess (a 4-digit number with non-repeating digits): ";
    • cin >> guess;
    • out << "Enter your guess (a 4-digit number with non-repeating digits): ";
    • in >> guess;
    • return guess;
    • }
    • pair<int, int> checkGuess(const string &randomNumber, const string &userGuess) {
    • int correctNumbers = 0;
    • int correctPosition = 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++;
    • }
    • }
    • return make_pair(correctNumbers, correctPosition);
    • }
    • int _main() {
    • // Seed rand since random_shuffle _probably_ uses it.
    • srand(static_cast<unsigned>(time(0)));
    • string randomNumber = generateRandomNumber();
    • int acceptGuess(const string &expected, istream &in = cin, ostream &out = cout) {
    • int attempts = 0;
    • while (true) {
    • string userGuess = getUserGuess();
    • string userGuess = getUserGuess(in, out);
    • if (userGuess.length() != 4 || hasDuplicateDigits(userGuess) || !isNumeric(userGuess)) {
    • cout << "Invalid input. Please enter a 4-digit number with non-repeating digits." << endl;
    • out << "Invalid input. Please enter a 4-digit number with non-repeating digits." << endl;
    • continue;
    • }
    • auto [corNum, corPos] = checkGuess(randomNumber, userGuess);
    • cout << "Correct numbers: " << corNum << " Correct position: " << corPos << endl;
    • auto [corNum, corPos] = checkGuess(expected, userGuess);
    • out << "Correct numbers: " << corNum << " Correct position: " << corPos << endl;
    • attempts++;
    • if (corPos == 4) {
    • cout << "Congratulations! You guessed the number " << randomNumber << " correctly in " << attempts << " attempts!" << endl;
    • out << "Congratulations! You guessed the number " << expected << " correctly in " << attempts << " attempts!" << endl;
    • break;
    • }
    • }
    • return attempts;
    • }
    • int _main(istream &in = cin, ostream &out = cout) {
    • // Seed rand since random_shuffle _probably_ uses it.
    • srand(static_cast<unsigned>(time(0)));
    • string randomNumber = generateRandomNumber();
    • acceptGuess(randomNumber, in, out);
    • return 0;
    • }
Code
Diff
  • #include <iostream>
    #include <string>
    using namespace std;
    
    bool helloWorld() {
      return [](const string &H, const string &W){
        return (cout << H << W << endl).good();
      }("Hello, ", "World!");
    }
    • //Created by RHB
    • // Your code here
    • #include <iostream>
    • #include <string>
    • using namespace std;
    • int main() {
    • string H, W;
    • H="Hello ";
    • W="World!";
    • cout << H << W << endl;
    • return 0;
    • bool helloWorld() {
    • return [](const string &H, const string &W){
    • return (cout << H << W << endl).good();
    • }("Hello, ", "World!");
    • }