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.

Ad
Ad

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