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.

### tenooki's Kumite #3

You are developing a microservice that processes loan requests and performs a variety of calculations. In this particular scenario, you will receive a batch of loan requests which must be processed to obtain the monthly interest rate, monthly payment amount and the risk factor. These 3 values must be stored in a read efficient in-memory structure in order to serve as a cache for other systems to query.

The formula to calculate the monthly payment amount is as follows:

(LOAN_AMOUNT * MONTHLY_RATE) / (1 - (1 + MONTHLY_RATE ^ ((-1) * TERM_MONTHS))

The risk factor is a value from 0 to 1, where 0 means no risk and 1 is the highest possible risk. The bank follows these guidelines to estimate a borrower's credit quality (higher percentages mean better credit capabilities):

• No delinquent debt (+35%)
• Debt to Income ratio (Monthly Debt / Monthly Income) < 43% (+30%)
• Credit history (Good +25%)
• Type of credit used (Mortgage +10%)

Input:

JSON Array of loan submissions

``````[
{
loanId: 1,
amount: 100000,
termYears: 10,
termMonths: 0,
anualInterest: 6,
type: "mortgage",
borrower: {
name: "Jhon Smith",
anualIncome: "150000",
delinquentDebt: false,
amountOwed: 0
}
},
{
loanId: 2,
amount: 200000,
termYears: 15,
termMonths: 0,
anualInterest: 6.5,
type: "student",
borrower: {
name: "James Gosling",
anualIncome: "150000",
delinquentDebt: false,
amountOwed: 0
}
}
]
``````

Output:

In-memory collections of instances of LoanAnalysis POJO containing:

• loanId,
• monthlyInterestRate
• monthlyPayment,
• riskFactor
``````public class Loan {
private int amount;
private int termYears;
private int termMonths;
private double anualInterest;

public Loan(int amount, int termYears, int termMonths, double anualInterest){
this.amount = amount;
this.termYears = termYears;
this.termMonths = termMonths;
this.anualInterest = anualInterest;
}

public double getMonthlyPayment(){
return this.amount*this.getMonthlyRate()/
(1-Math.pow(1+this.getMonthlyRate(), -this.getTermInMonths()));
}

public double getMonthlyRate(){
return this.anualInterest/100/12;
}

public int getTermInMonths(){
return this.termYears*12+this.termMonths;
}

public double riskFactor(int anualIncome){
return 0;
}
}``````

### Suma de números

Dados dos enteros a y b, que pueden ser positivos o negativos, encuentre la suma de todos los números entre incluirlos también y devolverlos.
Si los dos números son iguales, devuelva a o b.

Nota: a y b no están ordenados!

ObtenerSuma(1, 0) == 1 // 1 + 0 = 1
ObtenerSuma(1, 2) == 3 // 1 + 2 = 3
ObtenerSuma(0, 1) == 1 // 0 + 1 = 1
ObtenerSuma(1, 1) == 1 // 1 Since both are same
ObtenerSuma(-1, 0) == -1 // -1 + 0 = -1
ObtenerSuma(-1, 2) == 2 // -1 + 0 + 1 + 2 = 2

``````public class Suma
{
public int ObtenerSuma(int a, int b)
{
return (a + b) * (Math.abs(a - b) + 1) / 2;
}
}``````

### Next Fibonacci Number.

Getting an integer `n`, return the next digit after the nth digit of the fibonacci sequence.

For example:

n == 3, return 2.

n == 2, return 1.

n == 12, return 144.

Fib sequence. 0,1,1,2,3,5,8,13,21,34,55,89,144. . .

``````public class nthFib{

public static int fib(int n){
return n == 1 ? 1 : n == 0 ? 0 : (fib(n - 1) + fib(n - 2));
}
}``````

### Shorter Code - If Statement

Make this if statement shorter!

``````def larger_than_5(a):
return True if a > 5 else False``````

### Invert Pitch Set

Fundamentals

Write a function that takes a list of 12 UNIQUE numbers, ranging from 0 to 11. Find the interval difference of each step, and reverse the interval in the new set.

If the number is less than 0, it should wrap around. For example, if -1, then 11. If -2, then 10.

Also if the number is greater than 11, the number should be subtracted by 12.

The first number in the new set should be the same as the original set.

For example:

[7, 6, 4, 3, 1, 11, 10, 0, 9, 8, 2, 5] should return [7, 8, 10, 11, 1, 3, 4, 2, 5, 6, 0, 9]

(I'm having a hard time putting the description into words that make this seem completely independent to music. Knowing and understand music theory would make this a lot easier to understand)

``````def invert(testset):

base12 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

invset = [(testset[0])]
for s in range(len(testset)-1):
interval = testset[s] - testset[s+1]
if s == 0:
inv_val = testset[s] + interval
if inv_val > 11:
inv_val = inv_val - 12
else:
inv_val += interval
if inv_val > 11:
inv_val = inv_val - 12
if inv_val < 0:
inv_abs = base12[inv_val]
else:
inv_abs = inv_val
invset.append(inv_abs)
return(invset)``````

### Find Array indices from center to border

The idea is given an array size, find all indices in the correct order.

The order start at the center, then move up from the center for 1, then move down from the center for 1, and it continues.

If the size is odd : we take the actual center
(size is 5, the indice of the center will be 2)
| | | | | | -> center is | | |X| | | -> indice of X is 2

If the size is even : we take the indice below the center
(size if 6, the indice of the center is 2)
| | | | | | | -> center is | | |X| | | |-> indice before the center (X) is 2

For the first 10 numbers, solution is
#Number 0 - []
#Number 1 - 0
#Number 2 - 0, 1
#Number 3 - 1, 2, 0
#Number 4 - 1, 2, 0, 3
#Number 5 - 2, 3, 1, 4, 0
#Number 6 - 2, 3, 1, 4, 0, 5
#Number 7 - 3, 4, 2, 5, 1, 6, 0
#Number 8 - 3, 4, 2, 5, 1, 6, 0, 7
#Number 9 - 4, 5, 3, 6, 2, 7, 1, 8, 0
#Number 10 - 4, 5, 3, 6, 2, 7, 1, 8, 0, 9

``````def generateOrder(n):
if n == 0:
return []

r = []

if n % 2 == 0 :
r = generateOrder(n-1)
r.append(n-1)
else:
middle = round((n / 2) - 0.01)
r = [middle]
for i in range(middle):
r.append(middle + i + 1)
r.append(middle - i - 1)

return r``````

### NSObjectProtocol+configure

Allows for things like:

``````import UIKit

let label = UILabel().configure {
\$0.text = "Hello World"
\$0.numberOfLines = 4
\$0.font = UIFont.systemFont(ofSize: 16)
}
``````
``````import Foundation

public extension NSObjectProtocol {
func configure(_ closure: (Self) -> Void) -> Self {
closure(self)

return self
}
}``````

### Python Parser Combinator

Algorithms
Logic
Parsing
Strings
Higher-order Functions
Functions
Control Flow
Basic Language Features
Fundamentals

Seeing how there aren't any parsing libraries available in any language i use besides Haskell, i wrote up this small parser combinator library in Python based on the ReadS type from Haskell. The idea is simliar to PyParsing but the combinators proviceded are based off Parsec.

The parser type `P<a>` is a light wrapper around a function of type `String, Int -> [(String, Int, a)]`, which, given an input string and the current index, returns a generator of all possible matching tuples of (input string, next index, matched item).

The combinator that matches a character can be written as:

``````def char(chr):
def inner(str, idx):
if idx >= len(str): return
if str[idx] != chr: return
yield (str, idx + 1, chr)
return P(inner)
``````

Using `char`, the combinator that matches a sequence of characters could be written by combining multiple parsers:

``````def sequence(x, y, z):
return P.char(x).then(P.char(y)).then(P.char(z)).replace(x + y + z)
# or alternatively...
def sequence(x, y, z):
return P.char(x) >> P.char(y) >> P.char(z) ** (x + y + z)
# or even...
def sequence(*xs):
return P.seq(*map(P.char, xs)) ** xs
# sequence('a', 'b', 'c') should match 'abc'
``````
``````from functools import *
from itertools import *
import re

M = staticmethod

class P:
# f :: String, Int -> [(String, Int, a)]
__init__ = lambda self, f=None: setattr(self, 'f', f)
# pass forward a parser, similar to PyParsing's Forward()
forward = lambda self, f: [self, setattr(self, 'f', f)][0]

# same as stuff in Haskell

# pure = return
pure = M(lambda a: P(lambda s, i: iter([(s, i, a)])))
# bind = (>>=)
bind = lambda self, f: P(lambda s, i: (x for xs in
map(lambda x: f(x[2]).f(x[0], x[1]), self.f(s, i)) for x in xs))
# fmap = (<\$>)
fmap = lambda self, f: P(lambda s, i: ((x, y, f(z)) for x, y, z in self.f(s, i)))
# replace = (\$>)
replace = lambda self, v: P(lambda s, i: ((x, y, v) for x, y, _ in self.f(s, i)))
# apply = (<*>)
apply = lambda self, f: self.bind(lambda x: f.bind(lambda y: P.pure(y(x))))
# then = (>>)
then = lambda self, p: self.bind(lambda _: p)
# before = (<<)
before = lambda self, p: self.bind(lambda x: p.replace(x))
# alter = (<|>)
# N.B. the choices are left biased
#      place the more likely matches on the left as an optimization
alter = lambda self, p: P(lambda s, i: chain(self.f(s, i), p.f(s, i)))
# many = zeroOrMore
many = lambda self: self.some().alter(P.pure(iter([])))
# some = oneOrMore
some = lambda self: P.fix(lambda p: self.bind(lambda x:
p.alter(P.pure(iter([]))).fmap(lambda ys: chain([x], ys))))
# seq = sequence
# N.B. this returns a generator, so do parser.fmap(list) to be able to index it
seq = M(lambda *xs: reduce(lambda p, x: x.bind(lambda a: p.fmap(
lambda b: chain([a], b))), list(xs)[::-1], P.pure(iter([]))))

creep = lambda self, n: P(lambda s, i: ((x, y + n, z) for x, y, z in self.f(s, i)))
# skip n or more whitespace chars
lex = lambda self, n=0: self.before([P.many, P.some][n](P.char(str.isspace)))
# possibly successful parse based on a predicate
# f :: String, Int -> Either () (Int, a)
pred = M(lambda f:P(lambda s,i:iter([[(s,i+b[0],b[1])]if b else[]for b in[f(s,i)]][0])))
# same as pred but must not be at eof
pred1 = M(lambda f: P.pred(lambda s, i: f(s, i) if i<len(s) else []))
# parse a single char
# f :: Either Char (Char -> Bool)
char = M(lambda f: P.pred1(lambda s,i: [1,s[i]]*(f if callable(f)else lambda c:f==c)(s[i])))
# parser that always fails
fail = M(lambda: P(lambda x, y: iter([])))
# parse a string
string = M(lambda s: P.seq(*map(lambda c: P.char(lambda x: x == c), s)).replace(s))
# choose from a list of alternatives
choice = M(lambda *xs: reduce(lambda p, x: p.alter(x), xs, P.fail()))
# parse a regex
# N.B. this only gives either 0 or 1 result, so no backtracking if you use (x|y)
regex = M(lambda pattern, group=None, flags=0: P.pred(lambda s, i:
[[m.end() - i, m.group(group) if group is not None else m] if m is not None else []
for m in [re.search(r'(?<=^.{{{}}}){}'.format(i, pattern), s, flags)]][0]))
# parse end of input
eof = M(lambda: P.pred(lambda s, i: [0,None]*(i>=len(s))))
# helper function to avoid having to use .forward()
# f :: Parser a -> Any
fix = M(lambda f: [p.forward(q.f) for p in [P(None)] for q in [f(p)]][0])

# run the parser
# set just=True to yield only the match result
# N.B. this returns a generator of all possible matches,
#   with the first usually being the longest match.
#   use parser.then(P.eof()) if you want the full match
parse = lambda self, s, i=0, just=False: (x[2] if just else x for x in self.f(s, i))

__pow__,__pos__,__invert__,__or__,__rshift__,__lshift__=replace,some,many,alter,then,before

# usually i'd copy paste this condensed version if i use this library in a kata
Failed Tests

### `fail` option

``is_zero(N) :- N =:= 1.``

### Easy Cipher Breaking

This is a simple challenge. Given an encrypted sentence, decrypt that sentence.

Only alphabetical characters are included, except for spaces. Spaces are not altered.

``````def cipher_breaker(string: str):
final_list = []
for each in string:
if each != " ":
each = chr(123 - (ord(each) - 96))
final_list.append(each)
return "".join(final_list)``````