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.
String.prototype.scan = function(regex) {
if (!regex.global) throw "regex must have 'global' flag set";
var r = []
this.replace(regex, function() {
r.push(Array.prototype.slice.call(arguments, 1, -2));
});
return r;
}
function reverseComplement(dna) {
return /[^ATCG]/.test(dna) ? "Invalid sequence" :
[...dna.replace(/./g,x=>x=="A"?"T":x=="T"?"A":x=="C"?"G":"C")].reverse().join("")
}
function getFrames(seq){
var rev = reverseComplement(seq)
var seq_length = seq.length
return {
"1" : seq, "2": seq.substring(1,seq_length-1), "3": seq.substring(2,seq_length-1),
"-1": rev, "-2": rev.substring(1,seq_length-1), "-3": rev.substring(2,seq_length-1)
}
}
function findOrfInFrame(seq,frame,min,len) {
var orfs = []
var tri_nts = seq.match(/.{1,3}/g)
var start = ""
var stop = ""
var orf_seq = ""
var is_neg = frame < 0
var neg_offset = {"1" : 1, "2" : 3, "3" : 5}
var offset = neg_offset[Math.abs(frame).toString()]
tri_nts.forEach( function(tri_nt,i){
// The very end of the sequence
if (i == tri_nts.size - 1) {
stop = ((i*3)+frame+2)
if (is_neg) {
start = (len - parseInt(start) - offset)
stop = (len - parseInt(stop) - offset)
}
if ((orf_seq.length + 3) >= min) {
orfs.push([start.toString(),">#{stop}",orf_seq])
}
}
// Start of an ORF
if (orf_seq == "" && tri_nt == "ATG") {
orf_seq += tri_nt
start = (i * 3) + frame
// Not a stop codon
} else if (codons[tri_nt] != "*" && orf_seq != ""){
orf_seq += tri_nt
// Find a stop codon
} else if (codons[tri_nt] == "*" && orf_seq != ""){
if ((orf_seq.length + 3) >= min){
stop = ((i*3)+frame+2)
if (is_neg) {
start = (len - parseInt(start) - offset)
stop = (len - parseInt(stop) - offset)
}
orfs.push([start.toString(),stop.toString(),orf_seq])
start = ""
stop = ""
orf_seq = ""
}
}
});
return orfs
}
function findOrfs(seq,min) {
var frames = getFrames(seq)
var len = seq.length
var all_orfs = {}
var count = 1
var frames_l = [1]//,2,3,-1,-2,-3]
frames_l.forEach(function(frame){
var is_neg = frame < 0 ? true : false
var seq = frames[frame.toString()]
var orfs = findOrfInFrame(seq,frame,min,len)
orfs.forEach(function(orf){
var orf_info = {
'start' : orf[0],
'stop' : orf[1],
'strand': frame > 0 ? "+" : "-",
'seq' : orf[2].match(/.{1,3}/g).map(codon=>codons[codon]).join(""),
'bp' : orf[2].length + 3,
'aa' : orf[2].length / 3,
'frame' : frame,
};
all_orfs[`ORF${count}`] = orf_info
count += 1
});
});
console.log(all_orfs)
return all_orfs
}
describe("Example Test Cases", function(){
var seq = "AAAAGAGAAGCTGCAAGTCATGGATTTGGAAAAACATCAGGGAATTCATTTAAAGTAAATAGCTGCAAAGACCACATTGGAAAGTCAATGCCAAATGTCCTAGAAGATGAAGTATATGAAACAGTTGTAGATACCTCTGAAGAAGATAGTTTTTCATTATGTTTTTCTAAATGTAGAACAAAAAATCTACAAAAAGTAAGAACTAGCAAGACTAGGAAAAAAATTTTCCATGAAGCAAACGCTGATGAATGTGAAAAATCTAAAAACCAAGTGAAAGAAAAATACTCATTTGTATCTGAAGTGGAACCAAATGATACTGATCCATTAGATTCAAATGTAGCAAATCAGAAGCCCTTTGAGAGTGGAAGTGACAAAATCTCCAAGGAAGTTGTACCGTCTTTGGCCTGTGAATGGTCTCAACTAACCCTTTCAGGTCTAAATGGAGCCCAGATGGAGAAAATACCCCTATTGCATATTTCTTCATGTGACCAAAATATTTCAGAAAAAGACCTATTAGACACAGAGAACAAAAGAAAGAAAGATTTTCTTACTTCAGAGAATTCTTTGCCACGTATTTCTAGCCTACCAAAATCAGAGAAGCCATTAAATGAGGAAACAGTGGTAAATAAGAGAGATGAAGAGCAGCATCTTGAATCTCATACAGACTGCATTCTTGCAGTAAAGCAGGCAATATCTGGAACTTCTCCAGTGGCTTCTTCATTTCAGGGTATCAAAAAGTCTATATTCAGAATAAGAGAATCACCTAAAGAGACTTTCAATGCAAGTTTTTCAGGTCATATGACTGATCCAAACTTTAAAAAAGAAACTGAAGCCTCTGAAAGTGGACTGGAAATACATACTGTTTGCTCACAGAAGGAGGACTCCTTATGTCCAAATTTAATTGATAATGGAAGCTGGCCAGCCACCACCACACAGAATTCTGTAGCTTTGAAGAATGCAGGTTTAATATCCACTTTGAAAAAGAAAACAAATAAGTTTATTTATGCTATACATGATGAAACATCTTATAAAGGAAAAAAAATACCGAAAGACCAAAAATCAGAACTAATTAACTGTTCAGCCCAGTTTGAAGCAAATGCTTTTGAAGCACCACTTACATTTGCAAATGCTGATTCAGGTTTATTGCATTCTTCTGTGAAAAGAAGCTGTTCACAGAATGATTCTGAAGAACCAACTTTGTCCTTAACTAGCTCTTTTGGGACAATTCTGAGGAAATGTTCTAGAAATGAAACATGTTCTAATAATACAGTAATCTCTCAGGATCTTGATTATAAAGAAGCAAAATGTAATAAGGAAAAACTACAGTTATTTATTACCCCAGAAGCTGATTCTCTGTCATGCCTGCAGGAAGGACAGTGTGAAAATGATCCAAAAAGCAAAAAAGTTTCAGATATAAAAGAAGAGGTCTTGGCTGCAGCATGTCACCCAGTACAACATTCAAAAGTGGAATACAGTGATACTGACTTTCAATCCCAGAAAAGTCTTTTATATGATCATGAAAATGCCAGCACTCTTATTTTAACTCCTACTTCCAAGGATGTTCTGTCAAACCTAGTCATGATTTCTAGAGGCAAAGAATCATACAAAATGTCAGACAAGCTCAAAGGTAACAATTATGAATCTGATGTTGAATTAACCAAAAATATTCCCATGGAAAAGAATCAAGATGTATGTGCTTTAAATGAAAATTATAAAAACGTTGAGCTGTTGCCACCTGAAAAATACATGAGAGTAGCATCACCTTCAAGAAAGGTACAATTCAACCAAAACACAAATCTAAGAGTAATCCAAAAAAATCAAGAAGAAACTACTTCAATTTCAAAAATAACTGTCAATCCAGACTCTGAAGAACTTTTCTCAGACAATGAGAATAATTTTGTCTTCCAAGTAGCTAATGAAAGGAATAATCTTGCTTTAGGAAATACTAAGGAACTTCATGAAACAGACTTGACTTGTGTAAACGAACCCATTTTCAAGAACTAAAAAGAGAAGCTGCAAGTCATGGATTTGGAAAAACATCAGGGAATTCATTTAAAGTAAATAGCTGCAAAGACCACATTGGAAAGTCAATGCCAAATGTCCTAGAAGATGAAGTATATGAAACAGTTGTAGATACCTCTGAAGAAGATAGTTTTTCATTATGTTTTTCTAAATGTAGAACAAAAAATCTACAAAAAGTAAGAACTAGCAAGACTAGGAAAAAAATTTTCCATGAAGCAAACGCTGATGAATGTGAAAAATCTAAAAACCAAGTGAAAGAAAAATACTCATTTGTATCTGAAGTGGAACCAAATGATACTGATCCATTAGATTCAAATGTAGCAAATCAGAAGCCCTTTGAGAGTGGAAGTGACAAAATCTCCAAGGAAGTTGTACCGTCTTTGGCCTGTGAATGGTCTCAACTAACCCTTTCAGGTCTAAATGGAGCCCAGATGGAGAAAATACCCCTATTGCATATTTCTTCATGTGACCAAAATATTTCAGAAAAAGACCTATTAGACACAGAGAACAAAAGAAAGAAAGATTTTCTTACTTCAGAGAATTCTTTGCCACGTATTTCTAGCCTACCAAAATCAGAGAAGCCATTAAATGAGGAAACAGTGGTAAATAAGAGAGATGAAGAGCAGCATCTTGAATCTCATACAGACTGCATTCTTGCAGTAAAGCAGGCAATATCTGGAACTTCTCCAGTGGCTTCTTCATTTCAGGGTATCAAAAAGTCTATATTCAGAATAAGAGAATCACCTAAAGAGACTTTCAATGCAAGTTTTTCAGGTCATATGACTGATCCAAACTTTAAAAAAGAAACTGAAGCCTCTGAAAGTGGACTGGAAATACATACTGTTTGCTCACAGAAGGAGGACTCCTTATGTCCAAATTTAATTGATAATGGAAGCTGGCCAGCCACCACCACACAGAATTCTGTAGCTTTGAAGAATGCAGGTTTAATATCCACTTTGAAAAAGAAAACAAATAAGTTTATTTATGCTATACATGATGAAACATCTTATAAAGGAAAAAAAATACCGAAAGACCAAAAATCAGAACTAATTAACTGTTCAGCCCAGTTTGAAGCAAATGCTTTTGAAGCACCACTTACATTTGCAAATGCTGATTCAGGTTTATTGCATTCTTCTGTGAAAAGAAGCTGTTCACAGAATGATTCTGAAGAACCAACTTTGTCCTTAACTAGCTCTTTTGGGACAATTCTGAGGAAATGTTCTAGAAATGAAACATGTTCTAATAATACAGTAATCTCTCAGGATCTTGATTATAAAGAAGCAAAATGTAATAAGGAAAAACTACAGTTATTTATTACCCCAGAAGCTGATTCTCTGTCATGCCTGCAGGAAGGACAGTGTGAAAATGATCCAAAAAGCAAAAAAGTTTCAGATATAAAAGAAGAGGTCTTGGCTGCAGCATGTCACCCAGTACAACATTCAAAAGTGGAATACAGTGATACTGACTTTCAATCCCAGAAAAGTCTTTTATATGATCATGAAAATGCCAGCACTCTTATTTTAACTCCTACTTCCAAGGATGTTCTGTCAAACCTAGTCATGATTTCTAGAGGCAAAGAATCATACAAAATGTCAGACAAGCTCAAAGGTAACAATTATGAATCTGATGTTGAATTAACCAAAAATATTCCCATGGAAAAGAATCAAGATGTATGTGCTTTAAATGAAAATTATAAAAACGTTGAGCTGTTGCCACCTGAAAAATACATGAGAGTAGCATCACCTTCAAGAAAGGTACAATTCAACCAAAACACAAATCTAAGAGTAATCCAAAAAAATCAAGAAGAAACTACTTCAATTTCAAAAATAACTGTCAATCCAGACTCTGAAGAACTTTTCTCAGACAATGAGAATAATTTTGTCTTCCAAGTAGCTAATGAAAGGAATAATCTTGCTTTAGGAAATACTAAGGAACTTCATGAAACAGACTTGACTTGTGTAAACGAACCCATTTTCAAGAACTA"
var res = {
"ORF1" : {
'start' : "88",
'stop' : "2004",
'strand' : "+",
'seq' : "MPNVLEDEVYETVVDTSEEDSFSLCFSKCRTKNLQKVRTSKTRKKIFHEANADECEKSKNQVKEKYSFVSEVEPNDTDPLDSNVANQKPFESGSDKISKEVVPSLACEWSQLTLSGLNGAQMEKIPLLHISSCDQNISEKDLLDTENKRKKDFLTSENSLPRISSLPKSEKPLNEETVVNKRDEEQHLESHTDCILAVKQAISGTSPVASSFQGIKKSIFRIRESPKETFNASFSGHMTDPNFKKETEASESGLEIHTVCSQKEDSLCPNLIDNGSWPATTTQNSVALKNAGLISTLKKKTNKFIYAIHDETSYKGKKIPKDQKSELINCSAQFEANAFEAPLTFANADSGLLHSSVKRSCSQNDSEEPTLSLTSSFGTILRKCSRNETCSNNTVISQDLDYKEAKCNKEKLQLFITPEADSLSCLQEGQCENDPKSKKVSDIKEEVLAAACHPVQHSKVEYSDTDFQSQKSLLYDHENASTLILTPTSKDVLSNLVMISRGKESYKMSDKLKGNNYESDVELTKNIPMEKNQDVCALNENYKNVELLPPEKYMRVASPSRKVQFNQNTNLRVIQKNQEETTSISKITVNPDSEELFSDNENNFVFQVANERNNLALGNTKELHETDLTCVNEPIFKN",
'bp' : 1917,
'aa' : 638,
'frame' : 1,
},
"ORF2" : {
'start' : "2443",
'stop' : "2520",
'strand' : "+",
'seq' : "MEPRWRKYPYCIFLHVTKIFQKKTY",
'bp' : 78,
'aa' : 25,
'frame' : 1
},
"ORF3" : {
'start' : "440",
'stop' : "517",
'strand' : "+",
'seq' : "MEPRWRKYPYCIFLHVTKIFQKKTY",
'bp' : 78,
'aa' : 25,
'frame' : 2},
"ORF4" : {
'start' : "2414",
'stop' : "2491",
'strand' : "+",
'seq' : "MVSTNPFRSKWSPDGENTPIAYFFM",
'bp' : 78,
'aa' : 25,
'frame' : 2
},
"ORF5" : {
'start' : "411",
'stop' : "488",
'strand' : "+",
'seq' : "MVSTNPFRSKWSPDGENTPIAYFFM",
'bp' : 78,
'aa' : 25,
'frame' : 3
},
"ORF6" : {
'start' : "2091",
'stop' : ">4004",
'strand' : "+",
'seq' : "MPNVLEDEVYETVVDTSEEDSFSLCFSKCRTKNLQKVRTSKTRKKIFHEANADECEKSKNQVKEKYSFVSEVEPNDTDPLDSNVANQKPFESGSDKISKEVVPSLACEWSQLTLSGLNGAQMEKIPLLHISSCDQNISEKDLLDTENKRKKDFLTSENSLPRISSLPKSEKPLNEETVVNKRDEEQHLESHTDCILAVKQAISGTSPVASSFQGIKKSIFRIRESPKETFNASFSGHMTDPNFKKETEASESGLEIHTVCSQKEDSLCPNLIDNGSWPATTTQNSVALKNAGLISTLKKKTNKFIYAIHDETSYKGKKIPKDQKSELINCSAQFEANAFEAPLTFANADSGLLHSSVKRSCSQNDSEEPTLSLTSSFGTILRKCSRNETCSNNTVISQDLDYKEAKCNKEKLQLFITPEADSLSCLQEGQCENDPKSKKVSDIKEEVLAAACHPVQHSKVEYSDTDFQSQKSLLYDHENASTLILTPTSKDVLSNLVMISRGKESYKMSDKLKGNNYESDVELTKNIPMEKNQDVCALNENYKNVELLPPEKYMRVASPSRKVQFNQNTNLRVIQKNQEETTSISKITVNPDSEELFSDNENNFVFQVANERNNLALGNTKELHETDLTCVNEPIFK",
'bp' : 1914,
'aa' : 637,
'frame' : 3
},
"ORF7" : {
'start' : "1759",
'stop' : "1622",
'strand' : "-",
'seq' : "MLLSCIFQVATAQRFYNFHLKHIHLDSFPWEYFWLIQHQIHNCYL",
'bp' : 138,
'aa' : 45,
'frame' : -1,
},
"ORF8" : {
'start' : "1441",
'stop' : "1334",
'strand' : "-",
'seq' : "MLQPRPLLLYLKLFCFLDHFHTVLPAGMTENQLLG",
'bp' : 108,
'aa' : 35,
'frame' : -1
},
"ORF9" : {
'start' : "721",
'stop' : "578",
'strand' : "-",
'seq' : "MKKPLEKFQILPALLQECSLYEIQDAALHLSYLPLFPHLMASLILVG",
'bp' : 144,
'aa' : 47,
'frame' : -1
},
"ORF10" : {
'start' : "484",
'stop' : "260",
'strand' : "-",
'seq' : "MKKYAIGVFSPSGLHLDLKGLVETIHRPKTVQLPWRFCHFHSQRASDLLHLNLMDQYHLVPLQIQMSIFLSLGF",
'bp' : 225,
'aa' : 74,
'frame' : -1},
"ORF11" : {
'start' : "157",
'stop' : "50",
'strand' : "-",
'seq' : "MKNYLLQRYLQLFHILHLLGHLALTFQCGLCSYLL",
'bp' : 108,
'aa' : 35,
'frame' : -1
},
"ORF12" : {
'start' : "3762",
'stop' : "3625",
'strand' : "-",
'seq' : "MLLSCIFQVATAQRFYNFHLKHIHLDSFPWEYFWLIQHQIHNCYL",
'bp' : 138,
'aa' : 45,
'frame' : -2
},
"ORF13" : {
'start' : "3444",
'stop' : "3337",
'strand' : "-",
'seq' : "MLQPRPLLLYLKLFCFLDHFHTVLPAGMTENQLLG",
'bp' : 108,
'aa' : 35,
'frame' : -2
},
"ORF14" : {
'start' : "2724",
'stop' : "2581",
'strand' : "-",
'seq' : "MKKPLEKFQILPALLQECSLYEIQDAALHLSYLPLFPHLMASLILVG",
'bp' : 144,
'aa' : 47,
'frame' : -2
},
"ORF15" : {
'start' : "2487",
'stop' : "2263",
'strand' : "-",
'seq' : "MKKYAIGVFSPSGLHLDLKGLVETIHRPKTVQLPWRFCHFHSQRASDLLHLNLMDQYHLVPLQIQMSIFLSLGF",
'bp' : 225,
'aa' : 74,
'frame' : -2
},
"ORF16" : {
'start' : "2160",
'stop' : "2053",
'strand' : "-",
'seq' : "MKNYLLQRYLQLFHILHLLGHLALTFQCGLCSYLL",
'bp' : 108,
'aa' : 35,
'frame' : -2
},
"ORF17" : {
'start' : "2052",
'stop' : "1936",
'strand' : "-",
'seq' : "MNSLMFFQIHDLQLLFLVLENGFVYTSQVCFMKFLSIS",
'bp' : 117,
'aa' : 38,
'frame' : -2
}
}
it("Testing for Basic Functionality", function(){
Test.assertSimilar(findOrfs(seq,75), res);
});
});
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
function countCirculars(n) {
let count = 0;
for (let i=3;i<=n; i+=2) {
if (isPrime(i) && isCirclePrime(i))
count++;
}
return count+1;
}
function isPrime(n) {
for (let i=2; i<=Math.sqrt(n); i++) {
if (n%i === 0)
return false;
}
return true;
}
function isCirclePrime(n) {
let strN = n.toString();
for (let i = 1; i<strN.length; i++) {
strN = shiftString(strN);
if (!isPrime(parseInt(strN)))
return false
}
return true;
}
function shiftString(str) {
return str.substring(1) + str.substring(0,1);
}
// TODO: Replace examples and use TDD development by writing your own tests
// These are some CW specific test methods available:
// Test.expect(boolean, [optional] message)
// Test.assertEquals(actual, expected, [optional] message)
// Test.assertSimilar(actual, expected, [optional] message)
// Test.assertNotEquals(actual, expected, [optional] message)
describe("Solution", function(){
it("should be 55", function(){
Test.assertEquals(countCirculars(1000000), 55, "");
});
});
Return the names of everyone to greet with "Hello".
SELECT name FROM greetings
WHERE greeting='Hello';
results = run_sql
describe :items do
it "should return 7 items" do
expect(results.count).to eq 7
end
end
That's my first kumite... don't really know what all this is about...
using System;
using System.Linq;
public class Kata
{
public static int DuplicateCount(string str)
{
var orderedLowercase = str.ToLower().OrderBy(c => c);
var countDuplicates = 0;
var countOccurrenciesCurrentCharacter = 1;
char? previousElement = null;
var firstElement = true;
foreach(var currentElement in orderedLowercase)
{
if (firstElement)
{
firstElement = false;
}
else
{
if (currentElement == previousElement.Value)
{
countOccurrenciesCurrentCharacter ++;
if (countOccurrenciesCurrentCharacter == 2)
{
countDuplicates ++;
}
}
else
{
countOccurrenciesCurrentCharacter = 1;
}
}
previousElement = currentElement;
}
return countDuplicates;
}
}
namespace Solution {
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
[TestFixture]
public class KataTest
{
[Test]
public void KataTests()
{
Assert.AreEqual(0, Kata.DuplicateCount(""));
Assert.AreEqual(0, Kata.DuplicateCount("abcde"));
Assert.AreEqual(2, Kata.DuplicateCount("aabbcde"));
Assert.AreEqual(0, Kata.DuplicateCount("a"));
Assert.AreEqual(1, Kata.DuplicateCount("aa"));
Assert.AreEqual(2, Kata.DuplicateCount("aabBcde"), "should ignore case");
Assert.AreEqual(1, Kata.DuplicateCount("Indivisibility"));
Assert.AreEqual(2, Kata.DuplicateCount("Indivisibilities"), "characters may not be adjacent");
}
}
}
const convert = (num) => {
return parseFloat(num.toFixed(2));
};
describe('it works', () => {
assert.strictEqual(convert(1.0899999), 1.09);
assert.strictEqual(convert(2.348), 2.35);
assert.strictEqual(convert(0.111), .11);
});
There can only be one bulbul!
def sayHello(say):
l = ["bulbul", "8===D"]
return l
# TODO: Replace examples and use TDD development by writing your own tests
# These are some of the methods available:
# test.expect(boolean, [optional] message)
# test.assert_equals(actual, expected, [optional] message)
# test.assert_not_equals(actual, expected, [optional] message)
# You can use Test.describe and Test.it to write BDD style test groupings
say = 3
Test.assert_equals(sayHello(say), ["bulbul", "8===D"])
Could be done better?
package main
import "fmt"
func swap(dataset []int, a, b int) {
var x int = dataset[a]
dataset[a] = dataset[b]
dataset[b] = x
}
func bubble_sort(dataset []int, amout_of_integers int){
for i := 0; i <= amout_of_integers; i++ {
for j := amout_of_integers; j >= i + 1; j-- {
if dataset[j] < dataset[j-1] {
swap(dataset, j, j - 1)
}
}
}
}
func main(){
dataset := []int{5, 2, 4, 6, 1, 3};
fmt.Println(dataset)
bubble_sort(dataset, 5);
fmt.Println(dataset)
}
Provide a positive integer (0 < n
).
Returns an array of all factors of n
.
If there are no factors, returns an empty array.
Based on user boo1ean's solution here: https://www.codewars.com/kata/reviews/55aa0d71c1eba8a65a000132/groups/5787db6eba5c4b1c8c0016ae
function getFactors (n) {
if (n < 1 || ! Number.isInteger(n)) return [];
let divisors = [];
// Only iterates up to n/2, since no divisor will be greater than that
for (let i = 1; i <= n / 2; ++i) {
if (n % i) continue;
else divisors.push(i);
}
// Push the original number n to array
return divisors.concat([n]);
}
describe("Solution", function(){
it("sBasic tests", function(){
Test.assertSimilar(getFactors(0), [], "Should return empty array");
Test.assertSimilar(getFactors('string'), [], "Is not a number so should return an empty array");
Test.assertSimilar(getFactors(1), [1], "'1' should be the only divisor of '1'");
Test.assertSimilar(getFactors(13), [1, 13], "'13' is a prime number, so '1, 13' should be its divisors");
Test.assertSimilar(getFactors(50), [1, 2, 5, 10, 25, 50]);
});
});
A little help for claculate the distances between two points in a plane(2D case) and in the space (3D case)
from math import sqrt
def distance2D(pA, pB):
if pA == pB: return 0
xA, yA = tuple(pA); xB, yB = tuple(pB)
return sqrt((xA - xB)**2 + (yA - yB)**2)
def distance3D(pA, pB):
if pA == pB: return 0
xA, yA, zA = tuple(pA); xB, yB, zB = tuple(pB)
return sqrt((xA - xB)**2 + (yA - yB)**2 + (zA - zB) **2)
def distance2D_check(pA, pB):
if pA == pB: return 0
xA, yA = tuple(pA); xB, yB = tuple(pB)
return sqrt((xA - xB)**2 + (yA - yB)**2)
def distance3D_check(pA, pB):
if pA == pB: return 0
xA, yA, zA = tuple(pA); xB, yB, zB = tuple(pB)
return sqrt((xA - xB)**2 + (yA - yB)**2 + (zA - zB) **2)
def assertFuzzyEquals(actual, expected, msg=""):
merr = 1e-10
inrange = abs(actual - expected) <= merr
if (inrange == False):
msg = "At 1e-10: Expected value must be {:.10f} but got {:.10f}"
msg = msg.format(expected, actual)
return Test.expect(inrange, msg)
test.describe("Basic Tests for 2D")
pA = [1, 1]; pB = [2, 2]
assertFuzzyEquals(distance2D(pA, pB), 1.41421356237)
pA = [0, 0]; pB = [5, 6]
assertFuzzyEquals(distance2D(pA, pB), 7.81024967591)
pA = [-5, 4]; pB = [-10, 6]
assertFuzzyEquals(distance2D(pA, pB), 5.38516480713)
pA = [-5.1, 4.0]; pB = [10.2, -6.3]
assertFuzzyEquals(distance2D(pA, pB), 18.4439692041)
test.describe("Basic Tests for 3D")
pA = [1, 1, 1]; pB = [2, 2, 2]
assertFuzzyEquals(distance3D(pA, pB), 1.73205080757)
pA = [0, 0, 0]; pB = [7, 8, 9]
assertFuzzyEquals(distance3D(pA, pB), 13.9283882772)
pA = [-5, 4, 7]; pB = [-10, 6, -18]
assertFuzzyEquals(distance3D(pA, pB), 25.5734237051)
pA = [-5.1, 4.0, 1]; pB = [10.2, -6.3, -1]
assertFuzzyEquals(distance3D(pA, pB), 18.5520888312)
test.describe("Random Tests for 2D")
test.describe("Integer coordinates")
import random
from random import randint
for h in range(20):
pA = [randint(-100, 100), randint(-100, 100)]
pB = [randint(-100, 100), randint(-100, 100)]
result = distance2D_check(pA, pB)
res = distance2D(pA, pB)
assertFuzzyEquals(res, result)
test.it("Distance from " + str(pA) + " to " + str(pB) + " : " + str(result))
test.describe("Random Tests for 2D")
test.describe("Decimal coordinates")
for h in range(20):
pA = [randint(-100, 100) + random.random(), randint(-100, 100) + random.random() ]
pB = [randint(-100, 100) + random.random() , randint(-100, 100) + random.random()]
result = distance2D_check(pA, pB)
res = distance2D(pA, pB)
assertFuzzyEquals(res, result)
test.it("Distance from " + str(pA) + " to " + str(pB) + " : " + str(result))
test.describe("Random Tests for 3D")
test.describe("Integer coordinates")
for h in range(20):
pA = [randint(-100, 100), randint(-100, 100), randint(-100, 100)]
pB = [randint(-100, 100), randint(-100, 100), randint(-100, 100)]
result = distance3D_check(pA, pB)
res = distance3D(pA, pB)
assertFuzzyEquals(res, result)
test.it("Distance from " + str(pA) + " to " + str(pB) + " : " + str(result))
test.describe("Random Tests for 3D")
test.describe("Decimal coordinates")
for h in range(10):
pA = [randint(-100, 100) + random.random(), randint(-100, 100) + random.random(), randint(-100, 100) + random.random() ]
pB = [randint(-100, 100) + random.random() , randint(-100, 100) + random.random(), randint(-100, 100) + random.random()]
result = distance3D_check(pA, pB)
res = distance3D(pA, pB)
assertFuzzyEquals(res, result)
test.it("Distance from " + str(pA) + " to " + str(pB) + " : " + str(result))
A little help for claculate the distances between two points in a plane(2D cases) and in the space (3D cases)
def distance2D(pA, pB)
return 0 if pA == pB
xA = pA[0]; yA = pA[1]; xB= pB[0]; yB = pB[1]
return Math.sqrt((xA - xB)**2 + (yA - yB)**2)
end
def distance3D(pA, pB)
return 0 if pA == pB
xA = pA[0]; yA = pA[1]; zA = pA[2]; xB= pB[0]; yB = pB[1]; zB = pB[2]
return Math.sqrt((xA - xB)**2 + (yA - yB)**2 + (zA - zB) **2)
end
def range (min, max)
rand * (max-min) + min
end
def distance2D_check(pA, pB)
return 0 if pA == pB
xA = pA[0]; yA = pA[1]; xB= pB[0]; yB = pB[1]
return Math.sqrt((xA - xB)**2 + (yA - yB)**2)
end
def distance3D_check(pA, pB)
return 0 if pA == pB
xA = pA[0]; yA = pA[1]; zA = pA[2]; xB= pB[0]; yB = pB[1]; zB = pB[2]
return Math.sqrt((xA - xB)**2 + (yA - yB)**2 + (zA - zB) **2)
end
def assertFuzzyEquals(actual, expected)
merr = 1e-10
inrange = (actual - expected).abs <= merr
if (inrange == false) then
msg = "At 1e-10: Expected value must be %.10f but was %.10f" % [expected, actual]
end
return Test.expect(inrange, msg)
end
describe "Basic Tests for 2D Cases" do
it "Low Values of x, y" do
pA = [1, 1]; pB = [2, 2]
assertFuzzyEquals(distance2D(pA, pB), 1.41421356237)
pA = [0, 0]; pB = [5, 6]
assertFuzzyEquals(distance2D(pA, pB), 7.81024967591)
pA = [-5, 4]; pB = [-10, 6]
assertFuzzyEquals(distance2D(pA, pB), 5.38516480713)
pA = [-5.1, 4.0]; pB = [10.2, -6.3]
assertFuzzyEquals(distance2D(pA, pB), 18.4439692041)
end
end
describe "Basic Tests for 3D Cases" do
it "Low Values of x, y, z" do
pA = [1, 1, 1]; pB = [2, 2, 2]
assertFuzzyEquals(distance3D(pA, pB), 1.73205080757)
pA = [0, 0, 0]; pB = [7, 8, 9]
assertFuzzyEquals(distance3D(pA, pB), 13.9283882772)
pA = [-5, 4, 7]; pB = [-10, 6, -18]
assertFuzzyEquals(distance3D(pA, pB), 25.5734237051)
pA = [-5.1, 4.0, 1]; pB = [10.2, -6.3, -1]
assertFuzzyEquals(distance3D(pA, pB), 18.5520888312)
end
end
describe "Random Tests for 2D Cases" do
it "Integer Values for x, y" do
for h in 1..20
pA = [rand(-100..100), rand(-100..100)]
pB = [rand(-100..100), rand(-100..100)]
result = distance2D_check(pA, pB)
res = distance2D(pA, pB)
it "Testing for: pA: " + pA.to_s + ", pB: " + pB.to_s + " , distance = " + result.to_s do
assertFuzzyEquals(res, result)
end
end
end
end
describe "Random Tests for 2D Cases" do
it "Decimal Values for x, y" do
for h in 1..20
pA = [rand(-100..100) + range(0, 1) , rand(-100..100) + range(0, 1)]
pB = [rand(-100..100) + range(0, 1), rand(-100..100) + range(0, 1)]
result = distance2D_check(pA, pB)
res = distance2D(pA, pB)
it "Testing for: pA: " + pA.to_s + ", pB: " + pB.to_s + " , distance = " + result.to_s do
assertFuzzyEquals(res, result)
end
end
end
end
describe "Random Tests for 3D Cases" do
it "Integer Values for x, y, z" do
for h in 1..20
pA = [rand(-100..100), rand(-100..100), rand(-100..100)]
pB = [rand(-100..100), rand(-100..100), rand(-100..100)]
result = distance3D_check(pA, pB)
res = distance3D(pA, pB)
it "Testing for: pA: " + pA.to_s + ", pB: " + pB.to_s + " , distance = " + result.to_s do
assertFuzzyEquals(res, result)
end
end
end
end
describe "Random Tests for 3D Cases" do
it "Decimal Values for x, y" do
for h in 1..20
pA = [rand(-100..100) + range(0, 1) , rand(-100..100) + range(0, 1), rand(-100..100) + range(0, 1)]
pB = [rand(-100..100) + range(0, 1), rand(-100..100) + range(0, 1), rand(-100..100) + range(0, 1)]
result = distance3D_check(pA, pB)
res = distance3D(pA, pB)
it "Testing for: pA: " + pA.to_s + ", pB: " + pB.to_s + " , distance = " + result.to_s do
assertFuzzyEquals(res, result)
end
end
end
end