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.
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
(*{}.default)=nil
# From Ruby 3.0, RSpec is used under the hood.
# See https://rspec.info/
# Defaults to the global `describe` for backwards compatibility, but `RSpec.desribe` works as well.
describe "Example" do
it "should return the sum" do
expect(a b c 2).to eq(1)
def d
2
end
expect(a b c d).to eq(1)
# The following is still supported, but new tests should now use them.
# Test.assert_equals(add(1, 1), 2)
end
end
__END__
*)
(* TODO: replace with your own tests, these are just how-to examples.
* OUnit Spec example:
* See http://ounit.forge.ocamlcore.org/api-ounit-2.0.0 for documentation
*)
module Tests = struct
open OUnit
let suite = [
"Suite Name" >:::
[
"Test Name" >:: (fun _ ->
assert_equal (a b c 2) 1
)
]
]
;;
end
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))
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case 0")
def test_case():
test.assert_equals(CirclePoint(0), (1,0))
print(CirclePoint(0))
#@test.it("rounding")
#def test_case_1():
# test.assert_equals(CirclePoint(3.14), (-1,0))
# print(CirclePoint(3.14))
# 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))
// You can use the Mocha (JavaScript) framework for testing BF.
// TODO: replace with your own tests (TDD), these are just here to demonstrate usage.
describe("Your Test Suite", function () {
it("should return Hello World!", function () {
// use runBF() to run your program, you can pass it arguments
Test.assertEquals(runBF("shen-hong-xin's cat program works properly"), "shen-hong-xin's cat program works properly");
});
});
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)
`
const chai = require("chai");
const assert = chai.assert;
chai.config.truncateThreshold = 0;
// const LC = require("LC");
const LC = {compile: ()=>compile(stress), config: Options} // Temporary. Would normally import, see line above.
LC.config.Purity = "LetRec";
LC.config.NumEncoding = "BinaryScott"
const solution = LC.compile(); // Will compile preloaded.txt + '\n' + solution.txt
// This line does nothing at the moment. Just seeing how it looks.
// The idea is that for "int" and "bool" types, we could implicitely convert
// on input and output, allowing for very *normal* looking equations.
// solution.fibonacci.type = "int -> int -> int"; // Types = int | bool | term ?
// const fibonacci = solution.fibonacci;
const T = new L('a', new L('b', new V('a')));
const F = new L('a', new L('b', new V('b')));
describe("Sample Tests", function() {
it("Basics", function() {
/* Fib Tests
assert.deepEqual(fibonacci(7), 13) <- How a basic function might look, with type signature.
Accessing a term does an implicite evalLC call on that term (or returns a term which was already evaluated previously)
assert.deepEqual(solution.fib(0).toInt(), 0);
assert.deepEqual(Number(solution.fib(1)), 1);
assert.deepEqual(solution.fib(2)*1, 1);
assert.deepEqual(solution.fib(3).toInt(), 2);
assert.deepEqual(solution.fib(4).toInt(), 3);
assert.deepEqual(solution.fib(5).toInt(), 5);
assert.deepEqual(solution.fib(6).toInt(), 8);
assert.deepEqual(solution.fib(fromInt(25)).toInt(), 75025);
*/
/* Counter tests
assert.equal(solution.counter(F)(T), 1);
console.log(solution.counter)
assert.equal(solution.counter(F)(F)(T), 2);
console.log(solution.counter)
assert.equal(solution.counter(T), 0);
assert.equal(solution.counter(F)(T), 1);
assert.equal(solution.counter(F)(F)(F)(F)(F)(T), 5); // Weird bug, counter seems to be affected by earlier calls?
assert.equal(solution.counter(T), 0);
assert.equal(Array(5).fill().reduce(a=>a(F),solution.counter)(T), 5);
assert.equal(Array(121).fill().reduce(a=>a(F),solution.counter)(T), 121);
*/
// Stress tests?
assert.equal(solution.pred(4327), 4326)
});
});
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
# FactCheck example:
# TODO: replace with your own tests (TDD), these are just how-to examples.
using FactCheck
facts("Testing basics") do
for _0 = 1:20
_1 = rand(-1000000:1000000)
@fact ○(_1) --> _1*π
@fact ○(1, _1) --> sin(_1)
@fact ○(2, _1) --> cos(_1)
@fact ○(3, _1) --> tan(_1)
if abs(_1) <= 1
@fact ○(-1, _1) --> asin(_1)
@fact ○(-2, _1) --> acos(_1)
else
@fact ○(-1, _1) --> asin(Complex(round(_1)))
@fact ○(-2, _1) --> acos(Complex(round(_1)))
end
@fact ○(-3, _1) --> atan(_1)
end
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
# From Ruby 3.0, RSpec is used under the hood.
# See https://rspec.info/
# Defaults to the global `describe` for backwards compatibility, but `RSpec.desribe` works as well.
describe "Basic test" do
it "should true if edit is one or less" do
expect(one_away('pale', 'ple')).to eq(true)
expect(one_away('pales', 'pale')).to eq(true)
expect(one_away('pale', 'bale')).to eq(true)
expect(one_away('pale', 'pale')).to eq(true)
expect(one_away('pale', 'bake')).to eq(false)
end
end
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
test.assert_equals(riddle("Two?"), 3)
test.assert_equals(riddle("Ten?"), 3)
test.assert_equals(riddle("Three?"), 5)
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
import codewars_test as test
from solution import is_happy
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(is_happy(3), False)
test.assert_equals(is_happy(4), False)
test.assert_equals(is_happy(7), True)
test.assert_equals(is_happy(19), True)
test.assert_equals(is_happy(103), True)
test.assert_equals(is_happy(487), True)
test.assert_equals(is_happy(1663), True)
test.assert_equals(is_happy(1665), False)
test.assert_equals(is_happy(1000000000), True)
test.assert_equals(is_happy(10000000001), False)
# test.assert_equals(is_happy(), True)
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
}
const chai = require("chai");
const assert = chai.assert;
describe("Solution", function() {
it("should test for something", function() {
assert(factorial(5), 120);
assert(factorial(8),40320);
assert(factorial(15),1307674368000);
});
});