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
import numpy

def primes(n):
    sieve = numpy.ones(n/3 + (n%6==2), dtype=numpy.bool)
    for j in xrange(1,int(n**0.5)/3+1):
        if sieve[j]:
            k=3*j+1|1
            sieve[k*k/3::2*k] = False
            sieve[k*(k-2*(j&1)+4)/3::2*k] = False
    return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]

def primes_less_than(n):
    #n should be higher or equal 6. If n is a prime will not be part of the result """
    return primes(n).tolist()
require 'prime'

def primes_less_than(n)
    Prime.take_while {|p| p < n }
end
function primesLessThan(limit) {
    var primes = [];
    if (limit >= 2) {
        var sqrtlmt = Math.sqrt(limit) - 2;
        var nums = new Array(); // start with an empty Array...
        for (var i = 2; i <= limit; i++) // and
            nums.push(i); // only initialize the Array once...
        for (var i = 0; i <= sqrtlmt; i++) {
            var p = nums[i]
            if (p)
                for (var j = p * p - 2; j < nums.length; j += p)
                    nums[j] = 0;
        }
        for (var i = 0; i < nums.length - 1; i++) {
            var p = nums[i];
            if (p) primes.push(p);
        }
    }
    return primes;
}
JavatlacatiFailed Tests

Kotlin

Kotlin Hello World modified to show some language features

/**
 * Created by Javatlacati on 26/10/2016.
 */
object LambdaKotlin {
    @JvmStatic
    fun main(args: Array<String>) {
        val arr=arrayOf("hola","mundo","cruel")
        arr.forEach {
            println(it)
        }
    }
}

The following code will output a 2Darray with all the elements present in the array as keys and their corresponding occurrences sorted by the value of the element.

from collections import Counter

def count_occur_each_element(arr):
    if arr == []: return []
    return sorted(map(list, Counter(arr).items()))
def counter(arr)
    counts = Hash.new 0
    arr.each do |n|
        counts[n] += 1
    end
    return counts
end

def count_occur_each_element(arr)
    if arr == []
        return []
    end
    count_pairs = []
    counts = counter(arr)
    counts.each do |k, v|
        count_pairs << [k, v]
    end
    count_pairs.sort!
    return count_pairs
end

Try to upgrade codewars haskell-runner ghc to new version but fail one test.

Code extract from test/runner/haskell_spec.js

This code run fine here but failed on stackage lts-1.0 w/ ghc7.6.3

test.hs:38:12: error:
    • Couldn't match type ‘IO ()’ with ‘() -> IO ()’
      Expected type: ActionWith ()
        Actual type: IO ()
    • Possible cause: ‘deleteIfExists’ is applied to too many arguments
      In the first argument of ‘after’, namely
        ‘(deleteIfExists moviesDBFileName)’
      In the expression: after (deleteIfExists moviesDBFileName)
      In the second argument of ‘($)’, namely
        ‘after (deleteIfExists moviesDBFileName)
         $ do { it "contains the movies we expect"
                $ do { mkMoviesDB;
                       movies <- getMovies;
                       .... } }’
{-# 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 ()

Given a certain integer n, the following code gives a 2D array with all the possible and different partitions of n.
The array is sorted by the length of each partition that is the number od addens of each partition. Each partition has the addens sorted.

function fillArray(value, len) {
  if (len === 0) return [];
  var a = [value];
  while (a.length * 2 <= len) a = a.concat(a);
  if (a.length < len) a = a.concat(a.slice(0, len - a.length));
  return a;
}
 
function partitions(n){
	var resL = [];
    var a = fillArray(1, n), y = -1, v = n;
    while (v > 0) {
        v -= 1;
        x = a[v] + 1;
        while (y >= 2 * x) {
            a[v] = x;
            y -= x;
            v += 1;
        }
        var w = v + 1;
        while (x <= y) {
            a[v] = x;
            a[w] = y;
            resL.push(a.slice(0,w + 1));
            x += 1;
            y -= 1;
        }
        a[v] = x + y;
        y = a[v] - 1;
        resL.push(a.slice(0,w));
    }
    return resL;
}

Given a certain integer n, the following code gives a 2D array with all the possible and different partitions of n.
The array is sorted by the length of each partition that is the number od addens of each partition. Each partition has the addens sorted.

def partitions_(n):
    ind = 1
    sub = n - 1
    list_ = [0 for i in range(n + 1)]
    while True:
        if ind == 0: break
        elem = list_[ind - 1] + 1
        ind -= 1
        while True:
            if 2 * elem > sub: break
            list_[ind] = elem
            sub -= elem
            ind += 1
        l = ind + 1
        while True:
            if elem > sub: break
            list_[ind] = elem
            list_[l] = sub
            yield list_[:ind + 2]
            elem += 1
            sub -= 1
        list_[ind] = elem + sub
        sub = elem + sub - 1
        yield list_[:ind + 1]
        
def partitions(n):
    resL = []
    for part in partitions_(n):
        resL.append(part)
    return resL

We will obtain a tuple of length 2:
the first element is a 2D array with all the permutations that the same length of the array. If all the elements are unique in the array the the output will have a length equals to (length_array)!. As we will use arrays of elements that occurs once the function will ouput a boolean showing that the number of permutations is equal to the length of the given array, this will be the second element of the tuple

from math import factorial

def permutations_(arr, r=None): # see at https://docs.python.org/2/library/itertools.html
    pool = tuple(arr)           # it generates a permutation at once (lazely)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = range(n)
    cycles = range(n, n-r, -1)
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return
            
def permutations(arr):
    resL = []
    for perm in permutations_(arr):
        resL.append(list(perm))
    return resL, len(resL) == factorial(len(arr))