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.
Write a function that takes as a parameter a starting square as a string in formal chess notation and determines the valid squares that the bishop can move to in one move for an empty chess board (only bishop on the board). Must return an array of valid squares in ascending square order.
function moveBishop($startingSquare)
{
$result = [];
$letters = ["a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5, "f" => 6, "g" => 7, "h" => 8];
$startSqaureInDigits = $letters[$startingSquare[0]] . $startingSquare[1];
// bishop movement is always two ways at the same time as it moves diagonally at least one space.
// loop over 8 by 8 chessboard
//i loop is for letters
//j loop is for numbers
for($i = 1; $i <= 8; $i++){
for($j=1; $j <= 8; $j++)
{
if ($startSqaureInDigits != $i.$j && abs($startSqaureInDigits[0] - $i) == abs($startSqaureInDigits[1] - $j) )
{
$result[] = array_search($i,$letters).$j;
}
}
}
return $result;
}
Given a string of open and closed parenthesis output "Balanced" if the parenthesis are balanced or "Unbalanced" otherwise.
A string is balanced if it consists entirely of pairs of opening/closing parenthesis (in that order), none of which mis-nest.
Example input:
(())())
Example output:
Unbalanced
Example input:
(()())
Example output:
Balanced
function balanced_parenthesis(s) {
if(s == null) return null;
var i = 0,
startCnt = 0,
n = s.length;
for(i = 0; i < n; i++) {
if(s[i] === "(") {
startCnt += 1;
} else if(s[i] === ")") {
startCnt -= 1;
if(startCnt < 0) {
break;
}
}
}
if(startCnt !== 0) {
return 'Unbalanced';
} else {
return 'Balanced';
}
}
describe("Balanced Parenthesis Tests", function(){
it ("should return Balanced", function(){
Test.assertEquals(balanced_parenthesis("(()())"), "Balanced");
});
it ("should return Unbalanced", function(){
Test.assertEquals(balanced_parenthesis("(())())"), "Unbalanced");
});
it ("should return Unbalanced", function(){
Test.assertEquals(balanced_parenthesis(")()("), "Unbalanced");
});
it ("should return null for null input", function(){
Test.assertEquals(balanced_parenthesis(), null);
});
});
def foo(l):
r = copy(l)
return r
l = [1,2]
print(l)
n = foo(l)
print(n)
l.append(7)
print(n)
print(l)
def foo(l):
r = l
return r
l = [1,2]
print(l)
n = foo(l)
print(n)
l.append(7)
print(n)
print(l)
Generate prime numbers within a given minimum and maximum.
min and max values should be positive (greater than 0).
import java.util.*;
public class Primes {
public static List<Integer> generatePrimes(int min, int max) {
List<Integer> primes = new ArrayList<Integer>();
boolean isPrime = false;
if((min > max) || min < 0 || max <= 0) {
return null;
}
for(int i = min; i <= max; i++) {
long endLimit = (long)Math.floor(Math.sqrt(i));
isPrime = true;
for(long j = 2; j <= endLimit; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
primes.add(i);
}
}
return primes;
}
}
import java.util.*;
import org.junit.Test;
import static org.junit.Assert.*;
public class PrimesTest {
@Test
public void testCase1() {
List<Integer> expected = Arrays.asList(2,3,5,7);
assertEquals("Should return 2,3,5,7", expected, Primes.generatePrimes(2,10));
}
@Test
public void testCase2() {
assertNull("Should return null", Primes.generatePrimes(0, 0));
}
@Test
public void testCase3() {
assertNull("Should return null", Primes.generatePrimes(-4, 4));
}
@Test
public void testCase4() {
List<Integer> expected = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97);
assertEquals("Should return primes till 100", expected, Primes.generatePrimes(2,100));
}
}
How can u execute preloaded code in a c# kata.
I keep getting an error that the global namespace allready contains a definition for the Class in the Code block.
using System;
public static class Kata
{
public static void test()
{
Person p = new Person();
}
}
John likes numbers and digits. He takes digits of numder and sums squares of them.
Write function calc
with input natural number n
and output sum of squares of digits.
calc(1) = 1 // 1*1
calc(2) = 4 // 2*2
calc(123) = 14 // 1*1 + 2*2 + 3*3
calc(512) = 30 // 5*5 + 1*1 + 2*2
Also write function cumulate
with input natural number n
and output sum of function calc
result for numbers from 1
to n
.
cumulate(1) = 1 // calc(1) = 1
cumulate(2) = 5 // calc(1) + calc(2) = 1 + 4
cumulate(3) = 14 // calc(1) + calc(2) + calc(3) = 1 + 4 + 9
cumulate(12) = 293 // calc(1) + calc(2) + .. calc(11) + calc(12) = 1 + 4 + ... 2 + 5
Using special algorithm John found that
cumulate(12345678) = 2390700939
cumulate(123456789) = 27425527905
def calc n
n.to_s.chars
.map{|x|x.to_i**2}
.reduce(:+)
end
def cumulate n
sum_sq = ->(a,m){(a/m)*(a/m-1)*(a/m*2-1)/6*m+(a%m+1)*(a/m)**2}
sum_bi = lambda do |a,u,v|
t = (a/u)*(a/u/v)*(a+1-(a/u)*u)
ht = (a/u/v)*(a/u%v)*(2*(a/u)-1-a/u%v)/2
hha = v*sum_sq.(a/u/v*v-1,v)
hhb = (a/u/v)*(a/u/v-1)*v*(v-1)/4
(hhb+hha+ht)*u+t
end
(0..Math.log(n,10).ceil)
.reduce(0){|s,d|s+sum_sq.(n,10**d)+100*sum_sq.(n,10*10**d)-20*sum_bi.(n,10**d,10)}
end
Test.describe('Special tests') do
Test.assert_equals(calc(1), 1,"calc(1) = 1")
Test.assert_equals(calc(2), 4, "calc(2) = 4")
Test.assert_equals(calc(11), 2, "calc(11) = 2")
Test.assert_equals(calc(12), 5, "calc(12) = 5")
Test.assert_equals(calc(123), 14, "calc(123) = 14")
Test.assert_equals(calc(512), 30, "calc(512) = 30")
Test.assert_equals(cumulate(12), 293, "cumulate(12) = 293")
Test.assert_equals(cumulate(1728), 137470, "cumulate(1728) = 137470")
Test.assert_equals(cumulate(123456), 16870001, "cumulate(123456) = 16870001")
Test.assert_equals(cumulate(1234567), 203884928, "cumulate(1234567) = 203884928")
Test.assert_equals(cumulate(12345678), 2390700939, "cumulate(12345678) = 2390700939")
Test.assert_equals(cumulate(123456789), 27425527905, "cumulate(123456789) = 27425527905")
Test.assert_equals(cumulate(1234567890), 309440461350, "cumulate(1234567890) = 309440461350")
Test.assert_equals(cumulate(1234565890), 309440025966, "cumulate(1234565890) = 309440025966")
Test.assert_equals(cumulate(1231165890), 308794956217, "cumulate(1231165890) = 308794956217")
Test.assert_equals(cumulate(12345678901234567890), 6612923097811292310285, "cumulate(12345678901234567890) = 6612923097811292310285")
end
def cumulate_test n
sum_sq = ->(a,m){(a/m)*(a/m-1)*(a/m*2-1)/6*m+(a%m+1)*(a/m)**2}
sum_bi = lambda do |a,u,v|
t = (a/u)*(a/u/v)*(a+1-(a/u)*u)
ht = (a/u/v)*(a/u%v)*(2*(a/u)-1-a/u%v)/2
hha = v*sum_sq.(a/u/v*v-1,v)
hhb = (a/u/v)*(a/u/v-1)*v*(v-1)/4
(hhb+hha+ht)*u+t
end
(0..Math.log(n,10).ceil)
.reduce(0){|s,d|s+sum_sq.(n,10**d)+100*sum_sq.(n,10*10**d)-20*sum_bi.(n,10**d,10)}
end
Test.describe('Random tests') do
10.times do
amt = rand(10**15) + 1
Test.assert_equals(cumulate(amt), cumulate_test(amt), "cumulate(#{amt}) = #{cumulate_test(amt)}")
end
end
There is a FizzBuzzy Race comming up. There will be a cone dropped at every mile marker divisable by 3 and 5, start at the start line.
When divisable by 3 and 5 there will be two cones dropped.
The start line is the 0th point and needs cones also.
The command will be: 'fizzbuzzy' and take the miles as the sole parameter.
function fizzbuzzy(n) {
//insert code here
}
Test.assertEquals(fizzbuzzy(21), 13, "21 miles needs 13 cones")
Test.assertEquals(fizzbuzzy(99), 54, "99 miles needs 54 cones")
Using HashMap in Java.
/* HashMap Example */
import java.util.*;
import java.lang.*;
import java.io.*;
class HashMapDemo
{
public static void main (String[] args) throws java.lang.Exception
{
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 1);
map.put(2, 1);
map.put(3, 1);
map.put(4, 1);
map.put(5, 1);
map.put(6, 1);
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
int key = entry.getKey();
int value = entry.getValue();
System.out.println(key + " " + value);
}
}
}
It should return result of lisp-like arithmetic expressions:
run("(+ 3 (* 2 4) 1)") # 12
def run(code):
def func(operator):
from functools import reduce
add = lambda a, b: float(a) + float(b)
mul = lambda a, b: float(a) * float(b)
div = lambda a, b: float(a) / float(b)
deduct = lambda a, b: float(a) - float(b)
d = {
'+': lambda arr: reduce(add, arr),
'*': lambda arr: reduce(mul, arr),
'/': lambda arr: reduce(div, arr),
'-': lambda arr: reduce(deduct, arr)
}
return d[operator]
def lex(token):
if token in ('+', '-', '/', '*', '%'):
return "operator"
elif token == '(':
return "lbracket"
elif token == ')':
return "rbracket"
elif token[0].isalpha():
return "name"
elif token[0] == token[-1] and token[0] in ('"', "'"):
return "string"
else:
try:
float(token)
return "number"
except:
raise ValueError
def getArgs(words):
args = []
arg = []
i = 0
for word in words[2:]:
if word == '(':
i += 1
arg.append(word)
elif word == ')':
i -= 1
arg.append(word)
if i == 0:
args.append(arg)
arg = []
elif i == 0:
arg.append(word)
args.append(arg)
arg = []
else:
arg.append(word)
return args
def expr(words):
args = getArgs(words)
args_ = []
for arg in args:
if len(arg) == 1:
args_.append(arg)
else:
args_.append(expr(arg))
if lex(words[1]) == "operator":
return func(words[1])(list(map(lambda a: (type(a) in (list, tuple) and a[0]) or a, args_)))
lines = code.split("\n")
for line in lines:
word = ''
words = []
chars = tuple(line)
for i in tuple(line):
if i in ('(', ')'):
if word: words.append((word, lex(word)))
words.append((i, lex(i)))
word = ''
elif i == ' ':
if word: words.append((word, lex(word)))
word = ''
else:
word += i
if word: words.append((word, lex(word)))
words_ = list(map(lambda arr: arr[0], words))
return(expr(words_))
Test.assert_equals(run("(+ 1 2)"), 3.0)
Test.assert_equals(run("(* 3 (/ 10 2))"), 15.0)
For loops are commonly overused when other Javascript methods can lead to a cleaner and faster solution. A common example would be finding duplicates in an array.
This function called duplicates takes an array of numbers and returns a new array with the numbers duplicated in the original array ordered by value.
Your goal is to refactor this code to still find duplicates in an array and return those duplicates in a new array, but no longer use a for loop.
Note: numbers and their corresponding string representations should not be treated as duplicates (i.e., '1' !== 1).
Based on http://www.codewars.com/kata/find-duplicates/javascript
function duplicates(arr) {
var out = [];
for(var x=0;x<arr.length-1;x++)
{
var ch = arr[x];
for(var y=x+1;y<arr.length;y++)
{
var comp = arr[y];
if (comp === ch && out.indexOf(comp) === -1)
{
out.push(comp);
break;
}
}
}
out.sort();
return out;
}
Test.assertEquals(duplicates([1, 2, 4, 4, 3, 3, 1, 5, 3]).toString, [1,3,4].toString, "Sorry, your array does not have the correct contents");
Test.assertEquals(duplicates([0, 1, 2, 3, 4, 5]).toString, [].toString, "Sorry, your array does not have the correct contents");
Test.assertEquals(duplicates.toString().indexOf("for"), -1, "You can't use for loops");
Test.assertEquals(duplicates.toString().indexOf("forEach"), -1, "You can't use for loops");
Test.assertNotEquals(duplicates.toString().indexOf("reduce"), -1, "You should be using reduce in your solution");