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
Algorithms
Logic
Arrays
Data Types
Mathematics
Numbers

I had to use this for the kyu 3 binomial expansion kata since I have no clue how to use the BigInts library for Java. Instead of calculating the total value of each factorial, this finds the factors of the numerator and denominator, simplifies, and divides the results. Nothing special and there are better solutions, but I'm proud of it.

Note: The n-choose-k formula

        n!
  ------------
   k!(n - k)!
public class ArrayFactorial{
  public static int factorial(int n, int k) {
          int n_k = n - k;
          int[] numerator = new int[n];
          int[] denominator = new int[k + n_k];
          for(int i = 1; i <= n; i++)
              numerator[i - 1] = i;
          for(int i = 1; i <= k; i++)
              denominator[i - 1] = i;
          for(int i = 1; i <= n_k; i++)
              denominator[k + i - 1] = i;
          for(int i = 0; i < numerator.length; i++){
              for(int j = 0; j < denominator.length; j++){
                  if(numerator[i] == denominator[j]) {
                      numerator[i] = 1;
                      denominator[j] = 1;
                  }
              }
          }
          int n_sum = 1;
          int d_sum = 1;
          for(int v : numerator)
              n_sum *= v;
          for(int v : denominator)
              d_sum *= v;
          return n_sum / d_sum;
      }
  }

Hello! I have a lot of difficulties to write a good description of this kata. I published it some time ago but I met a lot of critics with that description and received good evaluations of the task. I tried to rewrite it several times but it would not get better. If you like thaе kata and you are interested in helping me it would be great!

image for description

What we have:

  • Input: a table pool (two-dimensional array);

  • "X" is a part of the table or cell;

  • One white cue ball is represented by number >=1. This number means the force of shot: one point of the force is equal to one movement of a ball, so the ball with number 3 can move 3 cells (to move to the next cell you should subtract one point from its force). After collision with a coloured ball it gives the rest points of force to a coloured ball and disappears (the white ball only determines the direction).

  • One coloured ball is represented by "O".

  • Pockets are represented by "U". They can be in any place on the borders of the table;

  • The output is: a boolean (whether the coloured ball rolled into a pocket) and a pair of integers (the final coordinates of the coloured ball).

Rules

The balls can move only to their adjacent cells in the horizontal, vertical ou diagonal direction. The line

You should shot the white ball in the direction of the coloured ball using that way that results in the imaginable straight line between them:

Possible collisions:

1) ["O", "X", "X"]  2) ["X", "X", "X"]  3) ["X", "4", "X"]  
   ["X", "X", "X"]     ["O", "X", "4"]     ["X", "X", "X"]  
   ["X", "X", "4"]     ["X", "X", "X"]     ["X", "O", "X"]  

No collisions:

1) ["X", "4", "X"]  2) ["X", "X", "X", "X"]
   ["X", "X", "X"]     ["X", "X", "X", "O"]
   ["O", "X", "X"]     ["4", "X", "X", "X"]

If the white ball can't reach the coloured ball by that way, a collision won't happen.

In the case of collision, the coloured ball "O" starts to move(in the same direction that the white ball moved) until it stops because its force is over or until it enters a pocket. If it hits the "table wall", the ball changes its angle of movement according to physics.

For example, in this case, after collision the ball "O" goes to the opposite direction:

["X", "O", "X"]  ["X", "O", "X"]  ["X", "X", "X"]  ["X", "X", "X"]  ["X", "X", "X"]
["X", "4", "X"]=>["X", "X", "X"]=>["X", "O", "X"]=>["X", "X", "X"]=>["X", "O", "X"]
["X", "X", "X"]  ["X", "X", "X"]  ["X", "X", "X"]  ["X", "O", "X"]  ["X", "X", "X"]

And in the next case, it "reflects":

 ["X", "O", "X"]  ["X", "O", "X"]  ["X", "X", "X"]  ["X", "X", "X"]  ["X", "X", "X"]
 ["4", "X", "X"]=>["X", "X", "X"]=>["X", "X", "O"]=>["X", "X", "X"]=>["O", "X", "X"]
 ["X", "X", "X"]  ["X", "X", "X"]  ["X", "X", "X"]  ["X", "O", "X"]  ["X", "X", "X"]  

Return true or false if the coloured ball did enter a pocket or not and the coordinates of coloured ball.

Notes

The size of a table can be different but always rectangular.

There are only two balls.

Examples

let table = [["U", "X", "O", "X"], // the collision is possible
             ["X", "X", "X", "X"],
             ["9", "X", "U", "X"]]

 table = [["U", "X", "O", "X"], 
          ["X", "8", "X", "X"], // <-- one movement spends one point of force
          ["X", "X", "U", "X"]]

 table = [["U", "X", "O", "X"], // <-- 7 points of force (the white ball was removed)
          ["X", "X", "X", "X"],
          ["X", "X", "U", "X"]]

 table = [["U", "X", "X", "X"], 
          ["X", "X", "X", "O"],// <--6 points
          ["X", "X", "U", "X"]]
          
 table = [["U", "X", "X", "X"], 
          ["X", "X", "X", "X"],
          ["X", "X", "U", "X"]] // <--the coloured ball entered a pocket

 return [true, [2, 2] ]  
let table = [["U", "X", "X"], // the collision is possible,
             ["1", "O", "U"], // but there is not enough force to reach a pocket
             ["X", "X", "X"]]
return [false, [1, 1] ]
let table =  [["U", "X", "X", "X"], // the collision is not possible
             ["X", "X", "X", "O"],
             ["9", "X", "U", "X"]]
return [false, [1, 3] ]

!The last critic of a Moderator:

  1. would be more readable to have the input as an array of strings, rather than an array of arays of strings, no? (and you could use whitespaces instead of X for "empty" places)

  2. the description really needs a rewrite... ;) General advises:
    a) don't give the examples before the specifications
    b) especially, don't mix explanations and examples
    c) give the general idea of the task right at the beginning before going into details. Like, that's the very first thing that should be in the description, before the picture.

  3. I believe you didn't specify that no pockets will ever be under the starting positions of the balls

  4. the notes are parts of the specs

  5. did you say that the force/speed may be greater than 9 (and is never negative)?

*3 - I'm going t fix it

function poolgame(table) {
         let force;
         let coordBall1 = {};
         let coordBall2 = {};

         for (let i = 0; i < table.length; i++) {
            for (let k = 0; k < table[i].length; k++) {
               if (Object.keys(coordBall1).length && Object.keys(coordBall2).length) break;
               if (!isNaN(table[i][k])) {
                  coordBall1.X = k;
                  coordBall1.Y = i;
                  force = table[i][k];
               } else if (table[i][k] == "O") {
                  coordBall2.X = k;
                  coordBall2.Y = i;
               }
            }
         }

         let dir = { X: 0, Y: 0 };
         let y = Math.abs(coordBall1.Y - coordBall2.Y);
         let x = Math.abs(coordBall1.X - coordBall2.X);

         if (coordBall1.Y === coordBall2.Y) {
            force -= x;
         } else if (coordBall1.X === coordBall2.X) {
            force -= y;
         } else {
            if (y !== x) return [false, [coordBall2.Y, coordBall2.X]]; //check if there is no collision
            force -= x;
         }
         if (force <= 0) return [false, [coordBall2.Y, coordBall2.X]]; //check if there is no collision 

         dir.X = (coordBall1.X > coordBall2.X) ? -1 : (coordBall1.X === coordBall2.X) ? 0 : 1;
         dir.Y = (coordBall1.Y > coordBall2.Y) ? -1 : (coordBall1.Y === coordBall2.Y) ? 0 : 1;

         let tableLimit = {
            X: table[0].length - 1,
            Y: table.length - 1
         }

         while (force--) {
            let possibleX = coordBall2.X + dir.X;
            let possibleY = coordBall2.Y + dir.Y;
            if (possibleX > tableLimit.X || possibleX < 0) dir.X = -dir.X;
            if (possibleY > tableLimit.Y || possibleY < 0) dir.Y = -dir.Y;
            coordBall2.X += dir.X;
            coordBall2.Y += dir.Y;
            if (table[coordBall2.Y][coordBall2.X] === "U") return [true, [coordBall2.Y, coordBall2.X]];
         }
         return [false, [coordBall2.Y, coordBall2.X]];
      }

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