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

Sprawdza czy wyraz jest palindromem.
Palindrom to wyraz który czytany od przodu i od tyłu daje to samo słowo.

function isPalindrom(word) {
  if (!word || word.indexOf(' ') > -1) {
    return false;
  }
  return word.toLowerCase() === word.toLowerCase().split('').reverse().join('');
}

(This is a draft for a potential Kata series, left as a Kumite for now)

Regex engine from scratch

Throughout this series you'll be gradually piecing together a regex engine, with each successive Kata adding an additional piece of syntax into the mix.

You may wish to copy code you've developed in earlier parts of the series for later parts so that you can gradually build up the engine as you go, or you can cater each solution to the specific syntax proposed. The latter might be better for the first few steps as they're very simple.

It all begins with a dot.

For the first step we're going to implement regex's . syntax.

To keep things simple, every other symbol except for a period should be treated as if it was inside a character set, even if the symbol would be treated as syntax by a real regex engine.

For example, the input [.], even though it looks like a character class, should be handled as if it was \[.\] because we're only implementing the dot metacharacter for now. This also means you can't cheat and just import re!

Your function will be provided a pattern as a string. This pattern should be handled somehow to produce a function that can then be used to match on a string. You should expect this prepared function to be called multiple times with different inputs, it can't match just once.

The produced match function should behave as if it had anchors on either end, so it should match the entire string.

Examples

match('c.t')("cat") => True
match('c.t')("cbt") => True
match('c.t')("catastrophic") => False (must match entire string)
match('c.t')("abc") => False (not a match)
match('[.]')('[a]') => True (we don't support character classes, treat them like letters)
match('[a]')('a') => False (we've not implemented character classes yet)
def match(pattern):
    def matcher(string):
        return len(pattern) == len(string) and all(a == b if a != '.' else True for a, b in zip(pattern, string))
    return matcher

(This is a draft for a potential Kata series, left as a Kumite for now)

Regex engine from scratch

Throughout this series you'll be gradually piecing together a regex engine, with each successive Kata adding an additional piece of syntax into the mix.

You may wish to copy code you've developed in earlier parts of the series for later parts so that you can gradually build up the engine as you go, or you can cater each solution to the specific syntax proposed. The latter might be better for the first few steps as they're very simple.

More or less the same

Following on from the previous part, we'll now be adding support for the simple quantifiers: *, +, ?. Support for braced quantifiers such as {3} will not be added, so braces should be treated like letters.

In part 1 you implemented the dot syntax, so you must implement that in this part too.

All other syntax should be treated as letters (and just matched on), even if they would be valid regex syntax in a real regex parser.

For example, even though [a] would typically be a character class containing the letter a, we haven't implemented character classes yet, so it should be treated as \[a\]. This also means you can't just import re, it won't work!

Your function will be provided with a pattern as a string. This pattern should be handled somehow to produce a function that can be used to match on a string. You should expect this prepared function to be called multiple times with different inputs, it can't match just once.

The produced match function should behave as if it had anchors on either end, so it should match the entire string.

Examples

match('.*')('cat') => True # .* should match anything
match('c.?t')('ct') => True # the dot is made optional by the ?
match('c.?t')('cat') => True
match('c[a]t')('cat') => False # We haven't implemented character classes
match('c[a]t')('c[a]t') => True
match('c{2}t')('cct') => False # We also won't be implementing braced quantifiers
match('c{2}t')('c{2}t') => True
# This is a k=1 solution and I'm not too happy with it.
# I was hoping to try and find an okay balance for something
# that could be written and understood in a Kata solution without being a full
# blown automata, but it's kind of unwieldy.

class PeekableIterator(object):
    def __init__(self, iterator):
        self.iterator = iterator
        self.ahead = None
        
    def peek(self):
        if self.ahead:
            return self.ahead
        
        self.ahead = self.read()
        return self.ahead
    
    def read(self):
        if (result := self.ahead):
            self.ahead = None
            return result
        
        try:
            return next(self.iterator)
        except StopIteration:
            return ''
            

def match(pattern):
    ops = []
    for part in pattern:
        if part == '?':
            op = ops.pop()
            ops.append(('optional', op))
        elif part == '*':
            op = ops.pop()
            ops.append(('many_or_none', op))
        elif part == '+':
            op = ops.pop()
            ops.append(('many', op))
        else:
            ops.append(('match', part))
    
    def do_op(stream, op, component):
        if op == 'match':
            return (component == '.' and stream.peek()) or stream.peek() == component
        elif op == 'optional':
            op, component = component
            if do_op(stream, op, component) and op == 'match':
                stream.read()
            return True
        elif op == 'many_or_none' or op == 'many':
            original_op = op
            op, component = component
            i = 0
            while do_op(stream, op, component):
                if op == 'match':
                    stream.read()
                i += 1
            return original_op == 'many_or_none' or i > 0
        raise "Huh?"
    
    def matcher(string):
        stream = PeekableIterator(iter(string))
        
        for op, component in ops:
            if not do_op(stream, op, component):
                return False
            
            if op == 'match':
                stream.read()
        return stream.read() == ''
    return matcher

Trying something different...

The task is to check for strings in A that exist (as substrings) in B, sorted.

%  check for Xs in As that exist in B, in sorted order
in_array(A, B, X) :-
  msort(A, Sorted),
  member(X, Sorted),
  in_b(X, B).
  
in_b(A, B) :-
  member(X, B),
  sub_string(X, _, _, _, A), !.
UnnamedFailed Tests

AVX

main.cpp:10:10: error: always_inline function '_mm256_add_pd' requires target feature 'avx', but would be inlined into function 'add' that is compiled without support for 'avx'
return _mm256_add_pd(xs, ys);

#include <immintrin.h>

using v4d = double __attribute__((__vector_size__(32)));

v4d add(v4d xs, v4d ys) {
  return _mm256_add_pd(xs, ys);
}
UnnamedFailed Tests

AVX

solution.c:6:10: error: always_inline function '_mm256_add_pd' requires target feature 'avx', but would be inlined into function 'add' that is compiled without support for 'avx'
return _mm256_add_pd(xs, ys);

#include <immintrin.h>

typedef double v4d __attribute__((__vector_size__(32)));

v4d add(v4d xs, v4d ys) {
  return _mm256_add_pd(xs, ys);
}

Given a string S of length N, the task is to find the length of the longest palindromic substring from a given string.

Examples:

Input: S = “abcbab”
Output: 5
Explanation:
string “abcba” is the longest substring that is a palindrome which is of length 5.

Input: S = “abcdaa”
Output: 2
Explanation:
string “aa” is the longest substring that is a palindrome which is of length 2.

Note: If the string is empty or None or null then just return 0.do not try to convert the string to lowercase

def length_longest_palindrome(string):
    n = len(string) 
    if n == 0:
        return 0 
    
    maxlen = 1
    table = [[False for i in range(n)]for j in range(n)] 
    for i in range(n):
        table[i][i] = True
        
    start = 0 
    for i in range(n-1):
        if string[i] == string[i+1]:
            table[i][i+1] = True 
            start = i 
            maxlen = 2 
            
    for k in range(3,n+1):
        for i in range(n-k+1):
            j = i + k - 1 
            if table[i+1][j-1] and string[i] == string[j]:
                table[i][j] = True
                
                if k > maxlen:
                    start = i 
                    maxlen = k 
    return maxlen

Given an array of positive integers representing coin denominations and a single non-negative integer n.
representing a target amount of money, write a function that returns the smallest number of coins needed to
make change for (to sum up to) that target amount using the given coin denominations.

Example:

sample Input
n = 7
denoms = [1,5,10]

output = 3//2x1+1x5

time = O(nd),space = O(n).
where n is target amount and d is number of coin denominations

Note: you have access to an unlimited amount of coins.In other words,if denominations are [1,5,10],you have access to unlimited amount of 1s,5s and 10s

If it's impossible to make change for target amount return -1

def minNumberOfCoinsForChange(n, denoms):
	numOfCoins = [float('inf') for amount in range(n+1)]  
	numOfCoins[0] = 0 
	for denom in denoms:
		for amount in range(len(numOfCoins)):
			if denom <= amount:
				numOfCoins[amount] = min(numOfCoins[amount],1+numOfCoins[amount - denom])
	return numOfCoins[n] if numOfCoins[n] != float('inf') else -1

given that you have:

stringObject = `{
  \"a\":\"false\",
  \"b\":\"33\",
  \"c\":\"hi i'm C!\",
  \"d\":\"{
    \\\"d1\\\":\\\"4.5\\\",
    \\\"d2\\\":\\\"Yo D2 here\\\"
  }\"
}`

make it deeply primitive as such:

resultObject = {
  a: false,
  b: 33,
  c: "hi i'm C!",
  d:{
    d1:4.5,
    d2:"Yo D2 here"
  }
}
function toPrimitiveDeep(stringObject){
  let result
  try{
    result = JSON.parse(stringObject);
  }catch (e){
    return stringObject
  }
  if(typeof result !== 'object') return result
  let keys = Object.keys(result)
  keys.forEach((key)=>{
    result[key] = toPrimitiveDeep(result[key])
  })
  return result
}
denis