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
Ciphers
Fundamentals
Cryptography
Algorithms
Code
Diff
  • import java.util.List;
    import java.util.stream.Collectors;
    
    public class Kata {
    	
    	// <<-CONSTANTS->>
    	private static final int UpperCase_LOWER_LIMIT = 65;
    	private static final int UpperCase_UPPER_LIMIT = 90;
    	private static final int LowerCase_LOWER_LIMIT = 97;
    	private static final int LowerCase_UPPER_LIMIT = 122;
    	private static final int INTERMEDIATE_OFFSET   = LowerCase_LOWER_LIMIT - UpperCase_UPPER_LIMIT - 1;
    
    	// <<-METHODS->>
    	private static int getLastDigit(final int digit) {
        String str = String.valueOf(digit);
        str = str.substring(str.length() - 1, str.length());
    		return Integer.valueOf(str);
    	}
    	
    	private static List<Integer> getEncryptationOffsets(String key) {
    		return key.chars()
    				.map(n -> getLastDigit(n) + key.length())
    				.boxed()
    				.toList();
    	}
    	
    	private static List<Integer> getPhraseChars(String phrase) {
    		return phrase.chars()
    				.boxed()
    				.collect(Collectors.toList());
    	}
    	
    	private static String parseChars(List<Integer> translation) {
    		return translation.stream()
    				.map(n -> (char) n.intValue())
    				.map(c -> Character.toString(c))
    				.collect(Collectors.joining());
    	}
    
    	public static String encode(String phrase, String key) {
    		if (phrase == null || phrase.isEmpty() || key == null) return "";
    		if (key.isEmpty()) return phrase;
        
    		List<Integer> offsets     = getEncryptationOffsets(key);
    		List<Integer> phraseChars = getPhraseChars(phrase);
    		List<Integer> translation  = new java.util.ArrayList<>();
    
    		int keyIndex = 0;
    		for (int i = 0; i < phrase.length(); i++) {
    			keyIndex = i % offsets.size();
    			
    			int current = phraseChars.get(i);
    			int result  = current + offsets.get(keyIndex);
    			if (current <= UpperCase_UPPER_LIMIT && result >= LowerCase_LOWER_LIMIT) {
    				int offset = result - UpperCase_UPPER_LIMIT;
    				result = LowerCase_LOWER_LIMIT + offset - 1;
    			}
    			
    			if (result > UpperCase_UPPER_LIMIT && result < LowerCase_LOWER_LIMIT) {
    				result += INTERMEDIATE_OFFSET;
    			} else if (result > LowerCase_UPPER_LIMIT) {
    				result = result - LowerCase_UPPER_LIMIT + UpperCase_LOWER_LIMIT - 1;
    			}
    			translation.add(result);
    			keyIndex++;
    		}
    
    		return parseChars(translation);
    	}
    
    	public static String decode(String phrase, String key) {
    		if (phrase == null || phrase.isEmpty() || key == null) return "";
    		if (key.isEmpty()) return phrase;
        
    		List<Integer> offsets     = getEncryptationOffsets(key);
    		List<Integer> phraseChars = getPhraseChars(phrase);
    		List<Integer> translation  = new java.util.ArrayList<>();
    
    		int keyIndex = 0;
    		for (int i = 0; i < phrase.length(); i++) {
    			keyIndex = i % offsets.size();
    			
    			int current = phraseChars.get(i);
    			int result  = current - offsets.get(keyIndex);
    			if (current >= LowerCase_LOWER_LIMIT && result <= UpperCase_UPPER_LIMIT) {
    				int offset = LowerCase_LOWER_LIMIT - result;
    				result = UpperCase_UPPER_LIMIT - offset + 1;
    			}
    			if (result < LowerCase_LOWER_LIMIT && result > UpperCase_UPPER_LIMIT) {
    				result -= INTERMEDIATE_OFFSET;
    			} else if (result < UpperCase_LOWER_LIMIT) {
    				int offset = UpperCase_LOWER_LIMIT - result;
    				result = LowerCase_UPPER_LIMIT - offset + 1;
    			}
    			translation.add(result);
    			keyIndex++;
    		}
    
    		return parseChars(translation);
    	}
      
    }
    • import java.util.List;
    • import java.util.stream.Collectors;
    • public class Kata {
    • // <<-CONSTANTS->>
    • private static final int UpperCase_LOWER_LIMIT = 65;
    • private static final int UpperCase_UPPER_LIMIT = 90;
    • private static final int LowerCase_LOWER_LIMIT = 97;
    • private static final int LowerCase_UPPER_LIMIT = 122;
    • private static final int INTERMEDIATE_OFFSET = LowerCase_LOWER_LIMIT - UpperCase_UPPER_LIMIT - 1;
    • // <<-METHODS->>
    • private static int getLastDigit(final int digit) {
    • String str = String.valueOf(digit);
    • str = str.substring(str.length() - 1, str.length());
    • return Integer.valueOf(str);
    • }
    • private static List<Integer> getEncryptationOffsets(String key) {
    • return key.chars()
    • .map(n -> getLastDigit(n) + key.length())
    • .boxed()
    • .toList();
    • }
    • private static List<Integer> getPhraseChars(String phrase) {
    • return phrase.chars()
    • .boxed()
    • .collect(Collectors.toList());
    • }
    • private static String parseChars(List<Integer> traduction) {
    • return traduction.stream()
    • private static String parseChars(List<Integer> translation) {
    • return translation.stream()
    • .map(n -> (char) n.intValue())
    • .map(c -> Character.toString(c))
    • .collect(Collectors.joining());
    • }
    • public static String encode(String phrase, String key) {
    • if (phrase == null || phrase.isEmpty() || key == null) return "";
    • if (key.isEmpty()) return phrase;
    • List<Integer> offsets = getEncryptationOffsets(key);
    • List<Integer> phraseChars = getPhraseChars(phrase);
    • List<Integer> traduction = new java.util.ArrayList<>();
    • List<Integer> translation = new java.util.ArrayList<>();
    • int keyIndex = 0;
    • for (int i = 0; i < phrase.length(); i++) {
    • keyIndex = i % offsets.size();
    • int current = phraseChars.get(i);
    • int result = current + offsets.get(keyIndex);
    • if (current <= UpperCase_UPPER_LIMIT && result >= LowerCase_LOWER_LIMIT) {
    • int offset = result - UpperCase_UPPER_LIMIT;
    • result = LowerCase_LOWER_LIMIT + offset - 1;
    • }
    • if (result > UpperCase_UPPER_LIMIT && result < LowerCase_LOWER_LIMIT) {
    • result += INTERMEDIATE_OFFSET;
    • } else if (result > LowerCase_UPPER_LIMIT) {
    • result = result - LowerCase_UPPER_LIMIT + UpperCase_LOWER_LIMIT - 1;
    • }
    • traduction.add(result);
    • translation.add(result);
    • keyIndex++;
    • }
    • return parseChars(traduction);
    • return parseChars(translation);
    • }
    • public static String decode(String phrase, String key) {
    • if (phrase == null || phrase.isEmpty() || key == null) return "";
    • if (key.isEmpty()) return phrase;
    • List<Integer> offsets = getEncryptationOffsets(key);
    • List<Integer> phraseChars = getPhraseChars(phrase);
    • List<Integer> traduction = new java.util.ArrayList<>();
    • List<Integer> translation = new java.util.ArrayList<>();
    • int keyIndex = 0;
    • for (int i = 0; i < phrase.length(); i++) {
    • keyIndex = i % offsets.size();
    • int current = phraseChars.get(i);
    • int result = current - offsets.get(keyIndex);
    • if (current >= LowerCase_LOWER_LIMIT && result <= UpperCase_UPPER_LIMIT) {
    • int offset = LowerCase_LOWER_LIMIT - result;
    • result = UpperCase_UPPER_LIMIT - offset + 1;
    • }
    • if (result < LowerCase_LOWER_LIMIT && result > UpperCase_UPPER_LIMIT) {
    • result -= INTERMEDIATE_OFFSET;
    • } else if (result < UpperCase_LOWER_LIMIT) {
    • int offset = UpperCase_LOWER_LIMIT - result;
    • result = LowerCase_UPPER_LIMIT - offset + 1;
    • }
    • traduction.add(result);
    • translation.add(result);
    • keyIndex++;
    • }
    • return parseChars(traduction);
    • return parseChars(translation);
    • }
    • }
Code
Diff
  • """Test equipment positions."""
    from __future__ import annotations
    from collections import Counter, defaultdict
    import datetime as dt
    import math
    import numpy as np
    import pandas as pd
    from typing import Any
    
    
    def data_dict() -> defaultdict[str, Any]:
        """Return all equipment positions."""
        d = defaultdict(list)
        d["T123"].append({"position": {"x": 42, "y": 24, "z": 0.42}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
        d["T456"].append({"position": {"x": 21.0, "y": 34, "z": 0.289}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
        d["T789"].append({"position": {"x": 17, "y": 39, "z": 0.789}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
        d["T456"].append({"position": {"x": 91.0, "y": 114, "z": 0.489}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
        d["T123"].append({"position": {"x": 43, "y": 25, "z": 0.43}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)})
        d["T789"].append({"position": {"x": 19., "y": 79, "z": 0.991}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)})
        d["T123"].append({"position": {"x": 46, "y": 29, "z": 0.44}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)})
        d["T456"].append({"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)})
        d["T123"].append({"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
        d["T789"].append({"position": {"x": 23., "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)})
        return d
    
    
    def latest_snapshot() -> dict[str, Any]:
        """Return a snapshot of latest equipment."""
        return {
            "T123": {"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)},
            "T456": {"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)},
            "T789": {"position": {"x": 23.0, "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)},
        }
    
    
    def counts() -> dict[str, int]:
        """Return counts per equipment."""
        return {
            "T123": 4,
            "T456": 3,
            "T789": 3
        }
    
    
    def speeds() -> defaultdict[str, Any]:
        """Return speeds of equipment."""
        d = defaultdict(list)
        d["T123"].append({"speed": 4.242654947082074, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
        d["T123"].append({"speed": 5.00000999999, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)})
        d["T123"].append({"speed": 1.4142489172702237, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)})
        d["T123"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
        d["T456"].append({"speed": 102.0687849638664, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)})
        d["T456"].append({"speed": 35.43388209045123, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
        d["T456"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
        d["T789"].append({"speed": 4.473538196997986, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)})
        d["T789"].append({"speed": 6.6750796998987205, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)})
        d["T789"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
        return d
    
      
    def find_furthest_west(d: defaultdict) -> str:
        """
        Find the name of the truck that is furthest west. That is,
        the truck with the smallest easting position component.
        """
        min_x = float('inf')
        furthest_west = None
        for equipment, positions in d.items():
            for pos in positions:
                if pos["position"]["x"] < min_x:
                    min_x = pos["position"]["x"]
                    furthest_west = equipment
        return furthest_west
    
    def get_latest_snapshot(d: defaultdict) -> dict[str, Any]:
        """
        Return a snapshot of the latest positional updates for the
        equipment.
        """
        snapshot = {}
        for equipment, positions in d.items():
            latest_pos = max(positions, key=lambda x: x["timestamp"])
            snapshot[equipment] = latest_pos
        return snapshot
    
    def get_counts(d: defaultdict) -> dict[str, int]:
        """Return a dict of trucks and the times they have provided updates."""
        return {equipment: len(positions) for equipment, positions in d.items()}
    
      
    def calculate_speeds(d: defaultdict) -> defaultdict[str, Any]:
        """Return a dict of equipment and the speeds they are travelling at."""
        pass
    
    
    
    • """Test equipment positions."""
    • from __future__ import annotations
    • from collections import Counter, defaultdict
    • import datetime as dt
    • import math
    • import numpy as np
    • import pandas as pd
    • from typing import Any
    • def data_dict() -> defaultdict[str, Any]:
    • """Return all equipment positions."""
    • d = defaultdict(list)
    • d["T123"].append({"position": {"x": 42, "y": 24, "z": 0.42}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
    • d["T456"].append({"position": {"x": 21.0, "y": 34, "z": 0.289}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
    • d["T789"].append({"position": {"x": 17, "y": 39, "z": 0.789}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
    • d["T456"].append({"position": {"x": 91.0, "y": 114, "z": 0.489}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
    • d["T123"].append({"position": {"x": 43, "y": 25, "z": 0.43}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)})
    • d["T789"].append({"position": {"x": 19., "y": 79, "z": 0.991}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)})
    • d["T123"].append({"position": {"x": 46, "y": 29, "z": 0.44}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)})
    • d["T456"].append({"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)})
    • d["T123"].append({"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
    • d["T789"].append({"position": {"x": 23., "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)})
    • return d
    • def latest_snapshot() -> dict[str, Any]:
    • """Return a snapshot of latest equipment."""
    • return {
    • "T123": {"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)},
    • "T456": {"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)},
    • "T789": {"position": {"x": 23.0, "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)},
    • }
    • def counts() -> dict[str, int]:
    • """Return counts per equipment."""
    • return {
    • "T123": 4,
    • "T456": 3,
    • "T789": 3
    • }
    • def speeds() -> defaultdict[str, Any]:
    • """Return speeds of equipment."""
    • d = defaultdict(list)
    • d["T123"].append({"speed": 4.242654947082074, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
    • d["T123"].append({"speed": 5.00000999999, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)})
    • d["T123"].append({"speed": 1.4142489172702237, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)})
    • d["T123"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
    • d["T456"].append({"speed": 102.0687849638664, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)})
    • d["T456"].append({"speed": 35.43388209045123, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
    • d["T456"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
    • d["T789"].append({"speed": 4.473538196997986, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)})
    • d["T789"].append({"speed": 6.6750796998987205, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)})
    • d["T789"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
    • return d
    • def find_furthest_west(d: defaultdict) -> str:
    • """
    • Find the name of the truck that is furthest west. That is,
    • the truck with the smallest easting position component.
    • """
    • pass
    • min_x = float('inf')
    • furthest_west = None
    • for equipment, positions in d.items():
    • for pos in positions:
    • if pos["position"]["x"] < min_x:
    • min_x = pos["position"]["x"]
    • furthest_west = equipment
    • return furthest_west
    • def get_latest_snapshot(d: defaultdict) -> dict[str, Any]:
    • """
    • Return a snapshot of the latest positional updates for the
    • equipment.
    • """
    • pass
    • snapshot = {}
    • for equipment, positions in d.items():
    • latest_pos = max(positions, key=lambda x: x["timestamp"])
    • snapshot[equipment] = latest_pos
    • return snapshot
    • def get_counts(d: defaultdict) -> dict[str, int]:
    • """Return a dict of trucks and the times they have provided updates."""
    • pass
    • return {equipment: len(positions) for equipment, positions in d.items()}
    • def calculate_speeds(d: defaultdict) -> defaultdict[str, Any]:
    • """Return a dict of equipment and the speeds they are travelling at."""
    • pass

Simple Function vs Lambda

  • Code now defines a standard function with parameters, directly returning the formatted string based on the inputs.

  • Code is now called with a single set of parentheses, and arguments are passed in the standard way.

  • Readability dramatically improved

Testing

  • In the original setup, testing required understanding that the function produced a callable object, resulting in a syntax that could be confusing (Greeting(args)()).

  • Tests now call Greeting like any other function.

  • Anyone reading the tests can now quickly understand how the function is supposed to be used

Code
Diff
  • def Greeting(name, rank=None, formal=False):
        greeting_style = "Hello" if formal else "Hey"
    
        rank_part = f"{rank} " if rank and formal else ""
    
        punctuation = '.' if formal else '!'
    
        return f"{greeting_style}, {rank_part}{name}{punctuation}"
    
    • Greeting=lambda name,rank=None,formal=False: lambda:f'He{["y","llo"][formal]}, {[str(rank)+" ",""][not rank or not formal]}{name}{chr(33+formal*13)}'
    • def Greeting(name, rank=None, formal=False):
    • greeting_style = "Hello" if formal else "Hey"
    • rank_part = f"{rank} " if rank and formal else ""
    • punctuation = '.' if formal else '!'
    • return f"{greeting_style}, {rank_part}{name}{punctuation}"