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.

Code
Diff
  • function hiThere($name) {
    	echo "Hello $name, welcome to PHP!";
    };
    
    hiThere("donaldsebleung");
    
  • 11
    function hiThere($name) {
    
    2
    	echo "Hello {$name}, welcome to PHP!";
    
    2+
    	echo "Hello $name, welcome to PHP!";
    
    33
    };
    
    44
    5
    hiThere("Austin");
    
    5+
    hiThere("donaldsebleung");
    

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 
}

Sum example

sum = fn(a, b) -> a + b end
sum.(2,3)
Object-oriented Programming

My attempt at using OOP to create a simple, minimalistic test fixture in PHP.

This Kumite is inspired by the test fixtures provided by Codewars to validate Kata solutions.

That being said, I really hope PHP will be fully supported in Codewars soon.

This Kumite can also be found on GitHub.

class Test {
  public $passes = 0;
  public $fails = 0;
  public function expect($expression, $msg = "Test Failed - Algorithm did not return expected results") {
    echo ($expression === true) ? "<p style='color:green;font-weight:bold;'>Test Passed</p>" : "<p style='color:red;font-weight:bold;'>$msg</p>";
    if ($expression === true) {
      $this->passes++;
    } else {
      $this->fails++;
    }
  }
  public function assert_equals($actual, $expected, $msg = "Test Failed: Actual Value did not match Expected") {
    echo ($actual === $expected) ? "<p style='color:green;font-weight:bold;'>Test Passed</p>" : "<p style='color:red;font-weight:bold;'>$msg => Expected: " . htmlspecialchars_decode("&quot;") . $expected . htmlspecialchars_decode("&quot;") . " but instead got: " . htmlspecialchars_decode("&quot;") . $actual . htmlspecialchars_decode("&quot;") . "</p>";
    if ($actual === $expected) {
      $this->passes++;
    } else {
      $this->fails++;
    }
  }
  public function assert_not_equals($actual, $expect_NOT, $msg = "Test Failed: Algorithm should NOT return tested value") {
    echo ($actual != $expect_NOT) ? "<p style='color:green;font-weight:bold;'>Test Passed</p>" : "<p style='color:red;font-weight:bold;'>$msg => Algorithm returned value: " . htmlspecialchars_decode("&quot;") . $actual . htmlspecialchars_decode("&quot;") . "</p>";
    if ($actual != $expect_NOT) {
      $this->passes++;
    } else {
      $this->fails++;
    }
  }
  public function print_summary() {
    echo ($this->passes > 0 || $this->fails > 0) ? "<p style='color:green;font-weight:bold;'>$this->passes Passed</p><p style='color:red;font-weight:bold;'>$this->fails Failed</p>" . (($this->fails === 0) ? "<p style='color:green;font-weight:bold;'>Algorithm Passed</p>" : "<p style='color:red;font-weight:bold;'>Algorithm did not pass - try again</p>") : "<p style='color:red;font-weight:bold;'>Error: No test cases provided; must provide at least 1 to validate algorithm</p>";
  }
}
Lists
Data Structures
Strings

Example how to convert your name to japanese in Groovy.***(joke)***

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 += ' '
      else 
        japanaseName += alphabet[((int)it) - 97]
    }

    japanaseName.split(' ').collect{it.capitalize()}.join(' ')
}
Code
Diff
  • var merge = function(array1, array2, callbackFN){ 
     return callbackFN(array1,array2);
    }
    
    function callbackFN(a,b) {
      if(Array.isArray(a) && Array.isArray(b) && (a.length === b.length)){
        return a.map(function(c,i){ return c + b[i]; });
      } else {
        return 'both inputs must be Array and same size of elements';
      }
      
    }
    
    var x = merge([1, 3, 4], [5, 6, 7, 8], callbackFN);
    console.log(x);   //x should now equal [6, 8, 10, 12].
    
  • 11
    var merge = function(array1, array2, callbackFN){ 
    
    22
     return callbackFN(array1,array2);
    
    33
    }
    
    44
    55
    function callbackFN(a,b) {
    
    6
      return a.map(function(c,i){return c + b[i];});
    
    6+
      if(Array.isArray(a) && Array.isArray(b) && (a.length === b.length)){
    
    7+
        return a.map(function(c,i){ return c + b[i]; });
    
    8+
      } else {
    
    9+
        return 'both inputs must be Array and same size of elements';
    
    10+
      }
    
    11+
      
    
    77
    }
    
    88
    9
    var x = merge([1, 2, 3, 4], [5, 6, 7, 8], callbackFN);
    
    14+
    var x = merge([1, 3, 4], [5, 6, 7, 8], callbackFN);
    
    1010
    console.log(x);   //x should now equal [6, 8, 10, 12].
    
Best Practices

The idea of this Kumite is inspired from a Kata by another user with a similar name.

Initially, you are given the PHP code that does the following:

  1. Accepts an array of integers as the argument (you may assume that all arguments passed to the function are valid integer-only arrays so no need to validate argument type)
  2. Squares all the integers in it
  3. returns the sum of all the (squared) integers in the array

For example, given an initial array:

array(1, 2, 3, 5, 6)

It will first be transformed to:

array(1, 4, 9, 25, 36)

Then it will:

return 75; // 1 + 4 + 9 + 25 + 36

The initial code does so by the use of 2 for loops and quite a few lines of code. Your task is to shorten the code as much as possible (possibly to 1 single line of code?) in order to reduce execution time.

Good luck :)

Note: Optionally, you can also shorten variable names to single letters as the original variable names are unnecessarily long

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;
  }
  $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;
}
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
Classes
Basic Language Features
Object-oriented Programming
Fundamentals
class Person
  constructor: (@name, @age) ->
  toString: -> "#{@name} is #{@age} years old" 
  
class Developer extends Person
  constructor: (name, age, @skills) -> super(name, age)
  toString: -> super.toString() + " and has #{@skills} skills"
  
jack = new Developer("Jack", 20, ['CoffeeScript', 'JavaScript'])
console.log jack.toString()
Classes
Basic Language Features
Object-oriented Programming
Fundamentals
Objects
class Person {
  String name
  int age
  
  void setName(String name) {
    if(name.matches(/^[a-zA-Z]*$/))
      this.name = name
    else
      throw new Exception('Invalid name')
  }
  
  void setAge(int age) {
    if(age >= 0 && age <= 150)
      this.age = age
    else
      throw new Exception('Invalid age')
  }
  
  String toString() {
    "$name is $age years old"
  }
  
}

class Developer extends Person {
  List<String> skills
  
  Developer(String name="No Name", int age=0, List<String> skills=[]) {
    setName(name)
    setAge(age)
    this.skills = skills.collect()
  }
  
  String toString() {
    super.toString() + " and have $skills skills"
  }
  
}

static main(args) {
  Person jack = new Developer("jack", 25, ['Groovy on Grails'])
  jack.name = jack.name.toUpperCase()
  jack.age++
  jack.skills << 'Spring'
  
  try{
    jack.name = "~~~JACK~~~"
  } catch(e) {
    println "### Mistake: ${e.getMessage()} ###"
  }
  
  try{
    jack.age -= 200
  } catch(e) {
    println "### Mistake: ${e.getMessage()} ###"
  }
  
  print jack
}
Lists
Data Structures
Collections
def languages = ['Java', 'C#', 'Scala', 'F#']
languages.add('Groovy')
languages << 'Clojure'

languages.remove('F#')
languages -= 'C#'

println "JVM programming languages: "
languages.each{println it.toUpperCase()}