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

-40 chars

Code
Diff
  • describeAge=a=>(x=>"You're a(n) "+(["kid","teenager","adult"].find((i,id)=>a<=x[id])||"elderly"))([12,17,64])
    • describeAge = a => {
    • ageL=[12,17,64]
    • return "You're a(n) "+(["kid","teenager","adult"].find((i,id)=>{
    • if(a<=ageL[id]){return i}
    • })||"elderly")
    • }
    • describeAge=a=>(x=>"You're a(n) "+(["kid","teenager","adult"].find((i,id)=>a<=x[id])||"elderly"))([12,17,64])
Code
Diff
  • fn round_half_up(n: f64, m: i32) -> f64 {
        (n * 10f64.powi(m) + 10f64.powi(-10)).round() / 10f64.powi(m)
    }
    • from decimal import Decimal, ROUND_HALF_UP
    • def roundHalfUp( n, m ):
    • return float( Decimal( str( n ) ).quantize( Decimal( "1." + "0" * m ), rounding = ROUND_HALF_UP ) )
    • fn round_half_up(n: f64, m: i32) -> f64 {
    • (n * 10f64.powi(m) + 10f64.powi(-10)).round() / 10f64.powi(m)
    • }
Object-oriented Programming
Mathematics
Code
Diff
  • use std::f64::consts::PI;
    
    pub struct Shape {
        color: String,
        thickness: u32,
        location: (i32, i32)
    }
    
    impl Shape {
        pub fn new(color: String, thickness: u32, location: (i32, i32)) -> Self {
            Self {
                color,
                thickness,
                location,
            }
        }
        
        pub fn change_color(&mut self, color: String) {
            self.color = color;
        }
    }
    
    pub struct Circle {
        radius: f64,
        color: String,
        thickness: u32,
        location: (i32, i32)
    }
    
    impl Circle {
        pub fn new(radius: f64, color: String, thickness: u32, location: (i32, i32)) -> Self {
            Self {
                radius,
                color,
                thickness,
                location
            }
        }
        
        pub fn change_color(&mut self, color: String) -> String {
            let message = format!("The color has changed from {} to {}", self.color, color);
            self.color = color;
            message
        }
        
        pub fn area(&self) -> f64 {
            PI * self.radius.powi(2)
        }
    }
    • import math
    • class Shape:
    • """A Shape base class."""
    • def __init__(self, color, thickness, location):
    • self.color = color
    • self.thickness = thickness
    • self.location = location
    • def __str__(self):
    • return f'{self.__class__.__name__}(color={self.color}, thickness={self.thickness}, location={self.location})'
    • def change_color(self, color):
    • self.color = color
    • class Circle(Shape):
    • """A Circle class that inherits from Shape class."""
    • def __init__(self, radius, color, thickness, location):
    • super().__init__(color, thickness, location)
    • self.radius = radius
    • def __str__(self):
    • return f'{super().__str__()[:-1]}, radius={self.radius})'
    • def change_color(self, color):
    • """Changes the color attribute of Shape. This is also an example of polymorphism"""
    • old, self.color = self.color, color
    • return f'The color has changed from {old} to {self.color}!'
    • def area(self):
    • """Returns the area of a Circle"""
    • return math.pi * self.radius ** 2
    • use std::f64::consts::PI;
    • pub struct Shape {
    • color: String,
    • thickness: u32,
    • location: (i32, i32)
    • }
    • impl Shape {
    • pub fn new(color: String, thickness: u32, location: (i32, i32)) -> Self {
    • Self {
    • color,
    • thickness,
    • location,
    • }
    • }
    • pub fn change_color(&mut self, color: String) {
    • self.color = color;
    • }
    • }
    • pub struct Circle {
    • radius: f64,
    • color: String,
    • thickness: u32,
    • location: (i32, i32)
    • }
    • impl Circle {
    • pub fn new(radius: f64, color: String, thickness: u32, location: (i32, i32)) -> Self {
    • Self {
    • radius,
    • color,
    • thickness,
    • location
    • }
    • }
    • pub fn change_color(&mut self, color: String) -> String {
    • let message = format!("The color has changed from {} to {}", self.color, color);
    • self.color = color;
    • message
    • }
    • pub fn area(&self) -> f64 {
    • PI * self.radius.powi(2)
    • }
    • }
Code
Diff
  • fn filter_data(items: &[Item], search: &str) -> Vec<Item> {
        let conditions: Vec<Condition> = search
            .split(' ')
            .map(Into::into)
            .collect();
    
        items
            .iter()
            .filter(|item| conditions.iter().all(|condition| condition.is_satisfied(item)))
            .cloned()
            .collect()
    }
    
    #[derive(Debug, PartialEq, Eq, Clone)]
    struct Item {
        pub name: String,
        pub code: String,
    }
    
    enum Condition {
        Positive(String),
        Negative(String),
    }
    
    impl Condition {
        fn is_satisfied(&self, item: &Item) -> bool {
            match self {
                Condition::Positive(s) => item.name.to_lowercase().contains(s) || item.code.to_lowercase().contains(s),
                Condition::Negative(s) => !item.name.to_lowercase().contains(s) && !item.code.to_lowercase().contains(s)
            }
        }
    }
    
    impl From<&str> for Condition {
        fn from(s: &str) -> Self {
            if s.starts_with("/-") {
                Condition::Negative(s[2..].to_lowercase())
            } else {
                Condition::Positive(s.to_lowercase())
            }
        }
    }
    • function filterData(items,search){
    • if (!search || search?.length == 0) {
    • return items;
    • }
    • let searchInput=search.replace(/\s\s+/g," ");
    • let textNegate=searchInput.split(' ').filter(rs=>rs.startsWith('/-')).map(rs=>rs.replace('/-',''));
    • searchInput=searchInput.replace(/[\s][/-]+.*/g, '');
    • searchInput=searchInput.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&').toLowerCase();
    • let seachArray=searchInput.split(' ');
    • seachArray=seachArray.filter(rs=>!rs.startsWith('\-'));
    • return items.filter(rs=>{
    • let text=rs.name.toLowerCase();
    • // test if contain only on word negated
    • if(textNegate.length==1 && textNegate[0].length>0){
    • if(text.search(textNegate[0].toLowerCase())>=0)
    • {
    • "negate one word"
    • return false;
    • }
    • }
    • if(text.search(search)>=0)
    • return true;
    • if(seachArray.length==1 && rs.code.search(search)>=0){
    • return true;
    • }
    • let result=false;
    • for(let i=0;i<seachArray.length;i++){
    • if(!new RegExp(`${seachArray[i]}.*`).test(text)){
    • result=false;
    • break;
    • }
    • result=true;
    • }
    • return result;
    • });
    • }
    • fn filter_data(items: &[Item], search: &str) -> Vec<Item> {
    • let conditions: Vec<Condition> = search
    • .split(' ')
    • .map(Into::into)
    • .collect();
    • items
    • .iter()
    • .filter(|item| conditions.iter().all(|condition| condition.is_satisfied(item)))
    • .cloned()
    • .collect()
    • }
    • #[derive(Debug, PartialEq, Eq, Clone)]
    • struct Item {
    • pub name: String,
    • pub code: String,
    • }
    • enum Condition {
    • Positive(String),
    • Negative(String),
    • }
    • impl Condition {
    • fn is_satisfied(&self, item: &Item) -> bool {
    • match self {
    • Condition::Positive(s) => item.name.to_lowercase().contains(s) || item.code.to_lowercase().contains(s),
    • Condition::Negative(s) => !item.name.to_lowercase().contains(s) && !item.code.to_lowercase().contains(s)
    • }
    • }
    • }
    • impl From<&str> for Condition {
    • fn from(s: &str) -> Self {
    • if s.starts_with("/-") {
    • Condition::Negative(s[2..].to_lowercase())
    • } else {
    • Condition::Positive(s.to_lowercase())
    • }
    • }
    • }
Code
Diff
  • fn letter_frequency(s: &str) -> Vec<(char, usize)> {
        let s = s.to_lowercase();
        let mut frequencies: Vec<(char, usize)> = ('a'..='z')
            .map(|l| (l, s.chars().filter(|&c| c == l).count()))
            .filter(|&(_, n)| n != 0)
            .collect();
        frequencies.sort_by_key(|&(_, n)| usize::MAX - n);
        frequencies
    }
    • from collections import Counter
    • def letter_frequency(text):
    • chars = Counter(c for c in text.lower() if c.isalpha())
    • return sorted(chars.items(), key=lambda x: (-x[1], x[0]))
    • fn letter_frequency(s: &str) -> Vec<(char, usize)> {
    • let s = s.to_lowercase();
    • let mut frequencies: Vec<(char, usize)> = ('a'..='z')
    • .map(|l| (l, s.chars().filter(|&c| c == l).count()))
    • .filter(|&(_, n)| n != 0)
    • .collect();
    • frequencies.sort_by_key(|&(_, n)| usize::MAX - n);
    • frequencies
    • }
Code
Diff
  • fn remove_exclamation_marks(s: &str) -> String {
        s.replace('!', "")
    }
    • function removeExclamationMarks(s) {
    • }
    • fn remove_exclamation_marks(s: &str) -> String {
    • s.replace('!', "")
    • }
Functional Programming
Code
Diff
  • fn prime_factors(number: u32) -> Vec<u32> {
        match (2..number).find(|divisor| number % divisor == 0) {
            Some(factor) => [vec![factor], prime_factors(number / factor)].concat(),
            None => vec![number],
        }
    }
    
    • def prime_factors(n):
    • divider = lambda x: next((i for i in range(2, x) if x % i == 0), -1)
    • return ([] if n == 1 else [n]) if divider(n) == -1 else ([divider(n)] + prime_factors(n // divider(n)))
    • fn prime_factors(number: u32) -> Vec<u32> {
    • match (2..number).find(|divisor| number % divisor == 0) {
    • Some(factor) => [vec![factor], prime_factors(number / factor)].concat(),
    • None => vec![number],
    • }
    • }
Code
Diff
  • pub fn is_divisible(n: i32, x: i32, y: i32) -> bool {
        n % x * y == 0
    }
    • pub fn is_divisible(n: i32, x: i32, y: i32) -> bool {
    • n%x+n%y==0
    • n % x * y == 0
    • }
Code
Diff
  • fn calculator(operator: char, num1: i32, num2: i32) -> i32 {
        match operator {
            '+' => num1 + num2,
            '-' => num1 - num2,
            '*' => num1 * num2,
            '/' => num1 / num2,
            _ => panic!("Invalid operator: '{operator}'.")
        }
    }
    • def calculator(operator, num1, num2):
    • if operator == "+":
    • result = num1 + num2
    • elif operator == "-":
    • result = num1 - num2
    • elif operator == "*":
    • result = num1 * num2
    • elif operator == "/":
    • result = num1 / num2
    • else:
    • raise ValueError("Invalid operator. Supported operators are +, -, *, /")
    • return result
    • result = calculator("+", 4, 8)
    • print(result)
    • result = calculator("-", 7, 4)
    • print(result)
    • result = calculator("*", 8, 7)
    • print(result)
    • result = calculator("/", 70, 7)
    • print(result)
    • fn calculator(operator: char, num1: i32, num2: i32) -> i32 {
    • match operator {
    • '+' => num1 + num2,
    • '-' => num1 - num2,
    • '*' => num1 * num2,
    • '/' => num1 / num2,
    • _ => panic!("Invalid operator: '{operator}'.")
    • }
    • }