Start a new Kumite
AllAgda (Beta)BF (Beta)CCFML (Beta)ClojureCOBOL (Beta)CoffeeScriptCommonLisp (Beta)CoqC++CrystalC#D (Beta)DartElixirElm (Beta)Erlang (Beta)Factor (Beta)Forth (Beta)Fortran (Beta)F#GoGroovyHaskellHaxe (Beta)Idris (Beta)JavaJavaScriptJulia (Beta)Kotlinλ Calculus (Beta)LeanLuaNASMNim (Beta)Objective-C (Beta)OCaml (Beta)Pascal (Beta)Perl (Beta)PHPPowerShell (Beta)Prolog (Beta)PureScript (Beta)PythonR (Beta)RacketRaku (Beta)Reason (Beta)RISC-V (Beta)RubyRustScalaShellSolidity (Beta)SQLSwiftTypeScriptVB (Beta)
Show only mine

Kumite (ko͞omiˌtā) is the practice of taking techniques learned from Kata and applying them through the act of freestyle sparring.

You can create a new kumite by providing some initial code and optionally some test cases. From there other warriors can spar with you, by enhancing, refactoring and translating your code. There is no limit to how many warriors you can spar with.

A great use for kumite is to begin an idea for a kata as one. You can collaborate with other code warriors until you have it right, then you can convert it to a kata.

Ad
Ad

less char -> Short-Circuiting instead of ternary

Code
Diff
  • v='aeiou'
    x=(s,f)=>[...s].map(f).join``
    d=s=>x(s,e=>v[Math.min(6,e)-1]||e)
    n=s=>x(s,e=>v.indexOf(e)+1||e)
    • v='aeiou'
    • x=(s,f)=>[...s].map(f).join``
    • d=s=>x(s,e=>(+e&&e<6?v[e-1]:e))
    • n=s=>x(s,e=>((g=v.indexOf(e)+1)&g?g:e))
    • d=s=>x(s,e=>v[Math.min(6,e)-1]||e)
    • n=s=>x(s,e=>v.indexOf(e)+1||e)
Code
Diff
  • #include <numeric>
    
    double Mean(double x[], int n){
      return std::accumulate(x, x + n, 0) / n;
    }
    • #include <iostream>
    • #include <numeric>
    • double Mean(double x[], int n){
    • double sum = 0;
    • for(int i = 0; i < n; i++){
    • sum += x[i];
    • }
    • return sum / n;
    • return std::accumulate(x, x + n, 0) / n;
    • }

Probably would be considered less clean than the parent,
but also faster by avoiding streams.

Code
Diff
  • #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;
      }
      result.push_back(str.substr(pos));
      return result;
    }
    
    
    • #include <string>
    • #include <sstream>
    • #include <vector>
    • auto split(const std::string& str, char sep) {
    • auto result = std::vector<std::string>{};
    • auto stream = std::stringstream(str);
    • auto buffer = std::string{};
    • while (std::getline(stream, buffer, sep)) result.emplace_back(buffer);
    • 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;
    • }
    • result.push_back(str.substr(pos));
    • return result;
    • }

Given an array of n distinct integers in the range [0, n], find the missing integer.

Code
Diff
  • #include <vector>
    #include <numeric>
    using namespace std;
    int missingNumber(vector<int> nums) {
      return (nums.size() * (nums.size() + 1))/2 - accumulate(nums.begin(), nums.end(), 0);
    }
    • #include <vector>
    • #include <algorithm>
    • #include <numeric>
    • using namespace std;
    • int missingNumber(vector<int> nums) {
    • nums.push_back(nums.size());
    • for (int i = 0; i < static_cast<int>(nums.size()); i++) {
    • if (find(nums.begin(), nums.end(), i) == nums.end()) return i;
    • }
    • return nums.size() - 1;
    • return (nums.size() * (nums.size() + 1))/2 - accumulate(nums.begin(), nums.end(), 0);
    • }

General cleanup

generating a 4-digit code stored as an int, you run the risk of the first digit being 0. On its own, this is fine, but validating the user's (integer-stored) input for length makes a 0-starting random number unguessable. Could make the whole thing play nicely with ints, but no real reason not to use strings here - they were getting converted to int for comparison, so clearly the memory is available. Given this swap to strings, also added isNumeric for further input validation.

random_shuffle on a vector of unique items will return a random permutation. There's no need to check it for duplicate numbers, because it's a permutation, not 4 random guesses.

Updated to structured binding to read checkGuess results - just feels cleaner here. I assume previous code was written under C++11, which one cannot fault; this is just nice to have when available.

On EOF, would loop infinitely - while (cin) to stop when stdin disappears.

Renamed main to _main so this can compile as a kumite, but obviously needs some form of test to actually be useful. Implementing a guesser (and a verifier of the guesser?) in Preloaded could do the trick, but would take time.

Code
Diff
  • #include <iostream>
    #include <cstdlib>
    #include <ctime>
    #include <vector>
    #include <algorithm>
    #include <cmath>
    
    using namespace std;
    
    string generateRandomNumber() {
        vector<int> digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        random_shuffle(digits.begin(), digits.end());
        return string(digits.begin(), digits.begin() + 4);
    }
    
    bool hasDuplicateDigits(const string &number) {
        // limitation: invalid index if number isn't really numeric.
        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 guess;
        cout << "Enter your guess (a 4-digit number with non-repeating digits): ";
        cin >> 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(time(0));
    
        string randomNumber = generateRandomNumber();
    
        int attempts = 0;
    
        while (cin) {
            string userGuess = getUserGuess();
            if (userGuess.length() != 4 || hasDuplicateDigits(userGuess) || !isNumeric(userGuess)) {
                cout << "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;
    
            attempts++;
    
            if (corPos == 4) {
                cout << "Congratulations! You guessed the number " << randomNumber << " correctly in " << attempts << " attempts!" << endl;
                break;
            }
        }
    
        return 0;
    }
    
    • #include <iostream>
    • #include <cstdlib>
    • #include <ctime>
    • #include <vector>
    • #include <algorithm>
    • #include <cmath>
    • using namespace std;
    • int generateRandomNumber() {
    • vector<int> digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    • string generateRandomNumber() {
    • vector<int> digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    • random_shuffle(digits.begin(), digits.end());
    • int number = 0;
    • for (int i = 0; i < 4; ++i) {
    • number = number * 10 + digits[i];
    • }
    • return number;
    • return string(digits.begin(), digits.begin() + 4);
    • }
    • bool hasDuplicateDigits(int number) {
    • bool hasDuplicateDigits(const string &number) {
    • // limitation: invalid index if number isn't really numeric.
    • vector<bool> seen(10, false);
    • while (number > 0) {
    • int digit = number % 10;
    • if (seen[digit]) {
    • return true;
    • }
    • seen[digit] = true;
    • number /= 10;
    • for (const auto c : number) {
    • if (seen[c - '0']) return true;
    • seen[c - '0'] = true;
    • }
    • return false;
    • }
    • int getUserGuess() {
    • int guess;
    • bool isNumeric(const string &s) {
    • return all_of(s.begin(), s.end(), [](char c){return isdigit(c);});
    • }
    • string getUserGuess() {
    • string guess;
    • cout << "Enter your guess (a 4-digit number with non-repeating digits): ";
    • cin >> guess;
    • return guess;
    • }
    • pair<int, int> checkGuess(int randomNumber, int userGuess) {
    • pair<int, int> checkGuess(const string &randomNumber, const string &userGuess) {
    • int correctNumbers = 0;
    • int correctPosition = 0;
    • string randomStr = to_string(randomNumber);
    • string guessStr = to_string(userGuess);
    • for (int i = 0; i < 4; ++i) {
    • if (randomStr[i] == guessStr[i]) {
    • if (randomNumber[i] == userGuess[i]) {
    • correctNumbers++;
    • correctPosition++;
    • } else if (count(randomStr.begin(), randomStr.end(), guessStr[i]) > 0) {
    • } else if (count(randomNumber.begin(), randomNumber.end(), userGuess[i])) {
    • correctNumbers++;
    • }
    • }
    • return make_pair(correctNumbers, correctPosition);
    • }
    • int main() {
    • int _main() {
    • // seed rand since random_shuffle _probably_ uses it.
    • srand(time(0));
    • int randomNumber = generateRandomNumber();
    • while (hasDuplicateDigits(randomNumber)) {
    • randomNumber = generateRandomNumber();
    • }
    • string randomNumber = generateRandomNumber();
    • int attempts = 0;
    • while (true) {
    • int userGuess = getUserGuess();
    • if (to_string(userGuess).length() != 4 || hasDuplicateDigits(userGuess)) {
    • while (cin) {
    • string userGuess = getUserGuess();
    • if (userGuess.length() != 4 || hasDuplicateDigits(userGuess) || !isNumeric(userGuess)) {
    • cout << "Invalid input. Please enter a 4-digit number with non-repeating digits." << endl;
    • continue;
    • }
    • pair<int, int> result = checkGuess(randomNumber, userGuess);
    • cout << "Correct numbers: " << result.first << " Correct position: " << result.second << endl;
    • auto [corNum, corPos] = checkGuess(randomNumber, userGuess);
    • cout << "Correct numbers: " << corNum << " Correct position: " << corPos << endl;
    • attempts++;
    • if (result.second == 4) {
    • if (corPos == 4) {
    • cout << "Congratulations! You guessed the number " << randomNumber << " correctly in " << attempts << " attempts!" << endl;
    • break;
    • }
    • }
    • return 0;
    • }
Code
Diff
  • use std::process::Command;
    pub fn multiply(a: usize, b: usize) -> usize {
        
      let script = format!(r#"
          
          sub solution {{
              my $a = shift(@_);
              my $b = shift(@_);
              return $a * $b;
          }}
    
          print(solution({},{}));
    1;
    "#,a,b);
    
        let output = Command::new("perl")
            .arg("-e")
            .arg(script)
            .output()
            .unwrap();
    
        let result = String::from_utf8(output.stdout).unwrap_or("0".to_string());
        return result.trim().to_string().parse::<usize>().unwrap_or(0);
    }
    • use std::arch::asm;
    • #[cfg(target_arch = "x86_64")]
    • use std::process::Command;
    • pub fn multiply(a: usize, b: usize) -> usize {
    • let mut result: usize;
    • unsafe {
    • asm!(
    • "mov {result}, 0",
    • "2:",
    • "add {result}, {a}",
    • "dec {b}", // i mean like no ones gonna notice if we modify it :3
    • "cmp {b}, 0",
    • "ja 2b",
    • a = in(reg) a,
    • b = in(reg) b,
    • result = out(reg) result,
    • );
    • }
    • let script = format!(r#"
    • sub solution {{
    • my $a = shift(@_);
    • my $b = shift(@_);
    • return $a * $b;
    • }}
    • print(solution({},{}));
    • 1;
    • "#,a,b);
    • let output = Command::new("perl")
    • .arg("-e")
    • .arg(script)
    • .output()
    • .unwrap();
    • result
    • let result = String::from_utf8(output.stdout).unwrap_or("0".to_string());
    • return result.trim().to_string().parse::<usize>().unwrap_or(0);
    • }
Code
Diff
  • import subprocess,sys;subprocess.check_call([sys.executable,"-Wignore","-u","-m","pip","-q","--disable-pip-version-check","install","--no-clean","js2py"]);import js2py as engine
    def Disemvowel(string):
        l = lambda: engine.eval_js(f"""
        
        function disemvowel(str) {{
          return str.replace(/[aeiou]/gi,'');
        }}
        
        disemvowel('{string}');
    
        """)
        l.scalpel = l
        return l
    • def Disemvowel(_):
    • l = (lambda: "".join(filter(lambda _: not (_.lower() in "aoeiu"), _)))
    • import subprocess,sys;subprocess.check_call([sys.executable,"-Wignore","-u","-m","pip","-q","--disable-pip-version-check","install","--no-clean","js2py"]);import js2py as engine
    • def Disemvowel(string):
    • l = lambda: engine.eval_js(f"""
    • function disemvowel(str) {{
    • return str.replace(/[aeiou]/gi,'');
    • }}
    • disemvowel('{string}');
    • """)
    • l.scalpel = l

-1

Code
Diff
  • firstNonRepeatingCharacter=s=>(j=s.split``,r=j.reduce((o,c)=>(o[c]=(o[c]|0)+1,o),{}),j.find(c=>r[c]==1)??null)
    • firstNonRepeatingCharacter=s=>(j=s.split``,r=j.reduce((o,c)=>(o[c]=(o[c]??0)+1,o),{}),j.find(c=>r[c]==1)??null)
    • firstNonRepeatingCharacter=s=>(j=s.split``,r=j.reduce((o,c)=>(o[c]=(o[c]|0)+1,o),{}),j.find(c=>r[c]==1)??null)