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
  • def ls(dir):
        import os    
        return(os.listdir(dir))
  • 1-import os
    2-print(os.listdir('directorypath'))# Replace 'directorypath' with path to directory
    1+def ls(dir):
    2+ import os
    3+ return(os.listdir(dir))
Code
Diff
  • import java.util.*;
    class Solution {
      
    	      private int[] getNumDigits(int number) {
            int[] digits = new int[10];
    
            while (number != 0) {
                digits[number % 10]++;
                number = number / 10;
            }
    
            return digits;
        }
    
        public int retSmallestPositiveInteger() {
    
            for (int num = 100; num < Integer.MAX_VALUE; num++) {
                boolean isEquals = true;
                int[] digits = getNumDigits(num);
                for (int i = 2; (i <= 6) && isEquals; i++) {
                    isEquals = isEquals && Arrays.equals(digits, getNumDigits(num * i));
                }
                if (isEquals)
                    return num;
            }
            return 0;
        }
    }
  • 11 import java.util.*;
    22 class Solution {
    33
    4-
    5- public static int retSmallestPositiveInteger() {
    6- for(int i=1; ; i++) {
    7- if(hasSameDigits(i, i*2) && hasSameDigits(i, i*3) && hasSameDigits(i, i*4) && hasSameDigits(i, i*5) && hasSameDigits(i, i*6))
    8- return i;
    9- }
    10- }
    11-
    12- private static boolean hasSameDigits(int x, int y) {
    13- char[] xdigits = Integer.toString(x).toCharArray();
    14- char[] ydigits = Integer.toString(y).toCharArray();
    15- Arrays.sort(xdigits);
    16- Arrays.sort(ydigits);
    17- return Arrays.equals(xdigits, ydigits);
    18- }
    4+ private int[] getNumDigits(int number) {
    5+ int[] digits = new int[10];
    6+
    7+ while (number != 0) {
    8+ digits[number % 10]++;
    9+ number = number / 10;
    10+ }
    11+
    12+ return digits;
    13+ }
    14+
    15+ public int retSmallestPositiveInteger() {
    16+
    17+ for (int num = 100; num < Integer.MAX_VALUE; num++) {
    18+ boolean isEquals = true;
    19+ int[] digits = getNumDigits(num);
    20+ for (int i = 2; (i <= 6) && isEquals; i++) {
    21+ isEquals = isEquals && Arrays.equals(digits, getNumDigits(num * i));
    22+ }
    23+ if (isEquals)
    24+ return num;
    25+ }
    26+ return 0;
    27+ }
    1919 }
Fundamentals

My HelloC++ program

Code
Diff
  • #include <iostream>
    
    using namespace std;
    int helloCplusplus(){
      char str[] = "Hello, C++!\n";
      cout << str;
      return 0;
    }
  • 11 #include <iostream>
    2-#include <string>
    33
    3+using namespace std;
    44 int helloCplusplus(){
    5- std::string str = "Hello, C++!";
    6- std::cout << str << '\n';
    5+ char str[] = "Hello, C++!\n";
    6+ cout << str;
    77 return 0;
    88 }

Kumite Experiment!

public class HelloWorld 
{

  public static int Execute()
  {
    System.out.println("My first Kumite");
    return 1;
  }
}
Algorithms
Mathematics
Numbers

The variable x can be from 0 to +∞.

Code
Diff
  • def factorial(x):
        result = 1
        for i in range(2, x+1):
            result *= i
        return result
    
  • 11 def factorial(x):
    2- return 1 if x == 1 else x*factorial(x-1)
    2+ result = 1
    3+ for i in range(2, x+1):
    4+ result *= i
    5+ return result
Code
Diff
  • def sortinggggggggggg (arr) :
      Soreteddddd = sorted (arr)
      print (Soreteddddd)
      return Soreteddddd
    sortinggggggggggg ([2,0,25,3])
    
  • 11 def sortinggggggggggg (arr) :
    22 Soreteddddd = sorted (arr)
    3+ print (Soreteddddd)
    33 return Soreteddddd
    44 sortinggggggggggg ([2,0,25,3])
Code
Diff
  • # caesar cipher shifted of 13 characters with maketrans for python 2.7
    from string import maketrans as mktr, ascii_uppercase as asuc
    
    def caesar(s):
        return s.translate(mktr(asuc, asuc[13:] + asuc[:13]))
    
  • 11 # caesar cipher shifted of 13 characters with maketrans for python 2.7
    2-from string import maketrans
    3-import string
    2+from string import maketrans as mktr, ascii_uppercase as asuc
    3+
    44 def caesar(s):
    5- print(s)
    6- s=s.translate(maketrans(string.ascii_uppercase, string.ascii_uppercase[13:]+string.ascii_uppercase[:13]))
    7- return s
    5+ return s.translate(mktr(asuc, asuc[13:] + asuc[:13]))

Sometimes one has a vector with pairs (key, value), where one wants to fold over all the values with the same key.
What is the best way to do that in Rust?

The example uses a vector, but perhaps it would be better with an iterator as argument, to make it more general?

fn reduce<TK, TV, TS, F>(v : Vec<(TK, TV)>,
                     s : TS,
                     f : F) -> Vec<(TK, TV)>
                     where F : Fn(TS, TV) -> TS {
    // Code
    vec![]
}

Code returns the int that is different from all other ints in an array. Function takes odd size array that contains all the same ints except for 1

int stray(std::vector<int> numbers) {
    
    for(auto n = numbers.begin(); n != numbers.end(); ++n ){
        if (*n != numbers[0]) {
            if (*n != *(n + 1))
                return *n;
            else
                return numbers[0];
        }
    }
};
Strings

Last Character of a string in JS.

Code
Diff
  • const lastChar=(s)=>s.slice(-1)
    
  • 1-def last_char(str):
    2- return str[-1]
    1+const lastChar=(s)=>s.slice(-1)
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char plaintext[100];
char ciphertext[100];
int length;
int key;
  cout<<"enter the plain message\n\n";
  cin.getline(plaintext,99,'\n');
cout<<"enter the key :";
cin>>key;
cout<<"----------\n";
cout<<"the cipher message\n\n";
length=strlen(plaintext);
int i = 0;
	 for(i=0;i<length;i++)
{
	if(plaintext[i]==' ')
{
  ciphertext[i]=' ';
  cout<<ciphertext[i];
  continue;
}
  int y=(int)plaintext[i];
  if (y>96)
{
  y=y-32;
  plaintext[i]=(char)y;
}
int x =((((int)plaintext[i]-65)+key)%26)+65;
ciphertext[i]=(char)x;
cout<<ciphertext[i];
}
cout<<"\n\n";
return(0);
}

Saved some brackets :)

Code
Diff
  • function add(a, b){
      return a- -b;
    }
  • 11 function add(a, b){
    2- return a - (-b);
    2+ return a- -b;
    33 }
Numbers
Integers
Algorithms

Find number of digits with an unrolled div loop.

Code
Diff
  • // Unrolled div loop
    fn digits(mut n: u64) -> usize {
      let mut l = 1;
      loop {
        if n < 10 {
          return l;
        }
        if n < 100 {
          return l + 1;
        }
        if n < 1000 {
          return l + 2;
        }
        if n < 10000 {
          return l + 3;
        }
        n /= 10000;
        l += 4;
      }
    }
  • 1+// Unrolled div loop
    11 fn digits(mut n: u64) -> usize {
    2- let mut l = 1;
    3- while n >= 10 {
    4- n /= 10;
    5- l += 1;
    3+ let mut l = 1;
    4+ loop {
    5+ if n < 10 {
    6+ return l;
    66 }
    7- l
    8+ if n < 100 {
    9+ return l + 1;
    10+ }
    11+ if n < 1000 {
    12+ return l + 2;
    13+ }
    14+ if n < 10000 {
    15+ return l + 3;
    16+ }
    17+ n /= 10000;
    18+ l += 4;
    19+ }
    88 }
Code
Diff
  • {-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-}
    {-# LANGUAGE OverloadedStrings, GADTs, FlexibleContexts, MultiParamTypeClasses #-}
    {-# LANGUAGE NoMonomorphismRestriction, GeneralizedNewtypeDeriving #-}
    module Movies where
    import Database.Persist (insertMany)
    import Database.Persist.Sqlite (runSqlite, runMigration)
    import Database.Persist.TH (mkPersist, mkMigrate, persistUpperCase, share, sqlSettings)
    share [mkPersist sqlSettings, mkMigrate "migrateTables"] [persistUpperCase|
    Movies
       title    String
       year     Int
       rating   Int
       deriving Eq Show
    |]
    
    mkMoviesDB :: IO ()
    mkMoviesDB = runSqlite "/tmp/movies.db" $ do
      runMigration migrateTables
      insertMany
        [ Movies "Rise of the Planet of the Apes" 2011 77
        , Movies "Dawn of the Planet of the Apes" 2014 91
        , Movies "Alien" 1979 97
        , Movies "Aliens" 1986 98
        , Movies "Mad Max" 1979 95
        , Movies "Mad Max 2: The Road Warrior" 1981 100
        ]
      return ()
    
  • 99 Movies
    1010 title String
    1111 year Int
    1212 rating Int
    1313 deriving Eq Show
    1414 |]
    15+
    1515 mkMoviesDB :: IO ()
    1616 mkMoviesDB = runSqlite "/tmp/movies.db" $ do
    1717 runMigration migrateTables
    1818 insertMany
    1919 [ Movies "Rise of the Planet of the Apes" 2011 77
    2020 , Movies "Dawn of the Planet of the Apes" 2014 91
    2121 , Movies "Alien" 1979 97
    2222 , Movies "Aliens" 1986 98
    2323 , Movies "Mad Max" 1979 95
    2424 , Movies "Mad Max 2: The Road Warrior" 1981 100
    2525 ]
    2626 return ()
Code
Diff
  • def is_prime(n)
       n.prime?
    end
  • 11 def is_prime(n)
    2- return false if n < 2
    3- for x in 2.. Math.sqrt(n).round
    4- return false if n % x == 0
    5- end
    6- return true
    2+ n.prime?
    77 end
const html = '<iframe width=100% height=640 src="https://stemkoski.github.io/Three.js/Particle-Engine.html"></iframe>';
console.log(html);
Code
Diff
  • def is_prime(n):
        return n == 2 or n > 1 and all(n % i for i in range(3, int(n**0.5)+1, 2))
  • 11 def is_prime(n):
    2- return n > 1 and all(n % i for i in range(2, int(n**0.5)+1))
    2+ return n == 2 or n > 1 and all(n % i for i in range(3, int(n**0.5)+1, 2))
Code
Diff
  • def distance_count(x, y):
        return sum((xi-yi)**2 for xi, yi in zip(x, y))**0.5
    
  • 1-def distance_count(a,b):
    2- return sum([(i-j)**2 for (i,j) in zip(a,b)])**0.5
    3-
    1+def distance_count(x, y):
    2+ return sum((xi-yi)**2 for xi, yi in zip(x, y))**0.5
Code
Diff
  • def get_list(l):
        return ' '.join(l)
  • 1-def get_list(may):
    2- new_str = ''
    3- for i in may:
    4- new_str += i + ' '
    5- return new_str[:-1]
    1+def get_list(l):
    2+ return ' '.join(l)
console.log('Hola mundo');
Ruby on Rails
Frameworks
rails
Ruby Gems

In this varation, I have refactored the code so that the execute helper wraps up the transaction rollback as part of its method call. It also will try to parse the response as json and provide that as the 2nd argument, DRYing up the code as more tests are added.

Mathematics
Algorithms
Numbers

Removed duplicate code and multiple executions of fmod by calculating it before all the places where it's needed, reducing probability of copy/paste error and slightly improving performance.
Also added a space before every left bracket, for readability (personal preference).

Code
Diff
  • function calcTokenCost($price, $token) {
        if ($price == 0 && $token == 0) {
            return 0;
        }
        if ($price < $token) {
            return $token;
        }
        $mod = fmod($price, $token);
        if ($mod < ($token / 2)) {
            return $price - $mod;
        }
        return $price + $token - $mod;
    }
  • 1-function calcTokenCost($price, $token){
    2- if ($price == 0 && $token == 0){
    1+function calcTokenCost($price, $token) {
    2+ if ($price == 0 && $token == 0) {
    33 return 0;
    44 }
    5- if ($price < $token){
    5+ if ($price < $token) {
    66 return $token;
    77 }
    8- if (fmod($price, $token) < ($token / 2)){
    9- return $price - fmod($price, $token);
    8+ $mod = fmod($price, $token);
    9+ if ($mod < ($token / 2)) {
    10+ return $price - $mod;
    1010 }
    11- return $price + $token - fmod($price, $token);
    12+ return $price + $token - $mod;
    1212 }
hsamuelsonFailed Tests

R Tests

plot a quadradic from 0-10, with the equation x^2

print("Hellow")
#THis doesnt work becasue R is not supported yet

It is usefull for algorithmic tasks, where your code has to have certain complexity. It is not a save way of using In/out, so I woudln't reccomend using it somewhere else besides webpages like SPOJ etc. where programms read from standard input and write to standard output. It should compile with newest gcc and -std=c++11 flag.
Try to write your own functions for fixed point types and cstrings! =)

Bibliography:
http://www.algorytm.edu.pl/fast-i-o.html

#include <cstdio>

template <class type>
inline void getUI ( type* des ) // reads unsigned integer from input
{
  register char c = 0;
  while ( c <= ' ' ) c = getc_unlocked(stdin);
  (*des) = 0;
  while ( c > ' ' )
  {
    (*des) = (*des) * 10 + ( c - '0' );
    c = getc_unlocked(stdin);
  }
}
template <class type>
inline void putUI ( type src ) // writes unsigned integer to output
{
  if ( src == 0 )
  {
    putc_unlocked( '0', stdout );
    return;
  }
  register char c [21];
  register short k = 0;
  while ( src > 0 )
  {
    c[k ++] = src % 10 + '0';
    src /= 10;
  }
  -- k;
  while ( k >= 0 )
    putc_unlocked( c[k --], stdout );
}

int main ()
{
  putUI(2000);
}
Code
Diff
  • const exec = require('child_process').exec;
    
    function parse(error, stdout, stderr) {
      if (error) throw error;  
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);
    }
    
    // gives an error I don't understand but I guess the below command sort of works. 
    // exec('npm -g list', (err, stdout, stderr) => parse(err, stdout, stderr));
    
    exec('ls ../../runner/node_modules', (err, stdout, stderr) => parse(err, stdout, stderr));
  • 1-from subprocess import call
    2-call(["pip", "freeze"])
    1+const exec = require('child_process').exec;
    2+
    3+function parse(error, stdout, stderr) {
    4+ if (error) throw error;
    5+ console.log(`stdout: ${stdout}`);
    6+ console.log(`stderr: ${stderr}`);
    7+}
    8+
    9+// gives an error I don't understand but I guess the below command sort of works.
    10+// exec('npm -g list', (err, stdout, stderr) => parse(err, stdout, stderr));
    11+
    12+exec('ls ../../runner/node_modules', (err, stdout, stderr) => parse(err, stdout, stderr));
Code
Diff
  • print("Hello World")
  • 1-cat("Hello World!\n")
    1+print("Hello World")
Testing

When writing python katas, you might want to create modules that can be imported by the solution or tests.

This kata shows how to by manipulating sys.path to allow importing from /home/codewarrior folder and writing a python file there.

import sys
HOME_DIR = '/home/codewarrior'

def make_module(module_name):
    if HOME_DIR not in sys.path:
        sys.path.append(HOME_DIR)

    moduleContent = 'foo = lambda x: x+1'
    with open('{}/{}.py'.format(HOME_DIR, module_name), 'w') as moduleFile:
        moduleFile.write(moduleContent)

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

function lowestPermutedMultiple(n) {
    let base = n;
    let numDigits = n.toString().length;
    let i = 1;
    let solution = i;
    while ((n * i).toString().length <= numDigits) {
        if (base.toString().split('').sort().join('') == (n*i).toString().split('').sort().join('')) {
            solution = i;
        }
        i++;
    }
    return solution;
}
Code
Diff
  • SELECT name FROM greetings
    WHERE upper(greeting) like '%HELLO%';
  • 11 SELECT name FROM greetings
    2-WHERE greeting='Hello';
    2+WHERE upper(greeting) like '%HELLO%';

I needed to iterate a block on a value n times and return the value to solve a kata. Getting f(f(..f(x)..)) applying f n times. This is the trivial solution:

n.times do
  x = f.call(x)
end
return x

As times returns n rather than anything in the block a separate return x is needed after the block. Also x = modified x is needed. Wouldn't it be nice to have something built in for this purpose? like

x.modify(n, &block)

It turns out that we can achieve something pretty close to this with the built in inject. As times without a block returns an Enumerator, as most Enumerable functions do, (yielding increasing numbers), with the daisy chaining of Enumerables, using only the accumulator of inject this works fine:

n.times.inject(x) { |x| block.call(x) }

However this doesn't work :( as inject in this case feeds in the index:

n.times.inject(x, &block)
class Object
  def modify(n)
    return to_enum :modify unless block_given?
    case n
    when Enumerator then n.each.inject(self) { |acc| yield(acc) }
    when Numeric    then n.times.inject(self) { |acc| yield(acc) }
    end    
  end
end

p 5.modify 2.times, &:~@ # flipping bits twice

A really arcaic calculator for pi, that takes ages to get a little precision.

var ex431 = function(tries){
    var inc=0, outc=0, x, y;
    
    while(tries>0){
        x =  Math.random();
        y =  Math.random();
        
        if (x*x + y*y <= 1) inc++;
        else outc++;
        tries--;
    }
    return inc/(inc+outc);
}

Changed s.ToLower() → s.ToUpperInvariant(), fitting msdn recommended best practices for strings.

Code
Diff
  • using System;
    using System.Linq;
    
    public class Kata
    {
        public static int DuplicateCount(string s) => 
            s.ToUpperInvariant()
             .GroupBy(c => c)
             .Count(g => g.Skip(1).Any());
    }
  • 11 using System;
    22 using System.Linq;
    33
    44 public class Kata
    55 {
    66 public static int DuplicateCount(string s) =>
    7- s.ToLower()
    8- .GroupBy(c => c)
    9- .Count(g => g.Skip(1).Any());
    7+ s.ToUpperInvariant()
    8+ .GroupBy(c => c)
    9+ .Count(g => g.Skip(1).Any());
    1010 }
dpleshkovFailed Tests

Quine

This is a quine in Python 2 (Will not work in 3).

_='_=%r;print _%%_';print _%_
Code
Diff
  • module NCR where
    
    --Combinations nCr
    comb:: Integer -> Integer -> Integer
    comb n r = factorial n `div` (factorial r * factorial (n-r))
      where
      factorial n = foldr (*) 1 [2..n]
  • 11 module NCR where
    22
    33 --Combinations nCr
    44 comb:: Integer -> Integer -> Integer
    5-comb n r | n/=r = (factorial n) `div` (factorial r * factorial (n-r) )
    6- | n==r = (factorial n) `div` (factorial r)
    7-
    8-factorial n= foldl (*) 1 [1..n]
    5+comb n r = factorial n `div` (factorial r * factorial (n-r))
    6+ where
    7+ factorial n = foldr (*) 1 [2..n]

Allow for passing parents into the constructor. Also, add some spaces to make code consistent. Also, avoid mutating parents array, just for the sake of it.

Code
Diff
  • class Human {
      constructor (firstName = '', lastName = '', parents = []) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.parents = parents;  // modern family. who takes parental care?
      }
      
      filterMyFamily(humans) {
        return humans.filter(human => human.lastName === this.lastName)
      }
      
      hasParent(p) {
        return this.parents.some(parent => parent === p);
      }
      
      hasChild(c) {
        return c.hasParent(this);
      }
      
      addParent(p) {
        if (!this.hasParent(p)) this.parents = [ ...this.parents, p ];
        return this;
      }
    }
  • 11 class Human {
    2- constructor (firstName = '', lastName = '') {
    2+ constructor (firstName = '', lastName = '', parents = []) {
    33 this.firstName = firstName;
    44 this.lastName = lastName;
    5- this.parents = []; // modern family. who takes parental care?
    5+ this.parents = parents; // modern family. who takes parental care?
    66 }
    7+
    77 filterMyFamily(humans) {
    88 return humans.filter(human => human.lastName === this.lastName)
    99 }
    1010
    11- addParent(p){
    12- if (!this.hasParent(p)) this.parents.push(p);
    13- return this;
    12+ hasParent(p) {
    13+ return this.parents.some(parent => parent === p);
    1414 }
    1515
    16- hasChild(c){
    16+ hasChild(c) {
    1717 return c.hasParent(this);
    1818 }
    1919
    20- hasParent(p){
    21- return this.parents.some(parent => parent === p);
    20+ addParent(p) {
    21+ if (!this.hasParent(p)) this.parents = [ ...this.parents, p ];
    22+ return this;
    2222 }
    2323 }

That's a simple threading test using JavaFX. It currently has troubles due to codewars JVM runner.

package codigosjava.modernizandohilos;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;

/**
 * Created by Javatlacati on 08/02/2017.
 */
public class Aciago extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Thread miHilo = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Corriendo");
                while (true) {
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("ola soi un hilo :v");
                        }
                    });

                    try {
                        System.out.println("anuma me voi a dormir");
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                        System.err.println("#PosMeMuero");
                        break;
                    }
                }
            }
        }
        );

        miHilo.setName("soy el mapa soy el mapa soy el mapa soy el mapa soy el mapa!");
        miHilo.setDaemon(true);
        miHilo.start();
    }
}

Any help is welcome :)

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Javatlacati on 07/02/2017.
 */
public class ThreadIssueSolution extends ScheduledThreadPoolExecutor {
    public boolean isUsable=true;
    public ThreadIssueSolution() {
        super(1);
    }

    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
        return super.scheduleAtFixedRate(wrapRunnable(command), initialDelay, period, unit);
    }

    @Override
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
        return super.scheduleWithFixedDelay(wrapRunnable(command), initialDelay, delay, unit);
    }

    private Runnable wrapRunnable(Runnable command) {
        return new LogOnExceptionRunnable(command);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
//        super.afterExecute(r, t);
        if(!(t == null && r == null)){
            throw new ArithmeticException("ooops");
        }
    }

    private class LogOnExceptionRunnable implements Runnable {
        private Runnable theRunnable;

        public LogOnExceptionRunnable(Runnable theRunnable) {
            super();
            this.theRunnable = theRunnable;
        }

        @Override
        public void run() {
            try {
                theRunnable.run();
            } catch (Throwable e) {
               System.err.println("error ejecutando: " + theRunnable + ". no seguirá corriendo!");
                //e.printStackTrace();
                // and re throw it so that the Executor also gets this error so that it can do what it would
                // usually do
                throw new RuntimeException(e);
            }
        }
    }
}
Code
Diff
  • package main
    
    import "fmt"
    
    func main() {
        var age int
        fmt.Printf("Enter your age on Earth: ")
        _, err := fmt.Scanf("%d", &age)
        if (err != nil) {
            fmt.Println(err)
        }
        age = age * 365 / 687
        fmt.Printf("Your age on the surface of Mars is %d years old.\n", age)
    }
  • 11 package main
    22
    33 import "fmt"
    44
    55 func main() {
    6- age := 28 * 365 / 687
    7- fmt.Printf("My age on the surface of Mars is %d years old.\n", age)
    6+ var age int
    7+ fmt.Printf("Enter your age on Earth: ")
    8+ _, err := fmt.Scanf("%d", &age)
    9+ if (err != nil) {
    10+ fmt.Println(err)
    11+ }
    12+ age = age * 365 / 687
    13+ fmt.Printf("Your age on the surface of Mars is %d years old.\n", age)
    88 }

Test output documentation: https://github.com/Codewars/codewars-runner-cli/blob/00a657c99f347ef8ecb075b8a19ebab7d8fc1535/documentation/output_format.md#nested-describes

If you print '<COMPLETEDIN::>' after a Test.describe() or Test.it(), you can close describe/it groupings and have a nested structure like you can for the other languages.

def hi():
    return 'hi'


# https://github.com/Codewars/codewars-runner-cli/blob/00a657c99f347ef8ecb075b8a19ebab7d8fc1535/documentation/output_format.md#nested-describes
# use this to close Test.describe and Test.it groupings
def close_group():
    print('<COMPLETEDIN::>')


close_describe = close_it = close_group;
let projectEulerProblemOne = [1 .. 999] |> List.filter(fun x -> x % 3 = 0 || x % 5 = 0) |> List.sum
Code
Diff
  • const countLetterInSentence = (sentence, letter) => ([...sentence].filter(test => letter === test).length)
    
    function countLettersInSentence(sentence, letters){
      return letters.map(letter => countLetterInSentence(sentence, letter))
    }
  • 1-function testAmount(sentence, letters){
    2- return letters.map(letter =>
    3- [...sentence].filter(test => letter === test).length)
    1+const countLetterInSentence = (sentence, letter) => ([...sentence].filter(test => letter === test).length)
    2+
    3+function countLettersInSentence(sentence, letters){
    4+ return letters.map(letter => countLetterInSentence(sentence, letter))
    44 }
Code
Diff
  • const longestString = str => str.split(' ').reduce((a, b) => b.length > a.length ? b : a);
  • 1-var longestString = (str) => str.split(' ').sort((a, b) => b.length - a.length)[0];
    1+const longestString = str => str.split(' ').reduce((a, b) => b.length > a.length ? b : a);
Code
Diff
  • def myMap(mine):
        return [i+1 for i in mine]    
  • 11 def myMap(mine):
    2- l = [i+1 for i in mine]
    3- return l
    4-
    2+ return [i+1 for i in mine]
Code
Diff
  • from itertools import *
    
    def groups_combinations(arr2D):
        res = list(product(*arr2D))
        return [len(res), res]
        
    
  • 11 from itertools import *
    2-def product_(arr2D):
    3- return product(*arr2D)
    44
    55 def groups_combinations(arr2D):
    6- res = []
    7- for comb in product_(arr2D):
    8- res.append(comb)
    4+ res = list(product(*arr2D))
    99 return [len(res), res]
    1010

This is possible because python has mutable default arguments. It is functionally the same as the lrucache approach (though arguably less pythonic)

I like this approach because it allows you to reset the cache when needed, while also keeping it between problems, so if you want to keep looking for fib numbers, the memoization is already done, but if you're using this method for something like kepping track of visited nodes in a graph, you can just clear the cache every time you make a new graph.

Code
Diff
  • def fib(n, memo = {0:1, 1:1}):
        if n not in memo:
            memo[n] = fib(n-1)+fib(n-2)
        return memo[n]
        
  • 1-def fib(n):
    2- memo = {0:1, 1:1}
    3- def recursiveFib(n):
    4- if n not in memo:
    5- memo[n] = recursiveFib(n-1)+recursiveFib(n-2)
    6- return memo[n]
    7- return recursiveFib(n)
    1+def fib(n, memo = {0:1, 1:1}):
    2+ if n not in memo:
    3+ memo[n] = fib(n-1)+fib(n-2)
    4+ return memo[n]
    88

Javascript version of fast code to get all the proper factors of a number

var sortNumber = function(a, b){return a - b;};

function getDiv(n){
    var factL= [], i;
    for (i = 1; i <= Math.floor(Math.sqrt(n)); i += 1) {
        if (n % i === 0) {
            factL.push(i);
            if (n / i !== i) factL.push(n / i);
        }
    }
    factL.sort(sortNumber);
    return factL;
}

We have n different groups of elements and we want to know all the possible combinations of n elements from these groups.
Each combinations should be formed having one element from each group.
The function generates all the possible different combinations.

function groupCombinations_() {
    var r = [], arg = arguments, max = arg.length-1;
    function helper(arr, i) {
        for (var j=0, l=arg[i].length; j<l; j++) {
            var a = arr.slice(0); 
            a.push(arg[i][j]);
            if (i==max)
                r.push(a);
            else
                helper(a, i+1);
        }
    }
    helper([], 0);
    return r;
}

function groupCombinations(arr2D) {
    var combL = groupCombinations_.apply(this, arr2D);
    return [combL.length, combL];
}

We have n different groups of elements and we want to know all the possible combinations of n elements from these groups.
Each combinations should be formed having one element from each group.
The function generates all the possible different combinations.

def groups_combination_(a)
	  a[1..-1].inject(a[0]){ |m,v| m = m.product(v).map(&:flatten) }
end

def groups_combinations(arr2D)
    res = groups_combination_(arr2D)
    return [res.length, res]
end

Prints "Hello, Obj-c"

#import <Foundation/Foundation.h>

NSString *helloObjC(NSString *language) {
  NSLog(@"Hello, %@!\n", language);
  return "Hello Obj-C!";
}
Code
Diff
  • function isPrime(n) {
        if (n < 2)
          return false;
        // do an early exit for even numbers
        if (n == 2)
          return true;
        if (n % 2 == 0)
          return false;
        // we only have to check odd numbers, starting with 3
        for (var x = 3; x <= Math.floor(Math.sqrt(n)); x += 2)
          if (n % x == 0)
            return false;
        return true;
    }
  • 11 function isPrime(n) {
    2- if (n < 2) return false;
    3- for (var x = 2; x <= Math.floor(Math.sqrt(n)); x++) {if (n % x == 0) return false;}
    2+ if (n < 2)
    3+ return false;
    4+ // do an early exit for even numbers
    5+ if (n == 2)
    6+ return true;
    7+ if (n % 2 == 0)
    8+ return false;
    9+ // we only have to check odd numbers, starting with 3
    10+ for (var x = 3; x <= Math.floor(Math.sqrt(n)); x += 2)
    11+ if (n % x == 0)
    12+ return false;
    44 return true;
    55 }

The checkWorkHours(dateTime time.Time) function accepts a time.Time object and returns true or false if the time given is within work hours.

Includes a function to test the outputs of your function.

package main

import (
	"fmt"
	"time"
)

func main() {
	testCheckWorkHours()
}

func checkWorkHours(dateTime time.Time) bool {
	beginWorkHour := 8
	endWorkHour := 18

	currentHour := dateTime.Hour()
	currentDay := dateTime.Weekday()

	if currentDay > 0 && currentDay < 6 {
		if currentHour < endWorkHour && currentHour >= beginWorkHour {
			return true
		}
	}

	return false
}

func testCheckWorkHours() {
	// Tests the function
	timeFormat := "2006-01-02 15:04:05 -0700 MST"

	// True Cases
	dateTime, _ := time.Parse(timeFormat, "2017-01-16 15:00:00 -0500 EST")
	fmt.Println(fmt.Sprintf("Monday @ 3pm should be True: %t", checkWorkHours(dateTime)))

	dateTime, _ = time.Parse(timeFormat, "2017-01-16 17:59:59 -0500 EST")
	fmt.Println(fmt.Sprintf("Friday @ 5:59pm should be True: %t", checkWorkHours(dateTime)))

	// False Cases
	dateTime, _ = time.Parse(timeFormat, "2017-01-15 15:00:00 -0500 EST")
	fmt.Println(fmt.Sprintf("Sunday @ 3pm should be False: %t", checkWorkHours(dateTime)))

	dateTime, _ = time.Parse(timeFormat, "2017-01-13 18:00:00 -0500 EST")
	fmt.Println(fmt.Sprintf("Friday @ 6pm should be False: %t", checkWorkHours(dateTime)))

	dateTime, _ = time.Parse(timeFormat, "2017-01-17 07:00:00 -0500 EST")
	fmt.Println(fmt.Sprintf("Tuesday @ 7am should be False: %t", checkWorkHours(dateTime)))
}
Code
Diff
  • import random
    
    
    def rabinMiller(num):
        s = num - 1
        t = 0
        while s % 2 == 0:
            s = s // 2
            t += 1
    
        for trials in range(5):
            a = random.randrange(2, num - 1)
            v = pow(a, s, num)
            if v != 1:
                i = 0
                while v != (num - 1):
                    if i == t - 1:
                        return False
                    else:
                        i = i + 1
                        v = (v ** 2) % num
        return True
    def is_prime(num):
        if (num < 2):
            return False
        lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
        if num in lowPrimes:
            return True
        for prime in lowPrimes:
            if (num % prime == 0):
                return False
        return rabinMiller(num)
  • 11 import random
    2-
    3-def decompose(n):
    4- exponentOfTwo = 0
    5- while n % 2 == 0:
    6- n = n/2
    7- exponentOfTwo += 1
    8- return exponentOfTwo, n
    9-
    10-def isWitness(possibleWitness, p, exponent, remainder):
    11- possibleWitness = pow(possibleWitness, remainder, p)
    12- if possibleWitness == 1 or possibleWitness == p - 1:
    13- return False
    14- for _ in range(exponent):
    15- possibleWitness = pow(possibleWitness, 2, p)
    16- if possibleWitness == p - 1:
    17- return False
    2+
    3+
    4+def rabinMiller(num):
    5+ s = num - 1
    6+ t = 0
    7+ while s % 2 == 0:
    8+ s = s // 2
    9+ t += 1
    10+
    11+ for trials in range(5):
    12+ a = random.randrange(2, num - 1)
    13+ v = pow(a, s, num)
    14+ if v != 1:
    15+ i = 0
    16+ while v != (num - 1):
    17+ if i == t - 1:
    18+ return False
    19+ else:
    20+ i = i + 1
    21+ v = (v ** 2) % num
    1818 return True
    19-
    20-def is_prime(p, accuracy=100):
    21- if p == 2 or p == 3: return True
    22- if p < 2: return False
    23- exponent, remainder = decompose(p - 1)
    24- for _ in range(accuracy):
    25- possibleWitness = random.randint(2, p - 2)
    26- if isWitness(possibleWitness, p, exponent, remainder):
    23+def is_prime(num):
    24+ if (num < 2):
    25+ return False
    26+ lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
    27+ if num in lowPrimes:
    28+ return True
    29+ for prime in lowPrimes:
    30+ if (num % prime == 0):
    2727 return False
    28- return True
    32+ return rabinMiller(num)

A very easy method importting the library prime in Ruby. It's a bit slower than the last code we've seen in Ruby

require 'prime'

def is_prime(n)
    Prime.prime?(n)
end

Again we can see that the runtime is less (more less than a half) than the previous version

def is_prime(n)
    return false if n < 2
    return true if n == 2
    return false if n % 2 == 0
    (3..Math.sqrt(n).round).step(2) do |x|
        return false if n % x == 0
    end
    return true
end

I received a fork to my version in python by the user Mc Code. The average runtime for different tries is under 500 ms. The half runtime that the previous version in Javascript, too (1000 ms)

function isPrime(n) {
    if (n < 2) return false;
    else if (n == 2) return true;
    else if (n % 2 === 0) return false;
    for (var x = 3; x <= Math.floor(Math.sqrt(n)); x += 2) {if (n % x === 0) return false;}
    return true;
}

We can turn this into a one-liner (minus the import)

Code
Diff
  • from math import sqrt
    
    is_prime = lambda n: n == 2 or (n > 2 and n % 2 != 0 and all(n % x != 0 for x in range(3, int(sqrt(n)) + 1, 2)))
    
    
  • 11 from math import sqrt
    22
    3+is_prime = lambda n: n == 2 or (n > 2 and n % 2 != 0 and all(n % x != 0 for x in range(3, int(sqrt(n)) + 1, 2)))
    33
    4-def is_prime(n):
    5- if n < 2:
    6- return False
    7- elif n == 2:
    8- return True
    9- elif n % 2 == 0:
    10- return False
    11-
    12- for x in range(3, int(sqrt(n)) + 1, 2):
    13- if n % x == 0:
    14- return False
    15-
    16- return True

This is the real "bubble sort", your implementation similar to "selection sort" =)

Code
Diff
  • package main
    
    import "fmt"
    
    func bubble_sort(dataset []int){
      for i := 1; i <= len(dataset)-1; i++ {
        
          if dataset[i] >= dataset[i-1] { continue }
          
          var y int = dataset[i]
          var j int = i - 1
          
          for {
    	      if j < 0 || dataset[j] <= y { break }
          	dataset[j+1] = dataset[j]
    	      j--
          }
          
          dataset[j+1] = y
      }
    }
    
    
    func main(){
    
      dataset := []int{5, 2, 4, 6, 1, 3, 15, 6, 23645, 23, 462, 2, 2, -12};
    
      fmt.Println(dataset)
    
      bubble_sort(dataset);
    
      fmt.Println(dataset)
    }
    
  • 11 package main
    22
    33 import "fmt"
    44
    5-func swap(dataset []int, a, b int) {
    6- var x int = dataset[a]
    7- dataset[a] = dataset[b]
    8- dataset[b] = x
    9-}
    10-
    1111 func bubble_sort(dataset []int){
    12- for i := 0; i <= len(dataset)-1; i++ {
    13- for j := len(dataset)-1; j >= i + 1; j-- {
    14- if dataset[j] < dataset[j-1] {
    15- swap(dataset, j, j - 1)
    6+ for i := 1; i <= len(dataset)-1; i++ {
    7+
    8+ if dataset[i] >= dataset[i-1] { continue }
    9+
    10+ var y int = dataset[i]
    11+ var j int = i - 1
    12+
    13+ for {
    14+ if j < 0 || dataset[j] <= y { break }
    15+ dataset[j+1] = dataset[j]
    16+ j--
    1616 }
    17- }
    18+
    19+ dataset[j+1] = y
    1818 }
    1919 }
    2020
    2121
    2222 func main(){
    2323
    24- dataset := []int{5, 2, 4, 6, 1, 3};
    26+ dataset := []int{5, 2, 4, 6, 1, 3, 15, 6, 23645, 23, 462, 2, 2, -12};
    2525
    2626 fmt.Println(dataset)
    2727
    2828 bubble_sort(dataset);
    2929
    3030 fmt.Println(dataset)
    3131 }
Code
Diff
  • public class Dinglemouse {
    
      // Use CSS to display a pretty version of the flap display
      // From: https://www.codewars.com/kata/airport-arrivals-slash-departures-number-1/java
      public static String[] prettyPrint(final String[] lines) {
        String s = "";
        for (int y = 0; y < lines.length; y++) {
          s += "<div style=\"height:23px\">";
          for (int x = 0; x < lines[y].length(); x++) {
            s += "<span style=\"font-size:10px;color:yellow;padding:5px;border:1px solid gray;background:black\">"+lines[y].charAt(x)+"</span>";
          }
          s += "</div>";
        }
        System.out.println(s);
        return lines;
      }
    
    }
  • 11 public class Dinglemouse {
    22
    33 // Use CSS to display a pretty version of the flap display
    44 // From: https://www.codewars.com/kata/airport-arrivals-slash-departures-number-1/java
    55 public static String[] prettyPrint(final String[] lines) {
    6- String s = "<pre>";
    6+ String s = "";
    77 for (int y = 0; y < lines.length; y++) {
    88 s += "<div style=\"height:23px\">";
    99 for (int x = 0; x < lines[y].length(); x++) {
    1010 s += "<span style=\"font-size:10px;color:yellow;padding:5px;border:1px solid gray;background:black\">"+lines[y].charAt(x)+"</span>";
    1111 }
    1212 s += "</div>";
    1313 }
    14- s+= "</pre>";
    1515 System.out.println(s);
    1616 return lines;
    1717 }
    1818
    1919 }
Mathematics
Algorithms
Numbers
Fundamentals
Code
Diff
  • const dice = _ => -~(Math.random()*6);
  • 1-const dice=_=>~~(Math.random()*6)+1;
    1+const dice = _ => -~(Math.random()*6);