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.
With the power of regex it becomes easy to tell if your string has even length!
class StringParity {
public static boolean isEvenLength(String str) {
return str.replaceAll("(?s)..", "").isEmpty(); // (?s) enables DOTALL
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SolutionTest {
@Test
void testSomething() {
assertEquals(true, StringParity.isEvenLength("even"));
assertEquals(false, StringParity.isEvenLength("odd"));
assertEquals(true, StringParity.isEvenLength(""));
assertEquals(false, StringParity.isEvenLength("Instant Noodles"));
assertEquals(true, StringParity.isEvenLength("\n\n"));
}
}
In this simple exercise, you will build a program that takes a value, integer , and returns a list of its multiples up to another value, limit . If limit is a multiple of integer, it should be included as well. There will only ever be positive integers passed into the function, not consisting of 0. The limit will always be higher than the base.
For example, if the parameters passed are (2, 6), the function should return [2, 4, 6] as 2, 4, and 6 are the multiples of 2 up to 6.
If you can, try writing it in only one line of code.
def find_multiples(b, l):
a=[]
for i in range(b,l+1,b):
a.append(i)
return a
import codewars_test as test
from solution import find_multiples
@test.describe("Fixed Tests")
def fixed_tests():
@test.it('Basic Test Cases')
def basic_test_cases():
test.assert_equals(find_multiples(5, 25), [5, 10, 15, 20, 25])
test.assert_equals(find_multiples(1, 2), [1, 2])
test.assert_equals(find_multiples(6, 30), [6, 12, 18, 24, 30])
...
import codewars_test as test
import threading
import queue
class it:
def __init__(self, title):
self.title = title
def __enter__(self, *_whatever):
# I'm sure there's a more suitable sync primitive, but, hey, queues.
self.wait = queue.Queue()
entered = queue.Queue()
self.exited = queue.Queue()
def hodor():
@test.it(self.title)
def impostor():
entered.put(())
self.wait.get()
self.exited.put(())
threading.Thread(target=hodor).start()
entered.get()
def __exit__(self, *_whatever):
self.wait.put(())
self.exited.get()
# same as `it`, copy pasted out of laziness
class describe:
def __init__(self, title):
self.title = title
def __enter__(self, *_whatever):
# I'm sure there's a more suitable sync primitive, but, hey, queues.
self.wait = queue.Queue()
entered = queue.Queue()
self.exited = queue.Queue()
def hodor():
@test.describe(self.title)
def impostor():
entered.put(())
self.wait.get()
self.exited.put(())
threading.Thread(target=hodor).start()
entered.get()
def __exit__(self, *_whatever):
self.wait.put(())
self.exited.get()
def taste():
return 'black'
with describe("Help! I'm being oppressed"):
with describe("Once upon a time ..."):
with it("should taste like purple"):
test.assert_equals(taste(), "purple")
with it("should taste like black"):
test.assert_equals(taste(), "black")
with describe("Should things exist?"):
with it("yes."):
test.expect(True)
with it("nah."):
test.expect(False)
Given two numbers, you must create a list of N items that alternates between one and the other.
Example:
If the input is "first_number"=2, "second_number"=5, "elements_on_list"=10,"range_begins_at"=0 the output should be:
[2, 5, 2, 5, 2, 5, 2, 5, 2, 5]
If the input is "first_number"=10, "second_number"=7, "elements_on_list"=23,"range_begins_at"=0 the output should be:
[10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10]
def generate_binay_list(first_number,second_number,elements_on_list,range_begins_at):
return [first_number if x%2==0 else second_number for x in range(range_begins_at, elements_on_list)]
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
test_classes=[]
class test_class():
def __init__(self,first_number,second_number,elements_on_list,range_begins_at,expected):
self.first_number=first_number
self.second_number=second_number
self.elements_on_list=elements_on_list
self.range_begins_at=range_begins_at
self.expected=expected
test_classes.append(test_class(2,5,10,0,[2, 5, 2, 5, 2, 5, 2, 5, 2, 5]))
test_classes.append(test_class(10,7,23,0,[10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10]))
test_classes.append(test_class(0,0,0,0,[]))
test_classes.append(test_class(-7,14,-3,0,[]))
test_classes.append(test_class(-7,14,-3,-7,[14, -7, 14, -7]))
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
for obj in test_classes:
result=generate_binay_list(obj.first_number,obj.second_number,obj.elements_on_list,obj.range_begins_at)
test.assert_equals(result,obj.expected)
add two numbers
public class Kumite {
public static int add(int x, int y) {
return x+y;
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
// TODO: Replace examples and use TDD by writing your own tests
class SolutionTest {
@Test
void normalTests() {
// assertEquals("expected", "actual");
assertEquals(4+5,Kumite.add(4,5));
}
}
- This function takes colors as arguments in the only RGBA
- @param {String} positiveColor
- @param {String} negativeColor
- @param {String} neutralColor
- @return {Function} Which takes a percentage as an argument and returns the color depending on the percentage passed
const calculateColor = ({ positive: positiveColor, negative: negativeColor, neutral: neutralColor }) => {
return percent => {
const absoluteValueOfNumber = Math.sign(percent)
const startPercent = 100
const opacityNeutral = 0.5
const opacityMinimal = 0.25
const isOpacityMinimal = val => val <= opacityMinimal
if (absoluteValueOfNumber === 1) {
const opacity = percent / startPercent
if (isOpacityMinimal(opacity)) {
return assignOpacity(positiveColor, opacityMinimal)
}
return assignOpacity(positiveColor, opacity)
}
if (absoluteValueOfNumber === -1) {
const opacity = Math.abs(percent) / startPercent
if (isOpacityMinimal(opacity)) {
return assignOpacity(negativeColor, opacityMinimal)
}
return assignOpacity(negativeColor, opacity)
}
if (absoluteValueOfNumber === 0) {
return assignOpacity(neutralColor, opacityNeutral)
}
}
}
function assignOpacity (color, value) {
const colorArr = color.split(',').reverse()
const opacity = colorArr[0]
const bracket = opacity[opacity.length - 1]
colorArr[0] = value + bracket
return colorArr.reverse().join()
}
// Since Node 10, we're using Mocha.
// You can use `chai` for assertions.
const Test = require("@codewars/test-compat");
const chai = require("chai");
const assert = chai.assert;
const colors = {
positive: 'rgba(178, 245, 211, 1)',
negative: 'rgba(255, 170, 170, 1)',
neutral: 'rgba(255, 255, 255, 1)',
}
const cc = calculateColor(colors);
// Uncomment the following line to disable truncating failure messages for deep equals, do:
// chai.config.truncateThreshold = 0;
// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
// Uncomment the following to use the old assertions:
// const Test = require("@codewars/test-compat");
describe("Solution", function() {
it("should test for check colors", function() {
Test.assertEquals( cc(16), 'rgba(178, 245, 211,0.25)');
Test.assertEquals( cc(50), 'rgba(178, 245, 211,0.5)');
Test.assertEquals( cc(-50), 'rgba(255, 170, 170,0.5)');
// Test.assertEquals(1 + 1, 2);
// assert.strictEqual(1 + 1, 2);
});
});
const unknown = 'Unknown error'
const catalog = {
en: {
ERROR_USER_NOT_FOUND: 'Error: User not found',
ERROR_500: 'Internal Server Error',
},
ru: {
ERROR_USER_NOT_FOUND: 'Ошибка: Пользователь не найден',
}
}
const catalogProvider = locale => error => catalog[locale][error] || unknown
// Since Node 10, we're using Mocha.
// You can use `chai` for assertions.
const chai = require("chai");
const assert = chai.assert;
const Test = require("@codewars/test-compat");
// Uncomment the following line to disable truncating failure messages for deep equals, do:
// chai.config.truncateThreshold = 0;
// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
// Uncomment the following to use the old assertions:
describe("Solution with EN locale", function() {
const cp = catalogProvider('en');
it("should test for something", function() {
Test.assertEquals( cp('ERROR_USER_NOT_FOUND'), 'Error: User not found');
Test.assertEquals( cp('ERROR_500'), 'Internal Server Error');
// Test.assertEquals(1 + 1, 2);
// assert.strictEqual(1 + 1, 2);
});
});
describe("Solution with RU locale", function() {
const cp = catalogProvider('ru');
it("should test for something", function() {
Test.assertEquals( cp('ERROR_USER_NOT_FOUND'), 'Ошибка: Пользователь не найден');
Test.assertEquals( cp('ERROR_500'), 'Unknown error');
// Test.assertEquals(1 + 1, 2);
// assert.strictEqual(1 + 1, 2);
});
});
#include <iostream>
#include <range/v3/view/take.hpp>
#include <range/v3/view/all.hpp>
int func(){
std::vector<int> vec = {4, 5, 6, 10};
auto stuff = ranges::views::all(vec) | ranges::views::take(2);
for(auto x: stuff)
std::cout << x << std::endl;
return 0;
}
Describe(any_group_name_you_want)
{
It(should_do_something)
{
Assert::That(func(), Equals(0));
}
};
const normalizeChance = (items) => items
.reduce((acc, current, i) => {
const last = acc [i-1];
return [
...acc,
{
...current,
chance: current.chance + (last ? last.chance : 0)
},
];
}, []);
const raffel = (rng, items) => {
const normalizedItems = normalizeChance(items);
if(normalizedItems[normalizedItems.length-1].chance !== 1) throw new Error("Sum of chance should be equal to 1")
return () => {
const winningNumber = rng();
const item = normalizedItems
.find(({ chance }) => winningNumber <= chance)
return {
...item,
winningNumber,
}
}
}
// Since Node 10, we're using Mocha.
// You can use `chai` for assertions.
const chai = require("chai");
const assert = chai.assert;
// Uncomment the following line to disable truncating failure messages for deep equals, do:
// chai.config.truncateThreshold = 0;
// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
// Uncomment the following to use the old assertions:
// const Test = require("@codewars/test-compat");
describe("Solution", function() {
const valuesToTest = [
[ 0.19485818770228258, "a" ],
[ 0.33340000000000000, "a" ],
[ 0.33350000000000000, "b" ],
[ 0.66660000000000000, "b" ],
[ 0.66670000000000000, "b" ],
[ 0.66680000000000000, "c" ],
[ 0.99990000000000000, "c" ],
[ 1.00000000000000000, "c" ],
]
valuesToTest.forEach(([ winningNumber, winnerName ]) => {
it(`return winner ${winnerName} for ${winningNumber}`, function() {
const rng = () => winningNumber
const winner = raffel(rng, [
{ name: "a", chance: 0.3334 },
{ name: "b", chance: 0.3333 },
{ name: "c", chance: 0.3333 },
])()
assert.equal(winner.name, winnerName)
});
});
it("throws when sum of chances > 1", function() {
const rng = () => 0.19485818770228258
try {
raffel(rng, [
{ name: "a", chance: 0.3334 },
{ name: "b", chance: 0.3333 },
{ name: "c", chance: 0.3334 },
]);
throw new Error("Did not throw");
} catch (e) {
assert.equal(e.message, "Sum of chance should be equal to 1");
}
})
it("throws when sum of chances < 1", function() {
const rng = () => 0.19485818770228258
try {
raffel(rng, [
{ name: "a", chance: 0.3333 },
{ name: "b", chance: 0.3333 },
{ name: "c", chance: 0.3333 },
]);
throw new Error("Did not throw");
} catch (e) {
assert.equal(e.message, "Sum of chance should be equal to 1");
}
})
it("works with Math.random", function() {
const winner = raffel(Math.random, [
{ name: "a", chance: 0.3334 },
{ name: "b", chance: 0.3333 },
{ name: "c", chance: 0.3333 },
])();
assert.isTrue(["a", "b", "c"].includes(winner.name))
})
it("1 million raffles distribuition with Math.random", function() {
const total = 1000000;
let i = 0;
const winners = [];
const myRaffel = raffel(Math.random, [
{ name: "a", chance: 0.3334 },
{ name: "b", chance: 0.3333 },
{ name: "c", chance: 0.3333 },
])
while(i < total - 1) {
i = i + 1
winners.push(myRaffel());
};
const sum = winners.reduce((acc, { name }) => {
acc[name] = (acc[name] ? acc[name] : 0) + 1
return acc
}, {});
const result = Object.entries(sum).map(([ name, winners ]) => ({ name, winners, percent: winners/(total*1.0) }))
console.log(result);
})
});
Your task is to remove every second char in a string.
Example:
removeEverySecond('hello world'); // 'hlowrd'
removeEverySecond('how you doing') // 'hwyudig'
function removeEverySecond(str) {
return [...str].filter((_,i) => !(i%2)).join``;
}
const chai = require("chai");
const assert = chai.assert;
describe("Solution", function() {
it("should test for something", function() {
assert.strictEqual(removeEverySecond('hello world'), 'hlowrd');
assert.strictEqual(removeEverySecond('how you doing'), 'hwyudig');
assert.strictEqual(removeEverySecond('abc'), 'ac');
assert.strictEqual(removeEverySecond(''), '');
assert.strictEqual(removeEverySecond('1234 56789 10112314'), '13 68 0134');
});
});