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

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

The Itertools module offers a the generator permutations that gives a permutation as a tuple, each time. Nevertheless the result will not be printed because some outputs are huge.

from itertools import *

def permut(arr):
    resL = []
    for perm in permutations(arr):
        resL.append(list(perm))
    return resL
Algorithms
Logic
(ns quicksort.core)

(defn quick-sort [nums]
  (if (< (count nums) 2) nums
    (concat
      (quick-sort (filter #(< % (first nums)) nums))
      (filter #(= % (first nums)) nums)
      (quick-sort (filter #(> % (first nums)) nums)))))

Shows how to use bash kta and how to create simple tests

echo Hello Bash!

When we want to generate primes we may have problems of memory if we use cumulative data structures. The following code generates each prime lazely using a generator instead of a function. To generate the prime numbers we use a primality test as a helper function

function isPrime(n) {
    if (n%1 || n<2) return false;
    var upper = Math.round(Math.pow(n, 1/2.0));
    for (var i = 2;i <= upper; i++) if (n % i == 0) return false;
    return true;
}

function *primeGener() {
    var i = 0;
    while(true) {
        if(isPrime(i)) yield i;
        i += 1;
    }
}

function countPrimes(limit) {
    var count = 0, call = primeGener();
    while(true) {
        var prime = call.next().value;
        if (prime > limit) break;
        count++
    }
    return count
}