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.
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;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD by writing your own tests
public class SolutionTest {
@Test
public void BasicTests() {
assertEquals(3, ArrayFactorial.factorial(3, 1));
assertEquals(10, ArrayFactorial.factorial(5, 2));
assertEquals(15, ArrayFactorial.factorial(6, 4));
}
@Test
public void LargerTests() {
assertEquals(1365, ArrayFactorial.factorial(15, 4));
assertEquals(19448, ArrayFactorial.factorial(17, 7));
}
}
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!
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:
-
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)
-
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. -
I believe you didn't specify that no pockets will ever be under the starting positions of the balls
-
the notes are parts of the specs
-
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]];
}
const chai = require("chai");
const assert = chai.assert;
chai.config.truncateThreshold = 0;
describe("Sample tests", function() {
it(`[
["X", "X", "U"],
["O", "X", "5"],
["U", "X", "X"]
]`, function() {
assert.deepEqual(poolgame(
[
["X", "X", "U"],
["O", "X", "5"],
["U", "X", "X"]
]), [ false, [ 1, 1 ] ]);
});
it(`[
["U", "X", "3"],
["X", "X", "X"],
["O", "X", "U"]
]`, function() {
assert.deepEqual(poolgame(
[
["U", "X", "3"],
["X", "X", "X"],
["O", "X", "U"]
]), [ false, [ 1, 1 ] ]);
});
it(`[
["U", "X", "O","X"],
["X", "X", "X","X"],
["8", "X", "X","X"]
]`, function() {
assert.deepEqual(poolgame(
[
["U", "X", "O","X"],
["X", "X", "X","X"],
["8", "X", "X","X"]
]), [ true, [ 0, 0 ] ]);
});
it(`[
["U", "X", "X","X"],
["X", "X", "X","O"],
["8", "X", "X","X"],
["X", "U", "U","X"]
]`, function() {
assert.deepEqual(poolgame(
[
["U", "X", "X","X"],
["X", "X", "X","O"],
["8", "X", "X","X"],
["X", "U", "U","X"]
]), [ false, [ 1, 3 ] ]);
});
it(`[
["U", "X", "X","O"],
["X", "X", "X","X"],
["X", "X", "X","X"],
["8", "U", "U","X"]
]`, function() {
assert.deepEqual(poolgame(
[
["U", "X", "X","O"],
["X", "X", "X","X"],
["X", "X", "X","X"],
["8", "U", "U","X"]
]), [ false, [ 1, 2 ] ]);
});
it(`[
["U", "X", "X","X"],
["X", "X", "O","X"],
["9", "X", "X","X"],
["X", "U", "U","X"]
]`, function() {
assert.deepEqual(poolgame(
[
["U", "X", "X","X"],
["X", "X", "O","X"],
["9", "X", "X","X"],
["X", "U", "U","X"]
]), [ false, [ 1, 2 ] ]);
});
it(`[
["U", "X", "X","O"],
["X", "X", "X","X"],
["X", "9", "X","X"],
["U", "X", "U","X"]
]`, function () {
assert.deepEqual(poolgame(
[
["U", "X", "X", "O"],
["X", "X", "X", "X"],
["X", "9", "X", "X"],
["U", "X", "U", "X"]
]), [true, [3, 0]]);
});
it(`[
["U", "X", "X","X"],
["X", "X", "X","X"],
["2", "X", "X","O"],
["X", "X", "U","X"],
["X", "U", "U","X"]
]`, function() {
assert.deepEqual(poolgame(
[
["U", "X", "X","X"],
["X", "X", "X","X"],
["2", "X", "X","O"],
["X", "X", "U","X"],
["X", "U", "U","X"]
]),[ false, [ 2, 3 ] ]);
});
it(`[
["U", "X", "X","X"],
["X", "X", "X","X"],
["1", "O", "X","X"]
]`, function() {
assert.deepEqual(poolgame(
[
["U", "X", "X","X"],
["X", "X", "X","X"],
["1", "O", "X","X"]
]), [ false, [ 2, 1 ] ]);
});
});
describe("New Edge test", function() {
it(`[
["X", "X", "U", "X", "X", "X", "U", "X", "X", "X"],
["X", "X", "X", "X", "X", "X", "X", "X", "X", "X"],
["X", "X", "X", "X", "X", "X", "X", "X", "X", "X"],
["X", "X", "X", "X", "X", "X", "X", "X", "X", "X"],
["X", "X", "X", "X", "O", "X", "X", "X", "X", "X"],
["X", "X", "X", "X", "X", "X", "X", "X", "X", "U"],
["X", "X", "X", "X", "X", "X", "X", "X", "X", "U"],
["X", "50", "X", "X", "X", "X", "X", "X", "X", "X"],
["U", "X", "X", "X", "X", "X", "X", "X", "X", "X"],
["U", "X", "U", "X", "U", "X", "X", "X", "X", "X"]
]`, function() {
assert.deepEqual(poolgame(
[
["X", "X", "U", "X", "X", "X", "U", "X", "X", "X"],
["X", "X", "X", "X", "X", "X", "X", "X", "X", "X"],
["X", "X", "X", "X", "X", "X", "X", "X", "X", "X"],
["X", "X", "X", "X", "X", "X", "X", "X", "X", "X"],
["X", "X", "X", "X", "O", "X", "X", "X", "X", "X"],
["X", "X", "X", "X", "X", "X", "X", "X", "X", "U"],
["X", "X", "X", "X", "X", "X", "X", "X", "X", "U"],
["X", "50", "X", "X", "X", "X", "X", "X", "X", "X"],
["U", "X", "X", "X", "X", "X", "X", "X", "X", "X"],
["U", "X", "U", "X", "U", "X", "X", "X", "X", "X"]
]), [ true, [ 8, 0 ] ]);
});
});
describe("Random tests", function() {
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
function createTable(a, b) {
let arr = [];
while (arr.length < a) {
let sub = [];
while (sub.length < b) {
sub.push("X");
}
arr.push(sub);
}
return arr;
}
function createTest() {
let outerSize = getRandomInt(3, 11);
let innerSize = getRandomInt(3, 11);
let arr = createTable(outerSize, innerSize)
let coordBall1 = {
Y: getRandomInt(0, outerSize),
X: getRandomInt(0, innerSize)
}
let coordBall2 = {};
let typeOfPos = Math.random();
if (typeOfPos < 0.3) {
coordBall2.X = coordBall1.X;
coordBall2.Y = getRandomInt(0, outerSize)
if (coordBall2.Y === coordBall1.Y) {
coordBall2.Y += (coordBall2.Y > 0) ? -1 : 1;
}
} else if (typeOfPos < 0.6) {
coordBall2.X = getRandomInt(0, innerSize)
coordBall2.Y = coordBall1.Y;
if (coordBall2.X === coordBall1.X) {
coordBall2.X += (coordBall2.X > 0) ? -1 : 1;
}
} else if (typeOfPos < 0.9) { //simple diagonal tests
if (Math.random() < 0.5) {
coordBall2.X = (coordBall1.X > 0) ? coordBall1.X - 1 : coordBall1.X + 1;
} else {
coordBall2.X = (coordBall1.X < innerSize - 1) ? coordBall1.X + 1 : coordBall1.X - 1;
}
if (Math.random() < 0.5) {
coordBall2.Y = (coordBall1.Y > 0) ? coordBall1.Y - 1 : coordBall1.Y + 1;
} else {
coordBall2.Y = (coordBall1.Y < outerSize - 1) ? coordBall1.Y + 1 : coordBall1.Y - 1;
}
} else {
coordBall2.Y = getRandomInt(0, outerSize)
if (coordBall2.Y === coordBall1.Y) {
coordBall2.Y += (coordBall2.Y > 0) ? -1 : 1;
}
coordBall2.X = getRandomInt(0, innerSize)
if (coordBall2.X === coordBall1.X) {
coordBall2.X += (coordBall2.X > 0) ? -1 : 1;
}
}
let pockets = [];
function createPockets(pos) {
let pocket;
if (pos === "top") {
pocket = [0, getRandomInt(0, innerSize)];
} else if (pos === "bottom") {
pocket = [outerSize - 1, getRandomInt(0, innerSize)];
} else if (pos === "left") {
pocket = [getRandomInt(0, outerSize), 0];
} else if (pos === "right") {
pocket = [getRandomInt(0, outerSize), innerSize - 1];
}
pockets.push(pocket)
}
let totalS = outerSize + innerSize;
if (totalS === 6) {
createPockets("top");
createPockets("bottom");
} else if (totalS < 10) {
createPockets("top");
createPockets("bottom");
createPockets("left");
createPockets("right");
} else if (totalS < 14) {
createPockets("top");
createPockets("bottom");
createPockets("left");
createPockets("right");
createPockets("left");
createPockets("right");
} else {
createPockets("top");
createPockets("bottom");
createPockets("top");
createPockets("bottom");
createPockets("left");
createPockets("right");
createPockets("left");
createPockets("right");
}
for (let i = 0; i < pockets.length; i++) {
let pocket = pockets[i];
arr[pocket[0]][pocket[1]] = "U";
}
arr[coordBall1.Y][coordBall1.X] = (getRandomInt(1, 50)).toString();
arr[coordBall2.Y][coordBall2.X] = "O";
return arr;
}
function mySol(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]];
}
function verify() {
for (let i = 0; i < 90; i++) {
let arr = createTest();
let solution = mySol(arr)
it(`arr`, function() {
assert.deepEqual(poolgame(arr), solution);
});
}
}
verify()
});
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('');
}
// Since Node 10, we're using Mocha.
// You can use `chai` for assertions.
const chai = require("chai");
const assert = chai.assert;
// Uncomment the following line to disable truncating failure messages for deep equals, do:
// chai.config.truncateThreshold = 0;
// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
// Uncomment the following to use the old assertions:
// const Test = require("@codewars/test-compat");
describe("isPalindrom", function() {
it("zwraca false kiedy word jest pustym ciągiem znaków", function() {
assert.strictEqual(isPalindrom(''), false);
});
it("zwraca false kiedy word zawiera spację", function() {
assert.strictEqual(isPalindrom('work krow'), false);
});
it("zwraca true kiedy word jest palindromem", function() {
assert.strictEqual(isPalindrom('kajak'), true);
});
it("zwraca true kiedy word jest palindromem z literami o różnej wielkości", function() {
assert.strictEqual(isPalindrom('Kajak'), true);
});
});
(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
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
cat = match('c.t')
test.assert_equals(cat('cat'), True)
test.assert_equals(cat('cbt'), True)
test.assert_equals(cat('catastrophic'), False)
test.assert_equals(match('c.t')('abc'), False)
test.assert_equals(match('[.]')('[a]'), True)
test.assert_equals(match('[a]')('a'), False)
(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
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
# Part 1
cat = match('c.t')
test.assert_equals(cat('cat'), True)
test.assert_equals(cat('cbt'), True)
test.assert_equals(cat('catastrophic'), False)
test.assert_equals(match('c.t')('abc'), False)
test.assert_equals(match('[.]')('[a]'), True)
test.assert_equals(match('[a]')('a'), False)
# Part 2 (could do with more tests)
test.assert_equals(match('.*')('cat'), True)
test.assert_equals(match('.*')(''), True)
test.assert_equals(match('a*')(''), True)
test.assert_equals(match('a*')('a'), True)
test.assert_equals(match('a*')('aa'), True)
test.assert_equals(match('ab?c')('ac'), True)
test.assert_equals(match('ab?c')('abc'), True)
test.assert_equals(match('a+')(''), False)
test.assert_equals(match('a+')('a'), True)
test.assert_equals(match('a+')('aa'), True)
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), !.
:- begin_tests(example).
:- include(example).
test(example_test) :-
A = ["live", "arp", "strong"],
B = ["lively", "alive", "harp", "sharp", "armstrong"],
findall(R, in_array(A, B, R), Actual), % setof?
assertion(Actual == ["arp", "live", "strong"]).
:- end_tests(example).
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);
}
Describe(add_function) {
It(should_add_vectors_of_doubles) {
auto xs = v4d{1, 2, 3, 4}, ys = v4d{10, 20, 30, 40};
auto e = xs + ys, a = add(xs, ys);
Assert::That(a[0], Equals(e[0]));
}
};
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);
}
#include <criterion/criterion.h>
typedef double v4d __attribute__((__vector_size__(32)));
v4d add(v4d xs, v4d ys);
Test(add_function, should_add_vectors_of_doubles) {
v4d xs = (v4d){1, 2, 3, 4}, ys = (v4d){10, 20, 30, 40};
v4d e = xs + ys, a = add(xs, ys);
cr_assert_eq(a[0], e[0]);
}
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
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(length_longest_palindrome(''),0)
test.assert_equals(length_longest_palindrome('a'),1)
test.assert_equals(length_longest_palindrome('aaabbaa'),6)
test.assert_equals(length_longest_palindrome('Hannah'),4)
test.assert_equals(length_longest_palindrome('geeks'),2)
test.assert_equals(length_longest_palindrome('forgeeksskeegfor'),10)
test.assert_equals(length_longest_palindrome('aab'),2)
test.assert_equals(length_longest_palindrome('Abbas'),2)
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
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(minNumberOfCoinsForChange(7,[1,5,10]),3)
test.assert_equals(minNumberOfCoinsForChange(7,[1,10,5]),3)
test.assert_equals(minNumberOfCoinsForChange(7,[5,1,10]),3)
test.assert_equals(minNumberOfCoinsForChange(0,[1,2,3]),0)
test.assert_equals(minNumberOfCoinsForChange(3,[2,1]),2)
test.assert_equals(minNumberOfCoinsForChange(4,[1,5,10]),4)
test.assert_equals(minNumberOfCoinsForChange(10,[1,5,10]),1)
test.assert_equals(minNumberOfCoinsForChange(24,[1,5,10]),6)
test.assert_equals(minNumberOfCoinsForChange(9,[3,5]),3)
test.assert_equals(minNumberOfCoinsForChange(10,[1,3,4]),3)
test.it("good testcases")
test.assert_equals(minNumberOfCoinsForChange(135,[39, 45, 130, 40, 4, 1, 60, 75]),2)
test.assert_equals(minNumberOfCoinsForChange(135, [39, 45, 130, 40, 4, 1]),3)