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.
Create a function to return True if the number is even and False if odd.
e.g. check_even(2) => True, check_even(9) => False
check_even = lambda x: x%2==0
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Test1")
def test_group():
@test.it("test true: 2")
def test_case():
test.assert_equals(check_even(2), True)
@test.describe("Test2")
def test_group():
@test.it("test false: 5")
def test_case():
test.assert_equals(check_even(5), False)
@test.describe("Test3")
def test_group():
@test.it("test false: 11")
def test_case():
test.assert_equals(check_even(11), False)
@test.describe("Test4")
def test_group():
@test.it("test true: 22")
def test_case():
test.assert_equals(check_even(22), True)
Your task is to find the minimum SQUARE area in which you can place two identical rectangles. The sides of the rectangles should be parallel to the sides of the square.
- You are given two identical rectangles with side lengths
a
andb
with1 <= a, b <= 100
. - Find the square with minimum area that contains both given rectangles. Rectangles can be rotated (both or just one) and moved, but the sides of the rectangles should be parallel to the sides of the desired square.
def minimal_square(a, b):
return max(min(a, b)*2, max(a, b))**2
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Simple tests")
def test_group():
@test.it("Test 1")
def test_case1():
test.assert_equals(minimal_square(2, 3), 16)
@test.it("Test 2")
def test_case2():
test.assert_equals(minimal_square(3, 7), 49)
Given an integer array and an positive integer variable, find the maximum or largest product you get after multiplying it by the elements in the array.
Input: arr = {1,2,3};
num = 3;
Output: 6
Because, 3 * 2 = 6
class Kata1 {
public static int maxPairProduct(int[] arr, int num) {
//Never Gonna Give You Up, Never Gonna Let You Down, Never Gonna Run Around And Desert You!
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD by writing your own tests
public class SolutionTest {
@Test
public void testSomething() {
// assertEquals("expected", "actual");
int[] arr1 = {1,2,3};
int[] arr2 = {5,8,3,7,10};
int[] arr3 = {21,34,2,12,65,4};
assertEquals(6, Kata1.maxPairProduct(arr1, 3));
assertEquals(80, Kata1.maxPairProduct(arr2,8));
assertEquals(780, Kata1.maxPairProduct(arr3, 12));
}
}
Basics
Verlan is a type of argot in the french language and is common in slang and youth language.
It rests on a long french tradition of transposing syllables of individual words to create slang words.
The word itself is an example for verlan.
Task
In this example you will create a function that takes a word and makes a verlan word out of it.
e.g.
- Maestro => Stromae
- Verlan => Lanver
function maestroSplit(string) {
let newWord = string.slice(parseInt(string.length / 2)) + string.slice(0, parseInt(string.length / 2));
return newWord.toLowerCase().charAt(0).toUpperCase() + newWord.toLowerCase().slice(1);
}
// 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("maestroSplit", function() {
it("should transform verLan to Lanver", () => {
Test.assertEquals(maestroSplit("verLan"), "Lanver");
});
it("should transform français to Çaisfran", () => {
Test.assertEquals(maestroSplit("français"), "Çaisfran");
});
it("should transform Maestro to Stromae", () => {
// Test.assertEquals(1 + 1, 2);
// assert.strictEqual(1 + 1, 2);
Test.assertEquals(maestroSplit("Maestro"), "Stromae");
});
it("should transform MaEsTrO to Stromae", () => {
Test.assertEquals(maestroSplit("MaEsTrO"), "Stromae");
});
it("should transform warscode to Codewars", () => {
Test.assertEquals(maestroSplit("wArScODE"), "Codewars");
});
});
Given the following numbers:
100 75 50 25 6 3
and the following operators:
(*) (-) (+) (/)
build an Expression
, that yields 952
when it is evaluated (evaluate
applies all the operators bottom - up)
Doubles are used for convenience, number is rounded and checked against an integer to mitigate floating point error that might accumulate.
module Example (solve, Expression(Value, Expr)) where
data Expression = Value Double | Expr Expression (Double -> Double -> Double) Expression
solve :: [Double] -> Expression
--solve = undefined
--- my brute-force solution
solve xs = head . filter validate . allExpressions os . allOrders $ xs
where os = getPermutationsAtDepth (length xs - 1) ops
evaluate :: Expression -> Double
evaluate (Value x) = x
evaluate (Expr i o j) = (evaluate i) `o` (evaluate j)
validate :: Expression -> Bool
validate = (==952) . round . evaluate
-- ok because all the numbers are unique
removed :: Eq a => a -> [a] -> [a]
removed x = filter (/=x)
allOrders :: Eq a => [a] -> [[a]]
allOrders [x] = [[x]]
allOrders xs = concat [ [ x:ns | ns <- allOrders (removed x xs)] | x <- xs]
ops = [(*), (-), (+), (/)] :: [Op]
type Op = Double -> Double -> Double
data NodeTree a = Node a [NodeTree a] | Leaf a deriving (Show)
genTree :: a -> [a] -> Int -> NodeTree a
genTree root es 1 = Node root (map Leaf es)
genTree root es depth = Node root (map (\x -> genTree x es (depth-1)) es)
getPaths :: NodeTree a -> [[a]]
getPaths (Leaf x) = [[x]]
getPaths (Node r xs) = concat [ [ r:t | t <- getPaths c] | c <- xs]
getPermutationsAtDepth :: Int -> [a] -> [[a]]
getPermutationsAtDepth 1 xs = [xs]
getPermutationsAtDepth depth xs = concat . map getPaths . map (\x -> genTree x xs d) $ xs where d = depth - 1
toExpression :: [Op] -> [Double] -> Expression
toExpression _ [] = error "should not be more operators than values!"
toExpression [] [e] = Value e
toExpression (o:os) (e:es) = Expr (Value e) o (toExpression os es)
allExpressions :: [[Op]] -> [[Double]] -> [Expression]
allExpressions os es = [toExpression o e | o <- os, e <- es]
module ExampleSpec where
-- Tests can be written using Hspec http://hspec.github.io/
-- Replace this with your own tests.
import Test.Hspec
import Example
import Data.List
numbers = [100, 75, 50, 25, 6, 3] :: [Double]
collectNums :: Expression -> [Double]
collectNums (Value x) = [x]
collectNums (Expr x _ y) = collectNums x ++ collectNums y
evaluate :: Expression -> Double
evaluate (Value x) = x
evaluate (Expr i o j) = (evaluate i) `o` (evaluate j)
validate :: Expression -> Bool
validate = (==952) . round . evaluate
-- `spec` of type `Spec` must exist
spec :: Spec
spec = do
describe "get the solution" $ do
it "must use each number once and only once" $ do
(sort . collectNums . solve $ numbers) `shouldBe` (sort numbers)
it "must equal 952" $ do
-- round because of floating point error
(round . evaluate . solve $ numbers) `shouldBe` (952 :: Int)
-- the following line is optional for 8.2
main = hspec spec
Write a function that will solve a 9x9 Sudoku puzzle. The function will take one argument consisting of the 2D puzzle array, with the value 0 representing an unknown square.
The Sudokus tested against your function will be "easy" (i.e. determinable; there will be no need to assume and test possibilities on unknowns) and can be solved with a brute-force approach.
For Sudoku rules, see the Wikipedia article.
const int sudoku[9][9] = {
{0,0,0,0,0,0,6,0,0},
{0,0,0,0,0,7,0,0,1},
{2,0,8,0,0,0,0,4,0},
{6,0,0,0,0,0,0,0,0},
{0,5,1,4,0,9,0,0,0},
{0,0,0,5,0,0,0,2,0},
{0,0,4,0,0,0,0,5,0},
{0,0,7,1,9,6,0,0,0},
{0,8,0,0,0,0,3,0,0},
};
#include <stddef.h>
typedef int (*T)[9];
T solve (const T sudoku) {
/* Write your code here */
return NULL;
}
// TODO: Replace examples and use TDD by writing your own tests. The code provided here is just a how-to example.
#include <criterion/criterion.h>
#include <stdbool.h>
typedef int (*T)[9];
extern T solve(const int (*)[9]);
const int a[9][9] = {
{0,0,0,0,0,0,6,0,0},
{0,0,0,0,0,7,0,0,1},
{2,0,8,0,0,0,0,4,0},
{6,0,0,0,0,0,0,0,0},
{0,5,1,4,0,9,0,0,0},
{0,0,0,5,0,0,0,2,0},
{0,0,4,0,0,0,0,5,0},
{0,0,7,1,9,6,0,0,0},
{0,8,0,0,0,0,3,0,0},
};
const int b[9][9] = {
{0,0,0,0,0,6,6,0,0},
{0,0,0,0,0,7,0,0,1},
{2,0,8,0,0,0,0,4,0},
{6,0,0,0,0,0,0,0,0},
{0,5,1,4,0,9,0,0,0},
{0,0,0,5,0,0,0,2,0},
{0,0,4,0,0,0,0,5,0},
{0,0,7,1,9,6,0,0,0},
{0,8,0,0,0,0,3,0,0},
};
bool check( int(*x)[9] );
Test(the_multiply_function, should_pass_all_the_tests_provided) {
cr_assert_eq(check(solve(a)), true);
cr_assert_eq(solve(b), NULL);
}
bool check( int(*x)[9] ) {
if(!x) return false;
for(int i=0;i<9;i++){
for(int j=0,k[9]={0};j<9;j++){
if(!x[i][j])return false;
if(k[x[i][j]-1])return false;
else k[x[i][j]-1] = 1;
}
for(int j=0,k[9]={0};j<9;j++)
if(k[x[j][i]-1])return false;
else k[x[j][i]-1] = 1;
}
for(int i=0;i<3;i++)for(int j=0;j<3;j++)
for(int m[9]={0},k=0;k<3;k++)for(int l=0;l<3;l++)
if(m[x[i*3+k][j*3+l]-1])return false;
else m[x[i*3+k][j*3+l]-1] = 1;
return true;
}
test
public class test{
public void testSomething(){
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD by writing your own tests
public class SolutionTest {
@Test
public void testSomething() {
// assertEquals("expected", "actual");
}
}
Recovering a type as a string, working with GCC, Clang & MSVC.
getTypeStr<const int*>() // Returns "const int*"
getTypeStr<decltype("Hello world!")>() // Returns "const char (&)[13]"
Each type string may vary according to the compiler's formatting style.
template <typename T>
constexpr std::string_view getTypeStr() noexcept {
#if defined(__clang__)
// Has the form "std::string_view getTypeStr() [T = ...]"
constexpr std::string_view funcSignature = __PRETTY_FUNCTION__;
constexpr std::size_t startStride = std::size("std::string_view getTypeStr() [T = ") - 1;
return std::string_view(funcSignature.data() + startStride, funcSignature.size() - startStride - 1);
// The following implementation would be ideal, but can't be resolved at compile-time (yet?)
// See: https://stackoverflow.com/questions/56484834/constexpr-stdstring-viewfind-last-of-doesnt-work-on-clang-8-with-libstdc
// constexpr std::size_t firstPos = funcSignature.find_first_of('=');
// static_assert(firstPos != std::string_view::npos, "Error: Character '=' not found in the function's signature.");
//
// constexpr std::size_t lastPos = funcSignature.find_last_of(']');
// static_assert(lastPos != std::string_view::npos, "Error: Character ']' not found in the function's signature.");
//
// static_assert(firstPos < lastPos, "Error: Trailing character found before leading one in the function's signature.");
//
// return std::string_view(funcSignature.data() + firstPos + 2, lastPos - firstPos - 2);
#elif defined(__GNUC__)
// Has the form "constexpr std::string_view getTypeStr() [with T = ...; std::string_view = std::basic_string_view<char>]"
constexpr std::string_view funcSignature = __PRETTY_FUNCTION__;
constexpr std::size_t firstPos = funcSignature.find_first_of('=');
static_assert(firstPos != std::string_view::npos, "Error: Character '=' not found in the function's signature.");
constexpr std::size_t lastPos = funcSignature.find_first_of(';', firstPos);
static_assert(lastPos != std::string_view::npos, "Error: Character ';' not found in the function's signature.");
static_assert(firstPos < lastPos, "Error: Trailing character found before leading one in the function's signature.");
return std::string_view(funcSignature.data() + firstPos + 2, lastPos - firstPos - 2);
#elif defined(_MSC_VER)
// Has the form "class std::basic_string_view<char,struct std::char_traits<char> > __cdecl getTypeStr<...>(void) noexcept"
constexpr std::string_view funcSignature = __FUNCSIG__;
constexpr std::size_t startStride = std::size("class std::basic_string_view<char,struct std::char_traits<char> > __cdecl getTypeStr<") - 1;
constexpr std::size_t endStride = std::size(">(void) noexcept") - 1;
return std::string_view(funcSignature.data() + startStride, funcSignature.size() - startStride - endStride);
// The following implementation would be ideal, but can't be resolved at compile-time because of a bug fixed only recently
// See: https://developercommunity.visualstudio.com/content/problem/331234/stdbasic-string-viewfind-is-not-always-constexpr.html
// constexpr std::string_view funcName = __FUNCTION__;
//
// constexpr std::size_t firstPos = funcSignature.find(funcName);
// static_assert(firstPos != std::string_view::npos, "Error: Function name not found in the function's signature.");
//
// constexpr std::size_t lastPos = funcSignature.find_last_of('>');
// static_assert(lastPos != std::string_view::npos, "Error: Character '>' not found in the function's signature.");
//
// static_assert(firstPos < lastPos, "Error: Trailing character found before leading one in the function's signature.");
//
// return std::string_view(funcSignature.data() + firstPos + funcName.size(), lastPos - firstPos - funcName.size());
#else
static_assert(false, "Error: The current compiler is not supported.");
#endif
}
Describe(type_str)
{
It(basic)
{
int testInt {};
const int& testIntRef = testInt;
Assert::That(getTypeStr<int>(), Equals("int"));
Assert::That(getTypeStr<decltype(testInt)>(), Equals("int"));
#if defined(__clang__)
Assert::That(getTypeStr<const int*>(), Equals("const int *"));
Assert::That(getTypeStr<decltype(testIntRef)>(), Equals("const int &"));
Assert::That(getTypeStr<decltype("Hello world!")>(), Equals("char const (&)[13]"));
Assert::That(getTypeStr<std::string_view>(), Equals("std::basic_string_view<char, std::char_traits<char> >"));
#elif defined(__GNUC__)
Assert::That(getTypeStr<const int*>(), Equals("const int*"));
Assert::That(getTypeStr<decltype(testIntRef)>(), Equals("const int&"));
Assert::That(getTypeStr<decltype("Hello world!")>(), Equals("const char (&)[13]"));
Assert::That(getTypeStr<std::string_view>(), Equals("std::basic_string_view<char>"));
#elif defined(_MSC_VER)
Assert::That(getTypeStr<const int*>(), Equals("const int*"));
Assert::That(getTypeStr<decltype(testIntRef)>(), Equals("const int&"));
Assert::That(getTypeStr<decltype("Hello world!")>(), Equals("const char(&)[13]"));
Assert::That(getTypeStr<std::string_view>(), Equals("class std::basic_string_view<char,struct std::char_traits<char> >"));
#endif
}
};
Now you are going to make a simple calculator.
The expression will be like this: n {symbol} m = {return value};
Example:
int result = calculate(4, 5, +); // 4 + 5 = 9;
Symbols are +, -, *.
public class calculator {
public static int calculate(int n, int m, char symbol) {
// do your best :)
int result = 0;
switch(symbol) {
case '+':
result = n + m;
break;
case '-':
result = n - m;
break;
case '*':
result = n * m;
break;
}
return result;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD by writing your own tests
public class SolutionTest {
@Test
public void testSomething() {
assertEquals(9, calculator.calculate(4, 5, '+'));
assertEquals(7, calculator.calculate(12, 5, '-'));
assertEquals(60, calculator.calculate(20, 3, '*'));
}
}
Mindbend is BF with extra steps.
What if BF had named registers? More operations? What if we fused that with assembly?
This is Mindbend, a silly little interpreter I made in an hour or two killing time on a Friday at school.
Basic rundown
There are 26 registers, a - z.
Each register is a 32-bit integer.
Commands
Keep in mind this notation:
- R is a register
- N is a number
- M is either
- C is a condition
-
*
represents an unfinished instruction
Here's the arithmetic:
-
!RM
moves M into R -
+RM
is R += M (addition) -
-RM
is R -= M (subtraction) -
*RM
is R *= M (multiplication) -
/RM
is R /= M (integer division) -
%RM
is R %= M (modulo)
Handling I/O:
-
.R
print out the value of R as a number -
;R
print out the value of R as a character (unicode codepoint) -
,R
accept one input character into R -
#R
read the input as a number, consuming the most amount of characters that creates a proper number -
_
take and discard an input character -
'M
seek to M in the input -
|R
store the length of the input in R
Conditions:
-
M=M
if M == M -
M!M
if M != M -
M>M
if M > M -
M<M
if M < M
Control structures:
-
iC[
...]
if C is true, then do what's inside, otherwise skip past]
-
wC[
...]
while C is true, do what's inside, otherwise skip past]
Examples
#a*a2.a
Read a number from input, double, and output
#a_#b+ab.a
Read two numbers delimited by a non-number character, add, and output
#bwa<b[.a+a1]
Read a number from the input and output every number from 0 to 1 less than it, e.g. if you pass in 10, the output will be 0123456789
An example with a breakdown
Here's the last example with a breakdown, using comments (:
):
#b : Take a number from the input
wa<b[ : While a < b
.a : Add a to output
+a1 : Add 1 to a
] : End of while block
module Mindbend
class Parser
getter registers : Hash(Char, Int32)
getter program : String = ""
getter position : Int32 = 0
getter input : String = ""
getter output : String = ""
getter input_position = 0
getter loop_pairs = [] of Tuple(Int32, Int32)
def reset
@program = ""
@position = 0
@input = ""
@input_position = 0
@output = ""
@loop_pairs = [] of Tuple(Int32, Int32)
('a'..'z').each { |char| @registers[char] = 0 }
end
def initialize()
@registers = {} of Char => Int32
end
def load_program(program)
reset
@program = program
end
def quick_run(program, input)
reset
@program = program
run(input)
@output
end
def run(input)
@input = input
while @position < @program.size
read_instruction
end
end
def read_char
char = @program[@position]?
@position += 1
char
end
def read_char!
read_char.not_nil!
end
def read_register
char = read_char!
raise Exception.new("#{char} is not a register") unless ('a'..'z').includes? char
char
end
def read_number
number_string = ""
loop do
char = read_char!
if number_string == "" && char == '-'
number_string += '-'
elsif ('0'..'9').includes? char
number_string += char
else
@position -= 1
break
end
end
raise Exception.new("Invalid number") if number_string == ""
number_string.to_i32
end
def read_number_from_input
number_string = ""
loop do
char = @input[@input_position]?
@input_position += 1
if number_string == "" && char == '-'
number_string += '-'
elsif char.nil?
break
elsif ('0'..'9').includes? char
number_string += char
else
@input_position -= 1
break
end
end
raise Exception.new("Invalid number from input") if number_string == ""
number_string.to_i32
end
def read_register_or_number
begin
return read_register
rescue
@position -= 1
return read_number
end
raise Exception.new("Invalid register/number")
end
def read_register_or_number_value : Int32
target = read_register_or_number
return target if target.is_a? Int32
return @registers[target] if target.is_a? Char
raise Exception.new("Invalid register/number")
end
def read_condition : Bool
a = read_register_or_number_value
operator = read_char!
raise Exception.new("Invalid conditional operator") unless ['=', '!', '>', '<'].includes? operator
b = read_register_or_number_value
case operator
when '='
return a == b
when '!'
return a != b
when '>'
return a > b
when '<'
return a < b
end
false
end
def read_open_block
raise Exception.new("Invalid block opening") unless read_char! == '['
end
def seek_close_block
level = 0
start = @position
end_position = -1
loop do
char = read_char
case char
when '['
level += 1
when ']'
if level > 0
level -= 1
else
end_position = @position
break
end
end
raise Exception.new("Block never closed") if @position > @program.size
end
@position = start
end_position
end
def read_instruction
case c = read_char
when '!'
# move instruction
register = read_register
from = read_register_or_number_value
@registers[register] = from
when '+'
# add instruction
register = read_register
operand = read_register_or_number_value
@registers[register] += operand
when '-'
# subtract instruction
register = read_register
operand = read_register_or_number_value
@registers[register] -= operand
when '*'
register = read_register
operand = read_register_or_number_value
@registers[register] *= operand
when '/'
register = read_register
operand = read_register_or_number_value
@registers[register] //= operand
when '%'
register = read_register
operand = read_register_or_number_value
@registers[register] = @registers[register] % operand
when ','
register = read_register
value = @input[@input_position]? || '0'
@registers[register] = value.to_i32? || value.ord
@input_position += 1
when '#'
register = read_register
value = read_number_from_input
@registers[register] = value
when '.'
register = read_register
@output += @registers[register].to_s
when ';'
register = read_register
@output += @registers[register].chr
when '\''
@input_position = read_register_or_number_value
when 'i'
condition = read_condition
read_open_block
unless condition
# skip to the next matching close block
@position = seek_close_block
end
when 'w'
start = @position - 1
condition = read_condition
read_open_block
end_pos = seek_close_block
if condition
loop_pairs << {end_pos, start}
else
@position = end_pos
end
when ']'
if lp = loop_pairs.find { |lp| lp[0] == @position }
@position = lp[1]
loop_pairs.delete lp
end
when '|'
@registers[read_register] = @input.size
when '_'
@input_position += 1
when ':'
until read_char == '\n'
end
when nil
# program is over
else
# ignore invalid instruction
end
end
end
end
# Spec example:
# TODO: replace with your own tests (TDD), these are just how-to examples.
parser = Mindbend::Parser.new
describe "Solution" do
it "succeeds on examples" do
parser.quick_run("#a*a2.a", "2").should eq "4"
parser.quick_run("#a_#b+ab.a", "1+2").should eq "3"
parser.quick_run("#bwa<b[.a+a1]", "10").should eq "0123456789"
end
end