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
  • Number.prototype.times = function (f) {
      for (let i = 0; i < this; i++) f(i);
    }
  • 11
    Number.prototype.times = function (f) {
    
    2
      for (let i = 0; i < this; i++) {
    
    3
        f(i);
    
    4
      }
    
    2+
      for (let i = 0; i < this; i++) f(i);
    
    55
    }
    
Code
Diff
  • let greetLanguage = (greeting = "Hello", language = "Javascript") => `${greeting}, ${language}!`;
  • 1
    function greetLanguage(greeting = "Hello", language = "Javascript") {
    
    2
      var result = `${greeting}, ${language}!`;
    
    3
      console.log(result);
    
    4
      return result;
    
    5
    }
    
    1+
    let greetLanguage = (greeting = "Hello", language = "Javascript") => `${greeting}, ${language}!`;
    

Recent Moves:

write one compare function.

  • first compare with string's length
  • when string have same length, then compare string with lex order.
module CmpStr where

import Data.Function
import Data.Monoid

cmpStr :: String -> String -> Ordering
cmpStr = (compare `on` length) `mappend` compare

Haskell is lazy, so we could get infinite sequence naturally.

like this.

module InfiniteSeq where

import Data.List

ones = repeat 1
nats = [0..]

merge = concat . transpose
merge2 x y = merge [x, y]

ints = 0: merge2 [1..] [(-1),(-2)..]

What are all the ways to output a string in Ruby?

Code
Diff
  • # What are all the ways to output a string in Ruby?
    def hello_ruby
      greet = "Hello Ruby!"
    
      print           greet, "\n"
      puts            greet
      $stdout.write   greet + "\n"
      $stdout.puts    greet
      $stdout.print   greet, "\n"
      $stdout <<      greet + "\n"
      (greet+"\n").each_char {|c| print c}
    end
  • 1
    greet = "Hello Ruby!"
    
    1+
    # What are all the ways to output a string in Ruby?
    
    2+
    def hello_ruby
    
    3+
      greet = "Hello Ruby!"
    
    22
    3
    print           greet, "\n"
    
    4
    puts            greet
    
    5
    $stdout.write   greet +"\n"
    
    6
    $stdout.puts    greet
    
    7
    $stdout.print   greet, "\n"
    
    8
    (greet+"\n").each_char {|c| print c}
    
    5+
      print           greet, "\n"
    
    6+
      puts            greet
    
    7+
      $stdout.write   greet + "\n"
    
    8+
      $stdout.puts    greet
    
    9+
      $stdout.print   greet, "\n"
    
    10+
      $stdout <<      greet + "\n"
    
    11+
      (greet+"\n").each_char {|c| print c}
    
    12+
    end
    

Recent Moves:

Code
Diff
  • class DataSet {
      constructor(...data) {
        this.data = data;
      }
      get mean() {
        return this._mean = (this._mean !== undefined) ? this._mean
          : this.data.reduce((a, b) => a + b) / this.data.length
      }
      get variance() {
        return this._variance = this._variance !== undefined ? this._variance
          : this.stdDeviation ** 2;
      }
      get stdDeviation() {
        return this._stdDeviation = (this._stdDeviation !== undefined) ? this._stdDeviation
          : Math.sqrt(
            this.data.map(x => x * x).reduce((a, b) => a + b) / this.data.length
            - (this.data.reduce((a, b) => a + b) / this.data.length) ** 2);
      }
      reset() {
        delete this._mean;
        delete this._variance;
        delete this._stdDeviation;
      }
      
    }
  • 11
    class DataSet {
    
    22
      constructor(...data) {
    
    33
        this.data = data;
    
    4
        this.mean = this.data.reduce((a,b)=>a+b) / this.data.length;
    
    5
        this.variance = this.data.map(x=>x*x).reduce((a,b)=>a+b) / this.data.length - this.mean ** 2;
    
    6
        this.stdDeviation = Math.sqrt(this.variance);
    
    77
      }
    
    8
      setMean() {
    
    9
        return this.mean = this.data.reduce((a,b)=>a+b) / this.data.length;
    
    5+
      get mean() {
    
    6+
        return this._mean = (this._mean !== undefined) ? this._mean
    
    7+
          : this.data.reduce((a, b) => a + b) / this.data.length
    
    1010
      }
    
    11
      setVar() {
    
    12
        this.stdDeviation = Math.sqrt(this.data.map(x=>x*x).reduce((a,b)=>a+b) / this.data.length - (this.data.reduce((a,b)=>a+b) / this.data.length) ** 2);
    
    13
        return this.variance = this.stdDeviation ** 2;
    
    9+
      get variance() {
    
    10+
        return this._variance = this._variance !== undefined ? this._variance
    
    11+
          : this.stdDeviation ** 2;
    
    1414
      }
    
    13+
      get stdDeviation() {
    
    14+
        return this._stdDeviation = (this._stdDeviation !== undefined) ? this._stdDeviation
    
    15+
          : Math.sqrt(
    
    16+
            this.data.map(x => x * x).reduce((a, b) => a + b) / this.data.length
    
    17+
            - (this.data.reduce((a, b) => a + b) / this.data.length) ** 2);
    
    18+
      }
    
    19+
      reset() {
    
    20+
        delete this._mean;
    
    21+
        delete this._variance;
    
    22+
        delete this._stdDeviation;
    
    23+
      }
    
    24+
      
    
    1515
    }
    

Shorter version that lets Python's parsing do more of the work (with some help from re).
Handles some of the edge cases of lisp such as (+) and (- 1); see https://www.gnu.org/software/emacs/manual/html_node/elisp/Arithmetic-Operations.html.

Code
Diff
  • import re
    from functools import reduce
    
    
    def op_add(base=0, *args):
        return base + sum(args)
    
    def op_mul(base=1, *args):
        return base * reduce(lambda a, b: a * b, args, 1)
    
    def op_sub(base=0, *args):
        return - base if not args else reduce(lambda a, b: a - b, args, base)
    
    def op_div(base, divisor, *args):
        return reduce(lambda a, b: a / b, args, base / divisor)
    
    ops = {'+': op_add, '-':op_sub, '*': op_mul, '/': op_div}
    
    def arith(lisp_list):
        # if this is a list treat teh frist elemnt as a function name and 
        # recurse the expression tree by passing all the remaining args to this function
        # and then passing all the results to the function
        if not isinstance(lisp_list, tuple):
            return lisp_list
        return ops[lisp_list[0]](*[arith(x) for x in lisp_list[1:]])
        
    def run(exp):
        if not exp:
            raise ValueError('invalid lisp expression')
        try:
            # do some substitutions to make the lisp lists into valid python lists and eval the results
            #if anything goes wring then then the string wasn't properly formatted lisp math
            exp = re.sub(r'\(([+/*\-])(\s|\))', r'("\1"\2', exp)
            lisp_list = re.sub(r'\s*(\s[0-9]*([.][0-9]+)?|(\s[(])|([)]))', r',\1', exp)
            return arith(eval(lisp_list))
        except:
            raise ValueError('invalid lisp expression')
  • 1
    def run(code):
    
    2
        
    
    3
        def func(operator):
    
    4
            from functools import reduce
    
    5
            
    
    6
            add    = lambda a, b: float(a) + float(b)
    
    7
            mul    = lambda a, b: float(a) * float(b)
    
    8
            div    = lambda a, b: float(a) / float(b)
    
    9
            deduct = lambda a, b: float(a) - float(b)
    
    10
            
    
    11
            d = {
    
    12
                '+': lambda arr: reduce(add,    arr),
    
    13
                '*': lambda arr: reduce(mul,    arr),
    
    14
                '/': lambda arr: reduce(div,    arr),
    
    15
                '-': lambda arr: reduce(deduct, arr)
    
    16
            }
    
    17
            
    
    18
            return d[operator]
    
    19
        
    
    20
        def lex(token):
    
    21
            if token in ('+', '-', '/', '*', '%'):
    
    22
                return "operator"
    
    23
            elif token == '(':
    
    24
                return "lbracket"
    
    25
            elif token == ')':
    
    26
                return "rbracket"
    
    27
            elif token[0].isalpha():
    
    28
                return "name"
    
    29
            elif token[0] == token[-1] and token[0] in ('"', "'"):
    
    30
                return "string"
    
    31
            else:
    
    32
                try:
    
    33
                    float(token)
    
    34
                    return "number"
    
    35
                except:
    
    36
                    raise ValueError
    
    37
                
    
    38
        def getArgs(words):
    
    39
            args = []
    
    40
            arg = []
    
    41
            i = 0
    
    42
            for word in words[2:]:
    
    43
                if word == '(':
    
    44
                    i += 1
    
    45
                    arg.append(word)
    
    46
                elif word == ')':
    
    47
                    i -= 1
    
    48
                    arg.append(word)
    
    49
                    if i == 0:
    
    50
                        args.append(arg)
    
    51
                        arg = []
    
    52
                elif i == 0:
    
    53
                    arg.append(word)
    
    54
                    args.append(arg)
    
    55
                    arg = []
    
    56
                else:
    
    57
                    arg.append(word)
    
    58
            return args
    
    1+
    import re
    
    2+
    from functools import reduce
    
    3+
    4+
    5+
    def op_add(base=0, *args):
    
    6+
        return base + sum(args)
    
    7+
    8+
    def op_mul(base=1, *args):
    
    9+
        return base * reduce(lambda a, b: a * b, args, 1)
    
    10+
    11+
    def op_sub(base=0, *args):
    
    12+
        return - base if not args else reduce(lambda a, b: a - b, args, base)
    
    13+
    14+
    def op_div(base, divisor, *args):
    
    15+
        return reduce(lambda a, b: a / b, args, base / divisor)
    
    16+
    17+
    ops = {'+': op_add, '-':op_sub, '*': op_mul, '/': op_div}
    
    18+
    19+
    def arith(lisp_list):
    
    20+
        # if this is a list treat teh frist elemnt as a function name and 
    
    21+
        # recurse the expression tree by passing all the remaining args to this function
    
    22+
        # and then passing all the results to the function
    
    23+
        if not isinstance(lisp_list, tuple):
    
    24+
            return lisp_list
    
    25+
        return ops[lisp_list[0]](*[arith(x) for x in lisp_list[1:]])
    
    5959
        
    
    60
        def expr(words):
    
    61
            args = getArgs(words)
    
    62
            args_ = []
    
    63
            for arg in args:
    
    64
                if len(arg) == 1:
    
    65
                    args_.append(arg)
    
    66
                else:
    
    67
                    args_.append(expr(arg))
    
    68
            
    
    69
            if lex(words[1]) == "operator":
    
    70
                return func(words[1])(list(map(lambda a: (type(a) in (list, tuple) and a[0]) or a, args_)))
    
    71
    72
        lines = code.split("\n")
    
    73
        for line in lines:
    
    74
            word = ''
    
    75
            words = []
    
    76
            chars = tuple(line)
    
    77
            
    
    78
            for i in tuple(line):
    
    79
                
    
    80
                if i in ('(', ')'):
    
    81
                    if word: words.append((word, lex(word)))
    
    82
                    words.append((i, lex(i)))
    
    83
                    word = ''
    
    84
                
    
    85
                elif i == ' ':
    
    86
                    if word: words.append((word, lex(word)))
    
    87
                    word = ''
    
    88
                    
    
    89
                else:
    
    90
                    word += i
    
    91
                    
    
    92
            if word: words.append((word, lex(word)))
    
    93
        words_ = list(map(lambda arr: arr[0], words))
    
    94
        return(expr(words_))
    
    27+
    def run(exp):
    
    28+
        if not exp:
    
    29+
            raise ValueError('invalid lisp expression')
    
    30+
        try:
    
    31+
            # do some substitutions to make the lisp lists into valid python lists and eval the results
    
    32+
            #if anything goes wring then then the string wasn't properly formatted lisp math
    
    33+
            exp = re.sub(r'\(([+/*\-])(\s|\))', r'("\1"\2', exp)
    
    34+
            lisp_list = re.sub(r'\s*(\s[0-9]*([.][0-9]+)?|(\s[(])|([)]))', r',\1', exp)
    
    35+
            return arith(eval(lisp_list))
    
    36+
        except:
    
    37+
            raise ValueError('invalid lisp expression')