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.
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);
Groovy: Sets operations example
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
Matching Brackets
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 {
public void test1() {
assertTrue( MatchingBrackets.isBalanced("{([])}") );
}
public void test2() {
assertTrue( MatchingBrackets.isBalanced("{}()[]") );
}
public void test3() {
assertFalse( MatchingBrackets.isBalanced("{([})}") );
}
public void test4() {
assertFalse( MatchingBrackets.isBalanced("(") );
}
public void test5() {
assertFalse( MatchingBrackets.isBalanced("{") );
}
public void test6() {
assertFalse( MatchingBrackets.isBalanced("[") );
}
public void test7() {
assertFalse( MatchingBrackets.isBalanced(")") );
}
public void test8() {
assertFalse( MatchingBrackets.isBalanced("}") );
}
public void test9() {
assertFalse( MatchingBrackets.isBalanced("]") );
}
public void test10() {
assertTrue( MatchingBrackets.isBalanced("{([{{([{}()[]])}}({([{{([{{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[]])}]])}}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[{([{{([{}()[]])}}({([{{([{}()[]])}}()[]])})[]])}]])}]])}]])}") );
}
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";
}
}
Javatlacati's Kumite #21
object Scala extends App {
class StringUtilities {
def upper(strings: String*): Seq[String] = {
strings.map((s:String) => s.toUpperCase())
}
}
val up = new StringUtilities
Console.println(up.upper("A", "First", "Scala", "Program"))
}
Caesar Cipher and Password Encryption/Decryption in PHP
Yeah, so I recently implemented the Caesar Cipher encryption algorithm in PHP. At first, I did it for fun (I knew how to code the Caesar Cipher in Javascript already so I thought: why don't I try it in PHP also?) but then I realised the practical applications of this simple cipher - I could encrypt/decrypt my passwords with it in my personal Forums! Of course if the website you are working on belongs to a huge multimillion dollar company you would not want to use this simple cipher (only) to encrypt your passwords due to its lack of complexity (and can therefore easily be cracked by an experienced hacker) but for smaller, perhaps personal, websites and forums, a Caesar Shift encryption is more than enough.
Enjoy :D
class CaesarCipher {
public $shift;
const alphabet = array(
"lowercase" => array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"),
"uppercase" => array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z")
);
public function __construct($shift = 0) {
$this->shift = $shift % 26;
}
public function encrypt($input) {
$result = str_split($input);
for ($i = 0; $i < count($result); $i++) {
for ($j = 0; $j < 26; $j++) {
if ($result[$i] === CaesarCipher::alphabet["lowercase"][$j]) {
$result[$i] = CaesarCipher::alphabet["lowercase"][($j + $this->shift) % 26];
$j = 26;
} elseif ($result[$i] === CaesarCipher::alphabet["uppercase"][$j]) {
$result[$i] = CaesarCipher::alphabet["uppercase"][($j + $this->shift) % 26];
$j = 26;
}
}
}
$result = implode($result);
return $result;
}
public function decrypt($input) {
$result = str_split($input);
for ($i = 0; $i < count($result); $i++) {
for ($j = 0; $j < 26; $j++) {
if ($result[$i] === CaesarCipher::alphabet["lowercase"][$j]) {
$result[$i] = CaesarCipher::alphabet["lowercase"][($j + 26 - $this->shift) % 26];
$j = 26;
} elseif ($result[$i] === CaesarCipher::alphabet["uppercase"][$j]) {
$result[$i] = CaesarCipher::alphabet["uppercase"][($j + 26 - $this->shift) % 26];
$j = 26;
}
}
}
$result = implode($result);
return $result;
}
}
$cipher = new CaesarCipher(1);
echo $cipher->encrypt("hello world");
echo $cipher->encrypt("HELLO WORLD");
echo $cipher->encrypt("Hello World");
$cipher = new CaesarCipher(5);
echo $cipher->encrypt("hello world");
echo $cipher->encrypt("HELLO WORLD");
echo $cipher->encrypt("Hello World");
$cipher = new CaesarCipher(8);
echo $cipher->encrypt("hello world");
echo $cipher->encrypt("HELLO WORLD");
echo $cipher->encrypt("Hello World");
$cipher = new CaesarCipher(13);
echo $cipher->encrypt("hello world");
echo $cipher->encrypt("HELLO WORLD");
echo $cipher->encrypt("Hello World");
$cipher = new CaesarCipher(20);
echo $cipher->encrypt("hello world");
echo $cipher->encrypt("HELLO WORLD");
echo $cipher->encrypt("Hello World");
$cipher = new CaesarCipher(25);
echo $cipher->encrypt("hello world");
echo $cipher->encrypt("HELLO WORLD");
echo $cipher->encrypt("Hello World");
$cipher = new CaesarCipher(30);
echo $cipher->encrypt("hello world");
echo $cipher->encrypt("HELLO WORLD");
echo $cipher->encrypt("Hello World");