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
Strings
Mathematics
Code
Diff
  • fn math(expression: &str) -> Result<i32, MathError> {
        // remove whitespace
        let expression: String = expression.chars().filter(|ch| !ch.is_whitespace()).collect();
        let operator: char = expression.chars().find(|ch| ['+', '-', '*', '/', '='].contains(&ch)).ok_or(MathError::MissingOperator)?;
        
        let operands: Vec<i32> = expression.split(operator).filter_map(|n| n.parse().ok()).collect();
        let num1 = *operands.get(0).ok_or(MathError::InvalidOperand)?;
        let num2 = *operands.get(1).ok_or(MathError::InvalidOperand)?;
        
        // check if they divide by zero
        if operator == '/' && num2 == 0 {
            return Err(MathError::DivideByZero);
        }
        
        match operator {
            '+' => num1.checked_add(num2).ok_or(MathError::Overflow),
            '-' => num1.checked_sub(num2).ok_or(MathError::Overflow),
            '*' => num1.checked_mul(num2).ok_or(MathError::Overflow),
            '/' => num1.checked_div(num2).ok_or(MathError::Overflow),
            '=' => Ok((num1 == num2).into()),
            _   => unreachable!()
        }
    }
    
    use MathError::*;
    #[derive(Debug, PartialEq, Eq)]
    enum MathError {
        MissingOperator,
        InvalidOperand,
        DivideByZero,
        Overflow,
    }
    
    
    
    • fn math(s: &str) -> Result<i32, MathError> {
    • let s: String = s.chars().filter(|ch| !ch.is_whitespace()).collect();
    • let Some((num1, num2)) =
    • s.split_once(|c| ['+', '-', '*', '/', '='].contains(&c))
    • else {
    • return Err(MissingOperator);
    • };
    • fn math(expression: &str) -> Result<i32, MathError> {
    • // remove whitespace
    • let expression: String = expression.chars().filter(|ch| !ch.is_whitespace()).collect();
    • let operator: char = expression.chars().find(|ch| ['+', '-', '*', '/', '='].contains(&ch)).ok_or(MathError::MissingOperator)?;
    • let operands: Vec<i32> = expression.split(operator).filter_map(|n| n.parse().ok()).collect();
    • let num1 = *operands.get(0).ok_or(MathError::InvalidOperand)?;
    • let num2 = *operands.get(1).ok_or(MathError::InvalidOperand)?;
    • // check if they divide by zero
    • if operator == '/' && num2 == 0 {
    • return Err(MathError::DivideByZero);
    • }
    • let operator = &s[num1.len()..=num1.len()];
    • let (Ok(num1), Ok(num2)) = (num1.parse::<i32>(), num2.parse::<i32>()) else {
    • return Err(InvalidOperand);
    • };
    • match operator {
    • "+" => Ok(num1 + num2),
    • "-" => Ok(num1 - num2),
    • "*" => Ok(num1 * num2),
    • "/" => {
    • if num2 != 0 {
    • Ok(num1 / num2)
    • } else {
    • Err(DivideByZero)
    • }
    • },
    • "=" => Ok(i32::from(num1 == num2)),
    • _ => unreachable!(),
    • '+' => num1.checked_add(num2).ok_or(MathError::Overflow),
    • '-' => num1.checked_sub(num2).ok_or(MathError::Overflow),
    • '*' => num1.checked_mul(num2).ok_or(MathError::Overflow),
    • '/' => num1.checked_div(num2).ok_or(MathError::Overflow),
    • '=' => Ok((num1 == num2).into()),
    • _ => unreachable!()
    • }
    • }
    • use MathError::*;
    • #[derive(Debug, PartialEq, Eq)]
    • enum MathError {
    • MissingOperator,
    • InvalidOperand,
    • DivideByZero
    • DivideByZero,
    • Overflow,
    • }

This solution avoids creating any objects or creating copies of the sequence or any temporary variables.
Using a class in the previous solutions was silly. >.<

Code
Diff
  • from typing import Sequence, Optional
    
    def missing_integer(sequence: Sequence[int]) -> Optional[int]:
        for x, y in zip(sequence, range(sequence[0], sequence[-1])):
            if x != y:
                return y
    • class MissingInteger:
    • def __init__(self, sequence):
    • self.sequence = sequence
    • self.perfect_sequence = range(min(self.sequence), max(self.sequence) +1 )
    • from typing import Sequence, Optional
    • def solution(self):
    • for number in self.perfect_sequence:
    • if number not in self.sequence:
    • return number
    • def missing_integer(sequence: Sequence[int]) -> Optional[int]:
    • for x, y in zip(sequence, range(sequence[0], sequence[-1])):
    • if x != y:
    • return y
Code
Diff
  • fn capitalize(s: &str) -> String {
        s.split(' ')
            .flat_map(|w| Some(w.get(..1)?.to_uppercase() + &w.get(1..)?))
            .collect::<Vec<String>>()
            .join(" ")
    }
    • fn capitalise(s: &str) -> String {
    • return s
    • .split(' ')
    • .map(capitalise_word)
    • fn capitalize(s: &str) -> String {
    • s.split(' ')
    • .flat_map(|w| Some(w.get(..1)?.to_uppercase() + &w.get(1..)?))
    • .collect::<Vec<String>>()
    • .join(" ");
    • }
    • fn capitalise_word(s: &str) -> String {
    • if s.len() == 0 {
    • return s.to_uppercase();
    • }
    • return s.get(0..=0).unwrap().to_uppercase() + s.get(1..).unwrap();
    • .join(" ")
    • }
Code
Diff
  • #include<bits/stdc++.h>
    using namespace std;
    
    long add_arr(vector<int> arr)
    {
      return std::reduce(begin(arr),end(arr));
    }
    • #include<bits/stdc++.h>
    • using namespace std;
    • long add_arr(vector<int> arr)
    • {
    • return std::accumulate(begin(arr),end(arr),0);
    • return std::reduce(begin(arr),end(arr));
    • }
Fundamentals

Represents an ordinal numeral (i.e. 1st, 24th, etc.)

Code
Diff
  • from __future__ import annotations
    
    
    class OrdinalNumeral:
        def __init__(self, n: int):
            """Represents an ordinal numeral (i.e. 1st, 24th, etc.)
    
            :param int n: The integer to represent
            :raises ValueError: Raised if n is below 0
            :raises TypeError: Raised if a non-integer/OrdinalNumber value is added to the number
            """
            if n < 0:
                raise ValueError("n must be positive or 0")
            self._n = n
    
        @property
        def n(self):
            return self._n
    
        @n.setter
        def n(self, n: int):
            if n < 0:
                raise ValueError("n must be positive or 0")
            self._n = n
    
        @property
        def numeral(self):
            if 11 <= (self.n % 100) <= 13:
                return str(self.n) + "th"
            return str(self.n) + ("th", "st", "nd", "rd", "th")[min(4, self.n % 10)]
    
        def __repr__(self):
            """Representation that can be used to recreate the object"""
            return f"OrdinalNumeral(n={self.n})"
    
        def __str__(self):
            """The 'nice' string version of the class"""
            return self.numeral
    
        def __int__(self):
            return self.n
    
        def __add__(self, other: int | OrdinalNumeral):
            """Can implement arithmetic operations if desired"""
            if isinstance(other, OrdinalNumeral):
                return OrdinalNumeral(self.n + other.n)
            elif isinstance(other, int):
                return OrdinalNumeral(self.n + other)
            else:
                raise TypeError(f"Unable to add {type(other)} with OrdinalNumeral")
    
    • from __future__ import annotations
    • class OrdinalNumeral:
    • def __init__(self, n: int):
    • if n < 0: raise ValueError("n must be positive or 0")
    • self.n = n
    • self.numeral = self._numeral()
    • """Represents an ordinal numeral (i.e. 1st, 24th, etc.)
    • :param int n: The integer to represent
    • :raises ValueError: Raised if n is below 0
    • :raises TypeError: Raised if a non-integer/OrdinalNumber value is added to the number
    • """
    • if n < 0:
    • raise ValueError("n must be positive or 0")
    • self._n = n
    • @property
    • def n(self):
    • return self._n
    • @n.setter
    • def n(self, n: int):
    • if n < 0:
    • raise ValueError("n must be positive or 0")
    • self._n = n
    • @property
    • def numeral(self):
    • if 11 <= (self.n % 100) <= 13:
    • return str(self.n) + "th"
    • return str(self.n) + ("th", "st", "nd", "rd", "th")[min(4, self.n % 10)]
    • def __repr__(self):
    • """representation that can be used to recreate the object"""
    • return f"OrdinalNumeral(self.n)"
    • """Representation that can be used to recreate the object"""
    • return f"OrdinalNumeral(n={self.n})"
    • def __str__(self):
    • """the 'nice' string version of the class"""
    • """The 'nice' string version of the class"""
    • return self.numeral
    • def __int__(self):
    • return self.n
    • def __add__(self, other):
    • """can implement arithmetic operations if desired"""
    • if (isinstance(other, OrdinalNumeral)): return OrdinalNumeral(self.n + other.n)
    • elif (isinstance(other, int)): return OrdinalNumeral(self.n + other)
    • else: raise TypeError(f"Unable to add {type(other)} with OrdinalNumeral")
    • def _numeral(self):
    • """define the ordinal numeral string"""
    • if 11 <= (self.n % 100) <= 13: return str(self.n)+"th"
    • return str(self.n)+("th", "st", "nd", "rd", "th")[min(4, self.n % 10)]
    • def __add__(self, other: int | OrdinalNumeral):
    • """Can implement arithmetic operations if desired"""
    • if isinstance(other, OrdinalNumeral):
    • return OrdinalNumeral(self.n + other.n)
    • elif isinstance(other, int):
    • return OrdinalNumeral(self.n + other)
    • else:
    • raise TypeError(f"Unable to add {type(other)} with OrdinalNumeral")