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.

Vigenère Cipher in PHP

An alternative algorithm to Caesar Cipher for encrypting passwords and other sensitive information. Should be more secure than Caesar Cipher.

class VigenèreCipher {
  public $key;
  public $alphabet;
  public function __construct($key, $alphabet) {
    $this->key = $key;
    $this->alphabet = $alphabet;
  }
  public function encrypt($string) {
    $result = str_split($string);
    $key_text = $this->key;
    $abc = str_split($this->alphabet);
    while (strlen($key_text) < count($result)) {
      $key_text .= $this->key;
    }
    $key_text = str_split($key_text);
    $temp = array();
    for ($i = 0; $i < count($result); $i++) {
      $temp[$i] = $key_text[$i];
    }
    # $temp = implode($temp);
    $key_text = $temp;
    // echo "<code style='font-weight:bold'>";
    // echo implode($result) . "<br>";
    // echo $key_text;
    // echo "</code>";
    for ($i = 0; $i < count($result); $i++) {
      if (array_search($result[$i], $abc) !== false) {
        $result[$i] = $abc[(array_search($result[$i], $abc) + array_search($key_text[$i], $abc)) % count($abc)];
      }
    }
    $result = implode($result);
    return $result;
  }
  public function decrypt($string) {
    $result = str_split($string);
    $key_text = $this->key;
    $abc = str_split($this->alphabet);
    while (strlen($key_text) < count($result)) {
      $key_text .= $this->key;
    }
    $key_text = str_split($key_text);
    $temp = array();
    for ($i = 0; $i < count($result); $i++) {
      $temp[$i] = $key_text[$i];
    }
    # $temp = implode($temp);
    $key_text = $temp;
    // echo "<code style='font-weight:bold'>";
    // echo implode($result) . "<br>";
    // echo $key_text;
    // echo "</code>";
    for ($i = 0; $i < count($result); $i++) {
      if (array_search($result[$i], $abc) !== false) {
        $key_text_location = array_search($key_text[$i], $abc);
        while ($key_text_location > array_search($result[$i], $abc)) $key_text_location -= strlen($this->alphabet);
        $result[$i] = $abc[(array_search($result[$i], $abc) - $key_text_location) % count($abc)];
      }
    }
    $result = implode($result);
    return $result;
  }
}

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
  • 1
    (ns randu)
    
    2
    3
    (defn randu-seq [x] (iterate #(mod (* 65539 %) 0x80000000) x))
    
    1+
    def randu_seq(x):
    
    2+
        while True:
    
    3+
            yield x
    
    4+
            x = x * 65539 % 0x80000000
    

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");
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"))
}
Code
Diff
  • sum = &Kernel.+/2
    sum.(2,3)
  • 1
    sum = fn(a, b) -> a + b end
    
    1+
    sum = &Kernel.+/2
    
    22
    sum.(2,3)
    
Lists
Data Structures
Strings
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.matches('\\s'))
            japaneseName += ' '
          else 
            japaneseName += alphabet[((int)it) - 97]
        }
    
        japaneseName.split(' ').collect{it.capitalize()}.join(' ')
    }
  • 2020
          'do','ru','mei','na','fu','zi'
    
    2121
        ]
    
    2222
    2323
        String japaneseName = ''
    
    2424
    2525
        name.each {
    
    26
          if(it in [' ', '\t', '\n'])
    
    27
            japanaseName += ' '
    
    26+
          if(it.matches('\\s'))
    
    27+
            japaneseName += ' '
    
    2828
          else 
    
    29
            japanaseName += alphabet[((int)it) - 97]
    
    29+
            japaneseName += alphabet[((int)it) - 97]
    
    3030
        }
    
    3131
    32
        japanaseName.split(' ').collect{it.capitalize()}.join(' ')
    
    32+
        japaneseName.split(' ').collect{it.capitalize()}.join(' ')
    
    3333
    }
    

Recent Moves:

Stacks
Arrays
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();
        }
    }
  • 1
    /**
    
    2
     *  Check if brackets are matching.
    
    3
     *  Time Complexity: O(N), Space Complexity: O(N)
    
    4
     *
    
    5
     *  @author Jayesh Chandrapal
    
    6
     */
    
    77
    import java.util.*;
    
    8
    import java.lang.*;
    
    9
    import java.io.*;
    
    1010
    11
    class MatchingBrackets {
    
    12
    	
    
    13
      /**
    
    14
       *  Checks if given input string contains matching brackets.
    
    15
       *
    
    16
       * @params str  input string to be checked
    
    22
    	    
    
    23
    	    for(Character c : str.toCharArray()) {
    
    24
                if(c == '(' || c == '{' || c == '[') {
    
    25
                    stack.push(c);
    
    3+
    public class MatchingBrackets {
    
    4+
    5+
      public static boolean isBalanced(String braces) {
    
    6+
            Stack<String> stack = new Stack<>();
    
    7+
            Map<String, String> enclosing = new HashMap<>();
    
    8+
            enclosing.put(")","(");
    
    9+
            enclosing.put("}","{");
    
    10+
            enclosing.put("]","[");
    
    11+
            for (char brace : braces.toCharArray()) {
    
    12+
                final String strBrace = Character.toString(brace);
    
    13+
                if (!stack.isEmpty() && stack.peek().equals(enclosing.get(strBrace))) {
    
    14+
                    stack.pop();
    
    2626
                } else {
    
    27
                    if(stack.isEmpty()) {
    
    28
                        balanced = false;
    
    29
                        break;
    
    30
                    }
    
    31
                    
    
    32
                    Character top = stack.peek();
    
    33
                    if((c == ')' && top == '(') || (c == '}' && top == '{') || (c == ']' && top == '[')) {
    
    34
                        stack.pop();
    
    35
                    } else {
    
    36
                        balanced = false;
    
    37
                        break;
    
    38
                    }
    
    16+
                    stack.push(strBrace);
    
    3939
                }
    
    40
    	    }
    
    41
    	    
    
    42
    	    return balanced && stack.isEmpty();
    
    43
    	}
    
    18+
            }
    
    19+
            return stack.isEmpty();
    
    20+
        }
    
    4444
    }
    

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