Begin a new Kumite
Search
About
  • Filter by Language:
  • 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.

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";
  }
}
Code
Diff
  • string language = "C#";
    System.Console.WriteLine("Hello, {0}!",language);
  • 1
    System.Console.WriteLine("Hello, C#!");
    
    1+
    string language = "C#";
    
    2+
    System.Console.WriteLine("Hello, {0}!",language);
    
Lambdas
Functional Programming
Functions
Declarative Programming
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() {
  <:]{%>;
  <:]{%>();
  <:](){%>();
}

Apart from using echo to output in PHP, you could alternatively use the print statement. Both behave similarly except for a few fundamental differences:

  1. print has a return value of 1; echo does not
  2. echo can take multiple arguments; print cannot
  3. echo executes faster than print
Code
Diff
  • print "Make PHP great again"; // ;)
  • 1
    echo "Hello, PHP folks!";
    
    1+
    print "Make PHP great again"; // ;)
    

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

This illustrates how to sum natural numbers using tail recursion. In some languages, tail call optimization is performed, which enables recursive calls to take constant stack space.

Code
Diff
  • def sum n
        def acc(n, s)
            return s if n <= 0 # Base case
            acc(n - 1, s + n)  # Recursion step, with accumulator
        end
        acc(n, 0)
    end
  • 11
    def sum n
    
    2
      return 1 if n == 1 # Base case of recursion method - must be defined; otherwise infinite recursion may occur
    
    3
      n + sum(n - 1)
    
    2+
        def acc(n, s)
    
    3+
            return s if n <= 0 # Base case
    
    4+
            acc(n - 1, s + n)  # Recursion step, with accumulator
    
    5+
        end
    
    6+
        acc(n, 0)
    
    44
    end
    

Recent Moves:

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);
  }
}
Stacks
Arrays

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

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