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

It has been decided that I like Ruby.

require "net/http"
require "nokogiri"

langs = {}
langs.default = 0

(1..10).each { |page| 
  Nokogiri::XML(Net::HTTP.get(URI("https://www.codewars.com/kumite?page=#{page}")))
    .xpath("//div[contains(@class, 'flex flex-row items-center mb-4')]")
    .each { |node| 
      lang = node.xpath("string(./div[contains(@class, "\
                      "'icon-container mb-0 bg-gray-200 dark:bg-k-20')]"\
                      "/i/@class)")
      langs[lang[10...lang.length - 1]] += 1
    }
}

puts langs
def factorial(n: int) -> int:
    """Returns factorial of a non-negative integer."""
    return 1 if n <= 0 else eval('*'.join([str(i) for i in range(1, n + 1)]))

Given a projectile speed s in m/s, the angle of the initial velocity beta in degrees, and the height of the origin y, calculate the time until the projectile arrives at the ground (y=0).

Further note:

  • Assume there is no drag.
  • 0 <= s, y <= 1000, 0 <= beta <= 90,
  • The time has to be accurate to three decimals.
  • Use 9.81 m/s^2 as the gravitional acceleration.
import math

def calc_time_of_impact(speed, angle, origin_y):

    x_value = 0
    y_value = 0
    time = 0.0001

    def x_formula(t): return speed * t * \
        math.cos(angle * math.pi / 180)

    def y_formula(t): return speed * t * \
        math.sin(angle * math.pi / 180) - 9.81/2*t*t

    while y_value >= -origin_y:
        x_value = x_formula(time)
        y_value = y_formula(time)
        time += 0.0001

    return time

Ruby sometimes feels like the least functional possible language.
I don't fully understand what's going on in that first line, I figured it out after having a nice chat with irb syntax errors about what it expects of me.

(*{}.default)=nil

def a(x)
  puts "a #{x}"
  8 / x
end

def b(x)
  puts "b #{x}"
  2 * x
end

def c(x)
  puts "c #{x}"
  2 + x
end

puts a b c 2

__END__
*)

let a x y z =
  print_endline "a";
  8 / x y z
;;

let b y z =
  print_endline "b";
  2 * y z
;;

let c z =
  print_endline "c";
  2 + z
;;

print_endline @@ string_of_int @@ a b c 2

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