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

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

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

This example prints the result of an operation.

package main

import "fmt"

func main() {
    fmt.Print("My age on the surface of Mars is ")
    fmt.Print(28 * 365 / 687) 
    fmt.Print(" years old.")
}

Finds Fibonacci number by given index

(ns fibonacci)

(defn get-fibonacci-number [index]
  "Finds fibonacci number by given index"
  (if (<= index 0) 0)
  (if (<= index 2) 1
    (+ (get-fibonacci-number (- index 1))
       (get-fibonacci-number (- index 2)))))

Finds factorial

(ns factorial)

(defn get-factorial [n]
  "takes n as a paramenter and returns n!"
  (if (<= n 0) 0)
  (if (<= n 1) 1
   (* n (get-factorial (dec n)))))

The second version of my PHP Test Fixture. Inspired by the test fixtures used here in Codewars. That being said, I really hope Codewars will support PHP soon so I can complete and author PHP kata :D

The source code and documentation for this test fixture can also be found on GitHub.

class Test {
  private $passes = 0;
  private $fails = 0;
  const token_chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  public function expect($condition, $msg = "Value was not what was expected") {
    if ($condition) {
      $this->passes++;
      echo "<span style='color:lime'>Test Passed</span><br />";
      return true;
    } else {
      $this->fails++;
      echo "<span style='color:red'>$msg</span><br />";
    }
  }
  public function assert_equals($actual, $expected, $msg = "Value did not match expected") {
    if ($actual === $expected) {
      $this->passes++;
      echo "<span style='color:lime'>Test Passed - Value === $expected</span><br />";
      return true;
    } else {
      $this->fails++;
      echo "<span style='color:red'>$msg - Expected: $expected, but instead got: $actual</span><br />";
      return false;
    }
  }
  public function assert_not_equals($actual, $expected, $msg = "Test Failed") {
    if ($actual !== $expected) {
      $this->passes++;
      echo "<span style='color:lime'>Test Passed - Value !== $expected</span><br />";
      return true;
    } else {
      $this->fails++;
      echo "<span style='color:red'>$msg - Algorithm should not have returned: $expected</span><br />";
      return false;
    }
  }
  public function expect_error($msg, $code) {
    try {
      $code();
    } catch (Exception $e) {
      $error_thrown = true;
      echo "Expected error was thrown: $e<br />";
    } finally {
      if ($error_thrown) {
        $this->passes++;
        echo "<span style='color:lime'>Test Passed</span><br />";
        return true;
      } else {
        $this->fails++;
        echo "<span style='color:red'>$msg</span><br />";
        return false;
      }
    }
  }
  public function expect_no_error($msg, $code) {
    try {
      $code();
    } catch (Exception $e) {
      $error_thrown = true;
      $error_msg = $e;
    } finally {
      if (!$error_thrown) {
        $this->passes++;
        echo "<span style='color:lime'>Test Passed</span><br />";
        return true;
      } else {
        $this->fails++;
        echo "<span style='color:red'>$msg - $error_msg</span><br />";
        return false;
      }
    }
  }
  public function describe($description, $tests) {
    $uniq_id = $this->random_token();
    echo "<div id='console_$uniq_id' style='color:white;background-color:black;padding:10px;font-family:monospace'>";
    echo "<strong>$description</strong>";
    echo "<div id='describe_$uniq_id' style='margin-left:20px'>";
    $tests();
    echo "</div>";
    $this->summarize();
    echo "</div>";
    echo "<script>
    document.getElementById('console_$uniq_id').style.border = '5px solid " . (($this->passes > 0 && $this->fails === 0) ? "lime" : "red") . "';
    </script>";
  }
  public function it($description, $tests) {
    echo "<strong>$description</strong>";
    echo "<div style='margin-left:20px'>";
    $tests();
    echo "</div>";
  }
  public function random_number() {
    return rand(0, 100);
  }
  public function random_token() {
    $length = rand(8, 10);
    $token = "";
    for ($i = 0; $i < $length; $i++) {
      $token .= str_split(Test::token_chars)[floor(lcg_value() * strlen(Test::token_chars))];
    }
    return $token;
  }
  public function summarize() {
    echo "<hr />";
    if ($this->passes === 0 && $this->fails === 0) {
      echo "<span style='color:red'>ERROR: NO TEST CASES PROVIDED</span><br />";
      return false;
    } else {
      echo "<span style='color:lime'>$this->passes Passed</span><br /><span style='color:red'>$this->fails Failed</span><br />";
      echo ($this->fails === 0 ? "<span style='color:lime'>Algorithm Passed</span>" : "<span style='color:red'>Algorithm Failed</span>") . "<br />";
      return $this->fails === 0;
    }
  }
}
#include <iostream>

using namespace std;

int main()
{
	int rows,columns;
	cout << "How many rows and columns does your table have?\n";
	cin >> rows >> columns;
	getchar();
	
		for(int i = 0;i<rows;i++)
    {
        for(int j=0;j<columns;j++)
        {
        		cout << "* ";
        }
        cout << endl;
    }
}

Recursively Comparing Two Arrays in PHP

Provided is a function check_similar which accepts two values (arrays) as input and compares the two values (or arrays) to see if they are equal, recursively. The function returns true if the two values or arrays are equal; false otherwise.

Preloaded

Preloaded is a custom PHP testing framework which can be found here.

// Function

function check_similar($actual, $expected) {
  if (!is_array($expected) || !is_array($actual)) return $actual === $expected;
  foreach ($expected as $key => $value) {
    if (!check_similar($actual[$key], $expected[$key])) return false;
  }
  foreach ($actual as $key => $value) {
    if (!check_similar($actual[$key], $expected[$key])) return false;
  }
  return true;
}


// Test Cases

$test->describe('check_similar($actual, $expected)', function () {
  $GLOBALS['test']->it("should work for primitive data types", function () {
    $GLOBALS['test']->assert_equals(check_similar(1, 1), true);
    $GLOBALS['test']->assert_equals(check_similar(0, 0), true);
    $GLOBALS['test']->assert_equals(check_similar(-1, -1), true);
    $GLOBALS['test']->assert_equals(check_similar(true, true), true);
    $GLOBALS['test']->assert_equals(check_similar(false, false), true);
    $GLOBALS['test']->assert_equals(check_similar("bacon", "bacon"), true);
    $GLOBALS['test']->assert_equals(check_similar("Hello World", "Hello World"), true);
    $GLOBALS['test']->assert_equals(check_similar(1, 0), false);
    $GLOBALS['test']->assert_equals(check_similar(0, 1), false);
    $GLOBALS['test']->assert_equals(check_similar(true, false), false);
    $GLOBALS['test']->assert_equals(check_similar(false, true), false);
    $GLOBALS['test']->assert_equals(check_similar("bacon", "Hello World"), false);
    $GLOBALS['test']->assert_equals(check_similar("Hello World", "bacon"), false);
  });
  $GLOBALS['test']->it("should work for one dimensional arrays (both normal and associative arrays)", function () {
    $GLOBALS['test']->assert_equals(check_similar(array(), array()), true);
    $GLOBALS['test']->assert_equals(check_similar(array(1), array(1)), true);
    $GLOBALS['test']->assert_equals(check_similar(array(0), array(0)), true);
    $GLOBALS['test']->assert_equals(check_similar(array(true), array(true)), true);
    $GLOBALS['test']->assert_equals(check_similar(array(false), array(false)), true);
    $GLOBALS['test']->assert_equals(check_similar(array("bacon"), array("bacon")), true);
    $GLOBALS['test']->assert_equals(check_similar(array("Hello World"), array("Hello World")), true);
    $GLOBALS['test']->assert_equals(check_similar(array(1, 2, 3, 4, 5), array(1, 2, 3, 4, 5)), true);
    $GLOBALS['test']->assert_equals(check_similar(array(1, 2, 3, 5, 4), array(1, 2, 3, 4, 5)), false);
    $GLOBALS['test']->assert_equals(check_similar(array(1, 2, 3), array(1, 2, 3, 4, 5)), false);
    $GLOBALS['test']->assert_equals(check_similar(array(1, 2, 3, 4, 5), array(1, 2, 3)), false);
    $GLOBALS['test']->assert_equals(check_similar(array("Hello" => "World", "Eat" => "bacon", "Drink" => "tea"), array("Hello" => "World", "Eat" => "bacon", "Drink" => "tea")), true);
    $GLOBALS['test']->assert_equals(check_similar(array("Hello" => "World", "Eat" => "bacon"), array("Hello" => "World", "Eat" => "bacon", "Drink" => "tea")), false);
    $GLOBALS['test']->assert_equals(check_similar(array("Hello" => "World", "Eat" => "bacon", "Drink" => "tea"), array("Hello" => "World", "Eat" => "bacon")), false);
    $GLOBALS['test']->assert_equals(check_similar(array("Hello" => "World"), array("Hello" => "World", "Eat" => "bacon", "Drink" => "tea")), false);
    $GLOBALS['test']->assert_equals(check_similar(array("Hello" => "World", "Eat" => "bacon", "Drink" => "tea"), array("Hello" => "World")), false);
  });
  $GLOBALS['test']->it("should work for complex multidimensional arrays (both normal and associative)", function () {
    $GLOBALS['test']->assert_equals(check_similar(array(array(array(array("Hello World")))), "Hello World"), false);
    $GLOBALS['test']->assert_equals(check_similar("Hello World", array(array(array(array("Hello World"))))), false);
    $GLOBALS['test']->assert_equals(check_similar(array(array(array(array("bacon")))), "bacon"), false);
    $GLOBALS['test']->assert_equals(check_similar("bacon", array(array(array(array("bacon"))))), false);
    $GLOBALS['test']->assert_equals(check_similar(array(array(array(array(1)))), 1), false);
    $GLOBALS['test']->assert_equals(check_similar(1, array(array(array(array(1))))), false);
    $GLOBALS['test']->assert_equals(check_similar(array(array(array(array(0)))), 0), false);
    $GLOBALS['test']->assert_equals(check_similar(0, array(array(array(array(0))))), false);
    $GLOBALS['test']->assert_equals(check_similar(array(array(array(array(array(1, 2, 3, 4, 5))))), array(array(array(array(array(1, 2, 3, 4, 5)))))), true);
    $GLOBALS['test']->assert_equals(check_similar(array(1, array(2, array(3, array(4, array(5))))), array(1, array(2, array(3, array(4, array(5)))))), true);
    $GLOBALS['test']->assert_equals(check_similar(array(2, array(1, array(3, array(4, array(5))))), array(1, array(2, array(3, array(4, array(5)))))), false);
    $GLOBALS['test']->assert_equals(check_similar(array(1, array(2, array(3, array(4, array(5))))), array(2, array(1, array(3, array(4, array(5)))))), false);
    $GLOBALS['test']->assert_equals(check_similar(array(
      1,
      3,
      5,
      7,
      8,
      "random key" => "random value",
      67,
      69,
      733,
      "another key" => "another value",
      "a nested array" => array(1, 2, 3, 5, 8, 10),
      "another nested array" => array(
        "key" => "value",
        "another key" => "another value",
        "yet another key" => "value",
        true,
        false,
        1,
        0,
        array(
          3, 4, 5, -23, -45, false, "Hello World", true, array()
        ),
        "random string"
      ),
      "finally" => array(array(3, 1, 5), array("Hello", "World", "key" => "value"))
    ), array(
      1,
      3,
      5,
      7,
      8,
      "random key" => "random value",
      67,
      69,
      733,
      "another key" => "another value",
      "a nested array" => array(1, 2, 3, 5, 8, 10),
      "another nested array" => array(
        "key" => "value",
        "another key" => "another value",
        "yet another key" => "value",
        true,
        false,
        1,
        0,
        array(
          3, 4, 5, -23, -45, false, "Hello World", true, array()
        ),
        "random string"
      ),
      "finally" => array(array(3, 1, 5), array("Hello", "World", "key" => "value"))
    )), true);
  });
});
def id_matrix(size):
    return [[1 if i == j else 0 for j in range(size)] for i in range(size)]