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
Utilities
Asynchronous

In this version end is protected so that it is only called once, and once its called next() no longer does anything.

Code
Diff
  • function Chain(){
      this.links = [];
    }
    
    Chain.prototype.link = function link(cb){
      this.links.push(cb);
      return this;
    }
    
    Chain.prototype.run = function run(end){
      var self = this,
          ended = false,
          _end = function(){
            end();
            ended = true;
          },
          next = function(){
            if (!ended){
              if(self.links.length) {
                self.links.shift()(next, _end);
              } else {
                  _end();
              }
            }
          };
       next(); 
    }
    • function Chain(){
    • this.links = [];
    • }
    • Chain.prototype.link = function link(cb){
    • this.links.push(cb);
    • return this;
    • }
    • Chain.prototype.run = function run(end){
    • if(this.links.length) {
    • this.links.shift()(Chain.prototype.run.bind(this, end), end);
    • } else {
    • end();
    • }
    • var self = this,
    • ended = false,
    • _end = function(){
    • end();
    • ended = true;
    • },
    • next = function(){
    • if (!ended){
    • if(self.links.length) {
    • self.links.shift()(next, _end);
    • } else {
    • _end();
    • }
    • }
    • };
    • next();
    • }

Write a generator that given a starting seed (which must be odd), will generate "random" numbers using the infamous RANDU generator, first value should be the seed itself.

Code
Diff
  • def randu_seq(x):
        while True:
            yield x
            x = x * 65539 % 0x80000000
    • (ns randu)
    • (defn randu-seq [x] (iterate #(mod (* 65539 %) 0x80000000) x))
    • def randu_seq(x):
    • while True:
    • yield x
    • x = x * 65539 % 0x80000000
Code
Diff
  • sum = &Kernel.+/2
    sum.(2,3)
    • sum = fn(a, b) -> a + b end
    • sum = &Kernel.+/2
    • sum.(2,3)
Lists
Data Structures
Strings
Data Types
Code
Diff
  • def name = "John Cena"
    try {
      println "Your name in japanese is " + convertToJapanese(name)
    } catch(e) {
      System.err << e.getMessage()
    }
    
    static String convertToJapanese(String name) {
    
        name = name.toLowerCase()
        
        if(name == "" || !name.matches('^[a-z\\s]*$'))
          throw new Exception('ERROR: invalid name\n')
    
        def alphabet = [
          'ka','zu','mi','te','ku',
          'lu','ji','ri','ki','zus',
          'me','ta','rin','to','mo',
          'no','ke','shi','ari','chi',
          'do','ru','mei','na','fu','zi'
        ]
    
        String japaneseName = ''
    
        name.each {
          if(it in [' ', '\t', '\n'])
            japaneseName += ' '
          else 
            japaneseName += alphabet[((int)it) - 97]
        }
    
        japaneseName.split(' ').collect{it.capitalize()}.join(' ')
    }
    • def name = "John Cena"
    • try {
    • println "Your name in japanese is " + convertToJapanese(name)
    • } catch(e) {
    • System.err << e.getMessage()
    • }
    • static String convertToJapanese(String name) {
    • name = name.toLowerCase()
    • if(name == "" || !name.matches('^[a-z\\s]*$'))
    • throw new Exception('ERROR: invalid name\n')
    • def alphabet = [
    • 'ka','zu','mi','te','ku',
    • 'lu','ji','ri','ki','zus',
    • 'me','ta','rin','to','mo',
    • 'no','ke','shi','ari','chi',
    • 'do','ru','mei','na','fu','zi'
    • ]
    • String japaneseName = ''
    • name.each {
    • if(it in [' ', '\t', '\n'])
    • japanaseName += ' '
    • japaneseName += ' '
    • else
    • japanaseName += alphabet[((int)it) - 97]
    • japaneseName += alphabet[((int)it) - 97]
    • }
    • japanaseName.split(' ').collect{it.capitalize()}.join(' ')
    • japaneseName.split(' ').collect{it.capitalize()}.join(' ')
    • }
Stacks
Arrays
Data Types
Code
Diff
  • import java.util.*;
    
    public class MatchingBrackets {
    
      public static boolean isBalanced(String braces) {
            Stack<String> stack = new Stack<>();
            Map<String, String> enclosing = new HashMap<>();
            enclosing.put(")","(");
            enclosing.put("}","{");
            enclosing.put("]","[");
            for (char brace : braces.toCharArray()) {
                final String strBrace = Character.toString(brace);
                if (!stack.isEmpty() && stack.peek().equals(enclosing.get(strBrace))) {
                    stack.pop();
                } else {
                    stack.push(strBrace);
                }
            }
            return stack.isEmpty();
        }
    }
    • /**
    • * 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);
    • public class MatchingBrackets {
    • public static boolean isBalanced(String braces) {
    • Stack<String> stack = new Stack<>();
    • Map<String, String> enclosing = new HashMap<>();
    • enclosing.put(")","(");
    • enclosing.put("}","{");
    • enclosing.put("]","[");
    • for (char brace : braces.toCharArray()) {
    • final String strBrace = Character.toString(brace);
    • if (!stack.isEmpty() && stack.peek().equals(enclosing.get(strBrace))) {
    • stack.pop();
    • } else {
    • if(stack.isEmpty()) {
    • balanced = false;
    • break;
    • }
    • Character top = stack.peek();
    • if((c == ')' && top == '(') || (c == '}' && top == '{') || (c == ']' && top == '[')) {
    • stack.pop();
    • } else {
    • balanced = false;
    • break;
    • }
    • stack.push(strBrace);
    • }
    • }
    • return balanced && stack.isEmpty();
    • }
    • }
    • return stack.isEmpty();
    • }
    • }

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"; // ;)
    • echo "Hello, PHP folks!";
    • print "Make PHP great again"; // ;)

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
    • 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)
    • 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
Best Practices
Code
Diff
  • function square_n_sum($array_of_numbers) {
      $acc = 0;
      foreach ($array_of_numbers as $el) {
        $acc += $el ^ 2;
      }
      return $acc;
    }
    echo square_n_sum(array(1,2,3,5,6)); // Should return 75
    echo "<br />";
    echo square_n_sum(array(1,2)); // Should return 5
    echo "<br />";
    echo square_n_sum(array(3,4)); // Should return 25
    echo "<br />";
    echo square_n_sum(array(1,2,3,4)); // Should return 30
    echo "<br />";
    echo square_n_sum(array(1,2,3,4,5,6,7,8,9,99)); // Should return 10086
    • function square_n_sum($array_of_numbers) {
    • for ($i = 0; $i < sizeof($array_of_numbers); $i++) {
    • $array_of_numbers[$i] = $array_of_numbers[$i] ** 2;
    • $acc = 0;
    • foreach ($array_of_numbers as $el) {
    • $acc += $el ^ 2;
    • }
    • $sum_of_squared_numbers = 0;
    • for ($i = 0; $i < sizeof($array_of_numbers); $i++) {
    • $sum_of_squared_numbers += $array_of_numbers[$i];
    • }
    • return $sum_of_squared_numbers;
    • return $acc;
    • }
    • echo square_n_sum(array(1,2,3,5,6)); // Should return 75
    • echo "<br />";
    • echo square_n_sum(array(1,2)); // Should return 5
    • echo "<br />";
    • echo square_n_sum(array(3,4)); // Should return 25
    • echo "<br />";
    • echo square_n_sum(array(1,2,3,4)); // Should return 30
    • echo "<br />";
    • echo square_n_sum(array(1,2,3,4,5,6,7,8,9,99)); // Should return 10086