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

Mathmatical simplification of sin and cosine? Only 2 decimal places of accuracy required.

import math

def CirclePoint(angle):
    return (math.cos(angle), math.sin(angle))
# no cheating methods such as eval exec 
# has the same relevant chars (nothing hidden in comment)

from __future__ import braces # 深紅心 is excited to see braces in python

from operator import itemgetter
from operator import getitem
from operator import setitem
from sys import stdout
from sys import argv

def kata(sin):
    class _:
        def __init__(self):
            pass
        def __lt__(*self):
            assert ptr
            mask = 1
            while not ptr & mask:
                mask *= 2
                mask |= 1
            ptr ^= mask
        def __gt__(*self):
            ptr = abs(~ptr)
        def __iter__(self):
            return self
        def __next__(self):
            if not itemgetter(ptr)(tape):
               raise StopIteration
    def idxs(option):
        if type(option) == dict:
            for x in option:
                yield x
                yield from idxs(itemgetter(x)(option))
        else:
            yield option
    tape = 30000 * list(range(1))
    ptr = 0
    sinptr = ~0

    setitem(*reversed(tuple(idxs(
        {ord(getitem(sin, sinptr := abs(~sinptr))): {ptr: tape}}))))
    setitem(*reversed(tuple(idxs(
        {itemgetter(ptr)(tape) + 1 & 0xff: {ptr: tape}}))))
    [setitem(*reversed(tuple(idxs(
        {itemgetter(ptr)(tape) - 1 & 0xff: {ptr: tape}}))))
    or stdout.write(chr(itemgetter(ptr)(tape))) and False
    or setitem(*reversed(tuple(idxs(
        {ord(getitem(sin, sinptr := abs(~sinptr))): {ptr: tape}}))))
    or setitem(*reversed(tuple(idxs(
        {itemgetter(ptr)(tape) + 1 & 0xff: {ptr: tape}}))))
    for _0 in _()]

if __name__ == "__main__":
    # pretty much stdin, right? right??
    kata(itemgetter(1)(argv))

Proof of Concept LC compiler and native tester in JS

How to use

  • Import the module const LC = require('LC')
  • Set any config options
  • Generate compiled user solution with LC.compile()
  • Test using normal JS test suite (Mocha)

The Kumite

In the kumite, Preloaded is used in place of the final module (in a real kata, Preloaded will simply be prepended to Solution before compilation). The constants in Code represent potential user solutions. Test Cases are as they would (potentially) appear in a real kata.

How it Works

User solutions are first parsed into term trees of Applications, Abstractions and Variables. The result is passed to evalLC which compiles.

stack is simulating recursive calls. It stores bound variable information, as well as the right hand side of applications (A) which are awaiting a value to bind to. boundVars is a Map keeping track of our environment (bound variables).

If the top term is a variable (V) we switch to the term and environment to which our variable's name is bound in boundVars

if the top term is an application (A) we pack the right term of the application, and the current environment (boundVars) into the stack, and move into the left term.

If the top term is an abstraction (L), we remove the last element of the stack. We bind it and its environment to our term's name (within boundVars), then move into the body of our term. If there is nothing in stack, then we are waiting for an input, so we pack our current environment into a function and return that, so when an argument is passed, it continues right where we left off.

Other languages

Here JS serves only as a 'host' and testing language, so other languages could likely be supported for authors who prefer it. Progress is being made on a Haskell version currently.

To do:

  • Write some large "katas" for stress testing
  • Add verbosity options
  • Construct a toString() method that applies environment variables
  • Write better errors for bad parsing
const text = String.raw`
succ = \n f x. f (n f x)
pair = \a.\b.\c.c a b
fst = \pair.pair (\a.\_.a)
snd = \pair.pair (\_.\b.b)
plus = \pair.\f.\x.(fst pair) f ((snd pair) f x)
next = \prev.pair (snd prev) (plus prev)
fib = \n. fst (n next (pair (\_.\b.b) (succ (\_.\b.b))))
`

// Proof of laziness -- using Scott
const lazy = String.raw`
succ = \ n _ f . f n
inf_list = \ n b . b n (inf_list (succ n))
counter = inf_list 0
`

// Stress testing -- "LetRec", "BinaryScott"
// Testing implementation of a "String" - ie. Arrays and related functions
const stress = String.raw`
# bools
true = \ a b . a
false = \ a b . b
not = \ b . b false true
and = \ a b . a b false
or = \ a b . a true b
xor = \ a b . a (b false true) b

# ints -- z = endbit, f = offbit, t = onbit
zero = \ z _ _ . z
succ = \ n _ f t . n (t zero) t (\ m . f (succ m))
pred = \ n z f t . n z (\ m . t (pred m)) f
bool = \ n . n false (\ _ . true) (\ _ . true)
odd = \ n . n false false true
even = \ n . not (odd n)
mul2 = \ n _ f _ . f n
addSlow = \ a b . bool b (addSlow (succ a) (pred b)) a
subSlow = \ a b . bool a (bool b (subSlow (pred a) (pred b)) a) (zero)

# arrays as foldr (strings)
`

It doesn't seem to be one of the Julia magic operators, so it's called like a normal function in this Kumite.
For reasons unknown, \bigcirc doesn't work in Codewars, shouldn't matter too much though.
Only sometimes returns Complex, as I think this imitates APL the best.

○(x)=π*x;○(t,x)=try(atan,acos,asin,0,sin,cos,tan)[t+4](x)catch;(asin,acos)[-t](Complex(round(x)))end

There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.
Example:
pale, ple -> true
pales, pale -> true
pale, bale -> true

def one_away(a,b)
  (a.split('')-b.split('')).count <= 1 ? true : false
end
Fundamentals
Games

You are spying on a club to try to guess the password! You see one man walk up to the guard. The guard asks him "Two?" the man answers with "three", and the guard lets him in. A little while later, another man walks up to the guard and the guard asks him "Ten?" The man answers with "three" and he gets let in. A bit later, another man walks up to the guard, and he asks him "Four?" the man says "three" but the guard doesn't let him in and the man leaves.

Can you figure out the code?

def riddle(word):
    return len(word) - 1
Mathematics
Algorithms
Logic
Numbers
Data Types

Find Happy numbers

A number h is happy when iteratively summing the squares of its digits eventually leads 1.
For example 7 is happy because

7^2 = 49 -> 4^2 + 9^2 = 97 -> 9^2 + 7^2 = 130 -> 1^2 + 3^2 + 0^2 = 10 -> 1^2 + 0^2 = 1.

Similarly, 3 is unhappy, because 3^2 = 9.

Task

Write a function is_happy returning True if its integer input h is happy.

def is_happy(h: int) -> bool:
    """Returns `True` if `h` is happy, `False` otherwise."""
    seen = set()
    while h > 1 and h not in seen:
        seen.add(h)
        tot = 0
        while h > 0:
            tot += pow(h % 10, 2)
            h //= 10
        h = tot
    return h == 1

I have to learn JQuery, and I thought I might as well do something fun with it to practice. This can be considered an advanced Hello World.
This makes extremely popular Kumite easier to look through without the need of opening new tabs with different roots or whatever it is you're expected to do.
While testing this, I noticed there are a few div.nested-items elements that have nothing inside them. I suspect that this is the result of Kumite being removed in some way.
Things I want to add at soem point:
Elements containing the code of each individual Kumite that can be popped out and viewed like a window.
A tool taking two of these windows and showing the diff between them.
Something useful for comparing different solutions for code golf Kumite.
A simple query system for searching for Kumite of given languages or fitting certain criteria, meant to allow the button for unhiding elements to indicate whether something fitting is being hidden.
Hopefully this part of the site does not completely die by the time I'm satisfied with this.

(function(x){
  x.src="https://code.jquery.com/jquery-3.6.0.min.js";
  document.querySelector("head").appendChild(x);
})(document.createElement("script"));

$("<button>[ - - ! - - ]</button>")
  .insertBefore(".nested-items")
  .click(function(){$(this).next().toggle();});

The factorial of a number is the product of all the numbers from 1 to that number

Like factorial of 3 would be 1 x 2 x 3

function factorial (n) {
  if (n <= 0) return 0
  
  let i = fact = 1
  while (i <= n) { 
  fact *= i
  i++
  }
  return fact
  
}

It's binarySearch implementation on JS. This returns the index number that contains the value. If the value is not in the array, it will return -1

function binarySearch(arr, el) {
  let left = -1;
  let right = arr.length;
  
  while (right - left > 1) {
    const mid = Math.floor((left + right) / 2);  
    if (arr[mid] === el) {
      return mid;
    }
    if (arr[mid] > el) {
      right = mid;
    } else {
      left = mid;
    }
  }
  return -1;
}