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.
Implements a linked list class in C++ with an insert, remove and printReverse function.
#include <iostream>
using namespace std;
class LList {
public:
LList() :head(0), tail(0) {}
~LList() {
Node * cur = head;
while (cur) {
cur = cur->next;
delete head;
head = cur;
}
}
void insert(int val) {
if (!tail) {
head=tail=new Node(val);
}
else {
tail->next=new Node(val, 0, tail);
tail=tail->next;
}
}
void printReverse() const;
bool remove(int val);
private:
struct Node {
Node(int d, Node *n = 0, Node *p = 0) : data(d), next(n), prev(p) {}
int data;
Node *next, *prev;
};
Node * head, *tail;
};
bool LList::remove(int val){
Node * curr = tail;
while (curr != NULL && curr->data != val){
curr = curr->prev;
}
if (curr == NULL)return false;
if (curr == head)
head = head->next;
else
curr->prev->next = curr->next;
if (curr == tail)
tail = tail->prev;
else
curr->next->prev = curr->prev;
delete curr;
return true;
}
void LList::printReverse()const{
Node * curr = tail;
while (curr){
cout << curr->data << endl;
curr = curr->prev;
}
}
//Test
void main(){
LList hello;
hello.insert(1);
hello.insert(2);
hello.insert(3);
hello.printReverse();//prints 123
hello.remove(2);
hello.printReverse();//prints 13
hello.remove(3);
hello.printReverse();//prints 1
hello.remove(1);
hello.printReverse();//prints NOTHING
}
You have a list of objects, and the length is N.
You want to take all the possible M-length slots with consecutive objects.
Suppose we have myList, we want all the 3-length slots:
List<int> myList = new List<int>() {32, 645, 3, 35, 75, 435, 423, 13, 65, 8};
List<int[]> listOfSlots = new List<int[]>()
{
new[] {32, 645, 3},
new[] {645, 3, 35},
new[] {3, 35, 75},
new[] {35, 75, 435},
new[] {75, 435, 423},
new[] {435, 423, 13},
new[] {423, 13, 65},
new[] {13, 65, 8}
};
using System.Collections.Generic;
using System.Linq;
int M = 3;
List<int[]> results = Enumerable.Range(0, myList.Count - M + 1).Select(n => myList.Skip(n).Take(M).ToArray()).ToList();
This shows a very simple example for displaying interactive Angular content within the output window. Click "View Output" to see.
var script = `<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.5/angular.min.js"></script>`;
var styles = `
html, body {
background-color: #ecf0f1;
margin: 20px auto;
display: block;
max-width: 600px;
height: 100%;
text-align: center;
}
body {
padding: 20px;
position: relative;
}
h2, a, p, *:before,h1 {
font-family: "Helvetica Neue", sans-serif;
font-weight: 300;
}
h1 {
color: #3498db;
}
h2 {
color: #2980b9;
margin-bottom: 9px;
margin-top: 0;
font-size: 20px;
background-color: white;
/*width: 100px;*/
text-align: center;
padding: 16px;
z-index: 15;
border-radius: 4px;
transition: all 2s ease-out;
}
p {
display: block;
width: 100%;
color: #2c3e50;
clear: both;
}
.description {
margin-bottom: 70px;
}
button {
border: 0;
background-color: #3498db;
color: white;
border-radius: 4px;
padding: 5px 10px;
transition: background-color 0.2s ease-out;
cursor: pointer;
}
button:hover {
background-color: #2980b9;
}
button:active, button:hover {
outline: none;
}
a {
color: #2c3e50;
transition: color 0.2s ease-out;
/*padding: 5px 10px;*/
margin-right: 16px;
}
a:hover {
color: #2ecc71;
}
.wrapper {
border: 1px dashed #95a5a6;
height: 56px;
margin-top: 16px;
border-radius: 4px;
position: relative;
font-size: 12px;
}
.wrapper p {
line-height: 31px;
}
`
var html = `
<div ng-app="">
<h1>Ng-show & ng-hide</h1>
<p class="description">Click on the "show"-link to see the content.</p>
<a href="" ng-click="showme=true">Show</a>
<button ng-click="showme=false">Hide</button>
<div class="wrapper">
<p ng-hide="showme">I am hidden content</p>
<h2 ng-show="showme">I am visible content</h2>
</div>
</div>
`
console.log(`${script}<style>${styles}</style>${html}`);
Test.expect(script.length > 0);
Example how to use basic sets operations in groovy
Set a = [6, 3, 4, 2, 5, 8]
Set b = [8, 9, 7, 5, 2, 6]
println "Set A : ${a}"
println "Set B: ${b}"
println "A = B : ${a == b}" // equality
println "A + B : ${a + b}" // union
println "A - B : ${a - b}" // difference
println "A symmetric difference B : ${(a-b) + (b-a)}" // symmetric difference
println "A intersection B : ${a.intersect b}" // intersection
Given an expression string exp, examine whether the pairs and the orders of "{", "}", "(", ")", "[", "]" are correct in exp.
For example, the program should return true
for [()]{}{[()()]()}
and false
for [(])
.
Check provided test cases to see expected behaviour for different inputs.
/**
* Check if brackets are matching.
* Time Complexity: O(N), Space Complexity: O(N)
*
* @author Jayesh Chandrapal
*/
import java.util.*;
import java.lang.*;
import java.io.*;
class MatchingBrackets {
/**
* Checks if given input string contains matching brackets.
*
* @params str input string to be checked
* @returns boolean value indicating if given string contains matching brackets
*/
public static boolean isBalanced(String str) {
boolean balanced = true;
Stack<Character> stack = new Stack<Character>();
for(Character c : str.toCharArray()) {
if(c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if(stack.isEmpty()) {
balanced = false;
break;
}
Character top = stack.peek();
if((c == ')' && top == '(') || (c == '}' && top == '{') || (c == ']' && top == '[')) {
stack.pop();
} else {
balanced = false;
break;
}
}
}
return balanced && stack.isEmpty();
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class TestCases {
@Test
public void test1() {
assertTrue( MatchingBrackets.isBalanced("{([])}") );
}
@Test
public void test2() {
assertTrue( MatchingBrackets.isBalanced("{}()[]") );
}
@Test
public void test3() {
assertFalse( MatchingBrackets.isBalanced("{([})}") );
}
@Test
public void test4() {
assertFalse( MatchingBrackets.isBalanced("(") );
}
@Test
public void test5() {
assertFalse( MatchingBrackets.isBalanced("{") );
}
@Test
public void test6() {
assertFalse( MatchingBrackets.isBalanced("[") );
}
@Test
public void test7() {
assertFalse( MatchingBrackets.isBalanced(")") );
}
@Test
public void test8() {
assertFalse( MatchingBrackets.isBalanced("}") );
}
@Test
public void test9() {
assertFalse( MatchingBrackets.isBalanced("]") );
}
@Test
public void test10() {
assertTrue( MatchingBrackets.isBalanced("{([{{([{}()[]])}}({([{{([{{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[]])}]])}}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[]])}]])}]])}]])}") );
}
@Test
public void test11() {
assertTrue( MatchingBrackets.isBalanced("") );
}
}
Just a simple and human-readable extension method for Integer
s in Javascript to effectively replace 99% of for loops and make the code look much cleaner and more readable. I've been using it in my Kata solutions lately. Enjoy :)
Number.prototype.times = function (f) {
for (let i = 0; i < this; i++) {
f(i);
}
}
describe("Number.prototype.times", _ => {
it("can effectively act as a 'for' loop to print 'Hello World' to the console repeatedly", _ => {
function helloWorld10() {
var result = [];
(10).times(_ => {
console.log("Hello World");
result.push("Hello World");
});
return result;
}
Test.assertSimilar(helloWorld10(), ["Hello World","Hello World","Hello World","Hello World","Hello World","Hello World","Hello World","Hello World","Hello World","Hello World"]);
});
it("can loop through arrays effectively", _ => {
function loopArrAndRtnSameArr(array) {
var result = [];
array.length.times(i => {
console.log(array[i]);
result.push(array[i]);
});
return result;
}
var myArr = [1,2,3,5,7,11,true,false,"Lorem ipsum"];
Test.assertSimilar(loopArrAndRtnSameArr(myArr), myArr);
});
});
Note: Please note that this Kumite is merely a simple example of how recursion works. It is in NO way a best practice to sum natural numbers using recursion. Summation by iteration is about 2 times quicker and of course you could always plug in the formula sum(n) == n * (n + 1) / 2
(which is by far the most efficient).
def sum n
return 1 if n == 1 # Base case of recursion method - must be defined; otherwise infinite recursion may occur
n + sum(n - 1)
end
describe "The function" do
it "should sum up to 10 correctly" do
Test.assert_equals sum(1), 1
Test.assert_equals sum(2), 3
Test.assert_equals sum(3), 6
Test.assert_equals sum(4), 10
Test.assert_equals sum(5), 15
Test.assert_equals sum(6), 21
Test.assert_equals sum(7), 28
Test.assert_equals sum(8), 36
Test.assert_equals sum(9), 45
Test.assert_equals sum(10), 55
end
it "should sum up to larger numbers correctly too" do
Test.assert_equals sum(20), 210
Test.assert_equals sum(30), 465
Test.assert_equals sum(40), 820
Test.assert_equals sum(50), 50 * (50 + 1) / 2
end
it "should sum up to any number correctly" do
5.times do
rand_int = Test.random_number
Test.assert_equals sum(rand_int), rand_int * (rand_int + 1) / 2
end
end
end
So, this is basically the official solution of a long-forgotten beta Kata I have authored.
This DataSet
class can do the following:
- Store the numerical data passed in to the constructor (as a variable number of arguments) as an array in
this.data
- Immediately calculate the mean, variance and standard deviation of the data upon initialization
- Re-calculate the
mean
,stdDeviation
andvariance
respectively upon calling thethis.setMean()
andthis.setVar()
methods respectively.
Since the Kata was created and since the official solution was initially crafted, I have already refactored, optimized and improved upon it a few times, so enjoy!
This Kumite comes with a simple example test case but you are free to add your own tests to confirm that it works properly.
class DataSet {
constructor(...data) {
this.data = data;
this.mean = this.data.reduce((a,b)=>a+b) / this.data.length;
this.variance = this.data.map(x=>x*x).reduce((a,b)=>a+b) / this.data.length - this.mean ** 2;
this.stdDeviation = Math.sqrt(this.variance);
}
setMean() {
return this.mean = this.data.reduce((a,b)=>a+b) / this.data.length;
}
setVar() {
this.stdDeviation = Math.sqrt(this.data.map(x=>x*x).reduce((a,b)=>a+b) / this.data.length - (this.data.reduce((a,b)=>a+b) / this.data.length) ** 2);
return this.variance = this.stdDeviation ** 2;
}
}
Test.describe("Your <code>DataSet()</code> Class", _ => {
Test.it("should work for the example provided in the description", _ => {
var myData1 = new DataSet(1,2,3,4,5,6,7);
Test.assertSimilar(myData1.data, [1,2,3,4,5,6,7]);
Test.assertEquals(myData1.mean, 4);
Test.assertEquals(myData1.variance, 4);
Test.assertEquals(myData1.stdDeviation, 2);
myData1.data[6] = 14;
Test.assertEquals(myData1.setMean(), 5);
Test.assertEquals(myData1.mean, 5);
Test.assertEquals(myData1.setVar(), 16);
Test.assertEquals(myData1.variance, 16);
Test.assertEquals(myData1.stdDeviation, 4);
});
Test.it("should also work for my custom test cases", _ => {
// Add your own test cases here :)
});
});
This is a valid expression (an empty lambda function):
<:]{%>
We can call it:
<:]{%>();
A variant with explicit argument list:
<:](){%>();
Actually, some alternative tokens are used here and this code is equaivalent to
[] {};
([] {})();
([]() {})();
int main() {
<:]{%>;
<:]{%>();
<:](){%>();
}
Fun with PHP classes (#2) - Animals and Inheritance
Overview
This is basically the PHP version of the Kata Fun with PHP classes #2 - Animals and Inheritance. If Codewars supported PHP, I would definitely translate my Kata into PHP the first chance I get :D
This Kumite can also be found on GitHub.
Preloaded
Preloaded is a class Animal
:
class Animal {
public $name;
public $age;
public $legs;
public $species;
public $status;
public function __construct($name, $age, $legs, $species, $status) {
$this->name = $name;
$this->age = $age;
$this->legs = $legs;
$this->species = $species;
$this->status = $status;
}
public function introduce() {
return "Hello, my name is $this->name and I am $this->age years old.";
}
}
class Shark extends Animal {
public function __construct($name, $age, $status) {
parent::__construct($name, $age, 0, "shark", $status);
}
}
class Cat extends Animal {
public function __construct($name, $age, $status) {
parent::__construct($name, $age, 4, "cat", $status);
}
public function introduce() {
return parent::introduce() . " Meow meow!";
}
}
class Dog extends Animal {
public $master;
public function __construct($name, $age, $status, $master) {
parent::__construct($name, $age, 4, "dog", $status);
$this->master = $master;
}
public function greet_master() {
return "Hello $this->master";
}
}