Start a new Kumite
AllAgda (Beta)BF (Beta)CCFML (Beta)ClojureCOBOL (Beta)CoffeeScriptCommonLisp (Beta)CoqC++CrystalC#D (Beta)DartElixirElm (Beta)Erlang (Beta)Factor (Beta)Forth (Beta)Fortran (Beta)F#GoGroovyHaskellHaxe (Beta)Idris (Beta)JavaJavaScriptJulia (Beta)Kotlinλ Calculus (Beta)LeanLuaNASMNim (Beta)Objective-C (Beta)OCaml (Beta)Pascal (Beta)Perl (Beta)PHPPowerShell (Beta)Prolog (Beta)PureScript (Beta)PythonR (Beta)RacketRaku (Beta)Reason (Beta)RISC-V (Beta)RubyRustScalaShellSolidity (Beta)SQLSwiftTypeScriptVB (Beta)
Show only mine

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.

Angular

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}`);
Sets
Arrays
Data Types

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
Stacks
Arrays
Data Types

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();
	}
}

Just a simple and human-readable extension method for Integers 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);
  }
}

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

So, this is basically the official solution of a long-forgotten beta Kata I have authored.

This DataSet class can do the following:

  1. Store the numerical data passed in to the constructor (as a variable number of arguments) as an array in this.data
  2. Immediately calculate the mean, variance and standard deviation of the data upon initialization
  3. Re-calculate the mean, stdDeviation and variance respectively upon calling the this.setMean() and this.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;
  }
}
Lambdas
Functional Programming
Functions
Declarative Programming
Programming Paradigms
Control Flow
Basic Language Features
Fundamentals
Language Syntax

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";
  }
}
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");