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.
import codewars_test as test import random # Random test cases @test.describe("Random tests") def random_tests(): @test.it("Random tests") def random_test_cases(): for _ in range(100): a = random.randint(-1000, 1000) b = random.randint(-1000, 1000) expected = a - b test.assert_equals(subtracti(a, b), expected)
- import codewars_test as test
- import random
- # Random test cases
- @test.describe("Random tests")
- def random_tests():
- @test.it("Random tests")
- def random_test_cases():
- for _ in range(100):
- a = random.randint(-1000, 1000)
- b = random.randint(-1000, 1000)
- expected = a - b
test.assert_equals(subtractio(a, b), expected)- test.assert_equals(subtracti(a, b), expected)
Write a function that multiplies two random inputs.
def twin_sum_solutions(array) array.each_with_object([]) do |element, memo| next if memo.include? element * 2 memo << element * 2 if array.count(element) > 1 end end
- def twin_sum_solutions(array)
duplicates = []find_duplicates(array).map{|e| e*2 }enddef find_duplicates(array)duplicates = []array.each do |element|duplicates << element if array.count(element) > 1- array.each_with_object([]) do |element, memo|
- next if memo.include? element * 2
- memo << element * 2 if array.count(element) > 1
- end
duplicates.uniqend- end
I'm not sure why but this version (building a slice as we go) is faster on average
Still about 3x slower than str.split though
def split(string, separator): split_list = [] current_slice = '' for char in string: if char == separator: split_list.append(current_slice) current_slice = '' else: current_slice += char split_list.append(current_slice) return split_list
# ojeriejire rust version in python- def split(string, separator):
- split_list = []
i = 0- current_slice = ''
- for char in string:
- if char == separator:
- split_list.append(current_slice)
- current_slice = ''
- else:
- current_slice += char
for j, c in enumerate(string):if c == separator:slice_ = string[i:j]split_list.append(slice_)i = j + 1split_list.append(string[i:])return split_list- split_list.append(current_slice)
- return split_list
import codewars_test as test @test.describe("Tests") def test(): @test.it("Works") def functional(): test.assert_equals(split("Hello World", ' '), ["Hello", "World"]) test.assert_equals(split("John-brings-his-cat", '-'), ["John", "brings", "his", "cat"]) test.assert_equals(split(",joe,mama,", ','), ["", "joe", "mama", ""]) @test.it("Is fast enough") def fast(): test.assert_equals(split("*".join("" for i in range(2000000)), "*"), [""]*2000000) test.assert_equals(split(":".join("character sequence" for i in range(1500000)), ":"), ["character sequence"]*1500000) test.assert_equals(split(":".join("performance test number three" for i in range(3000000)), ":"), ["performance test number three"]*3000000) print("All test cases passed.")
#[test]- import codewars_test as test
- @test.describe("Tests")
- def test():
assert split("Hello World", ' ') == ["Hello", "World"]assert split("John-brings-his-cat", '-') == ["John", "brings", "his", "cat"]assert split(",joe,mama,", ',') == ["", "joe", "mama", ""]- @test.it("Works")
- def functional():
- test.assert_equals(split("Hello World", ' '), ["Hello", "World"])
- test.assert_equals(split("John-brings-his-cat", '-'), ["John", "brings", "his", "cat"])
- test.assert_equals(split(",joe,mama,", ','), ["", "joe", "mama", ""])
- @test.it("Is fast enough")
- def fast():
- test.assert_equals(split("*".join("" for i in range(2000000)), "*"), [""]*2000000)
- test.assert_equals(split(":".join("character sequence" for i in range(1500000)), ":"), ["character sequence"]*1500000)
- test.assert_equals(split(":".join("performance test number three" for i in range(3000000)), ":"), ["performance test number three"]*3000000)
- print("All test cases passed.")
# Running the test function to check if the function workstest()
Prefer to remove the 'using std::' stuff
generateRandomNumber: Should not initialize rd and mtt etc... for each generation call => make it static. Same with the base string
hasDuplicateDigits: using bitset instead of std::vector<bool> ... avoid like to allocate on a simple test. And use accumulate ?
isNumeric: prefer to use '::isdigit' in std::all_of (defined in <cctype>). Uses locale, but who cares ??
checkGuess: std::pair is defined in <utility>; and prefer to directly initialize the return structure with a binding if one likes...
acceptGuess :
made a default max counter of attempts
reworked the main loop (do{ ..... } while ()); note an invalid attempt is an attempt so one should increment the #attempts anyway
.. and last : use fmt/format (or std::format in C++20), with predefined messages out of the code lines, for further translation
#include <fmt/format.h> #include <iostream> #include <cstdlib> #include <ctime> #include <vector> #include <bitset> #include <algorithm> #include <cmath> #include <cctype> #include <random> static const std::string msgs[]={ "Enter your guess (a 4-digit number with non-repeating digits): ", "Correct numbers: {} Correct position: {}", "Congratulations! You guessed the number {} correctly in {} attempts!", "Oups.. You could not guess the number in {} attempts!", "Invalid input. Please enter a 4-digit number with non-repeating digits." }; // Initialize random number generator outside functions static std::random_device rd; // Obtain a random number from hardware static std::mt19937 g(rd()); // Seed the generator std::string generateRandomNumber() { static std::string base{"0123456789"}; // Shuffle digits std::shuffle(base.begin(), base.end(), g); // Return the first 4 digits as a string return base.substr(0,4); } bool hasDuplicateDigits(const std::string &number) { return std::accumulate(number.cbegin(),number.cend(), std::bitset<10>{0}, [](auto &bs,auto c) {return bs.set(c-'0');} ).count()!=number.size(); } bool isNumeric(const std::string &s) { return std::all_of(s.begin(), s.end(), ::isdigit); } std::string getUserGuess(std::istream &in = std::cin, std::ostream &out = std::cout) { std::string guess; out << msgs[0]; in >> guess; return guess; } std::pair<int, int> checkGuess(const std::string &randomNumber, const std::string &userGuess) { std::pair<int, int> ret {0,0}; for (int i = 0; i < 4; ++i) { if (randomNumber[i] == userGuess[i]) { ++std::get<0>(ret), ++std::get<1>(ret); } else if (std::count(randomNumber.begin(), randomNumber.end(), userGuess[i])) { ++std::get<0>(ret); } } return ret; } int acceptGuess(const std::string &expected, std::istream &in = std::cin, std::ostream &out = std::cout, int maxattempts=20) { int attempts = 0; std::pair status{0,0}; do { std::string userGuess = getUserGuess(in, out); if (userGuess.length() != 4 || hasDuplicateDigits(userGuess) || !isNumeric(userGuess)) { out << msgs[4] << std::endl; } else { status = checkGuess(expected, userGuess); out << fmt::format(msgs[1],status.first,status.second) << std::endl; } attempts++; } while (status.second!=4 && attempts<maxattempts); if (attempts==maxattempts) out << fmt::format(msgs[3],attempts)<< std::endl; else out << fmt::format(msgs[2],expected,attempts)<< std::endl; return attempts; } int _main(std::istream &in = std::cin, std::ostream &out = std::cout) { // Seed rand since random_shuffle _probably_ uses it. srand(static_cast<unsigned>(time(0))); std::string randomNumber = generateRandomNumber(); acceptGuess(randomNumber, in, out); return 0; }
- #include <fmt/format.h>
- #include <iostream>
- #include <cstdlib>
- #include <ctime>
- #include <vector>
- #include <bitset>
- #include <algorithm>
- #include <cmath>
- #include <cctype>
- #include <random>
using std::cin;using std::cout;using std::endl;using std::istream;using std::make_pair;using std::mt19937;using std::ostream;using std::pair;using std::random_device;using std::string;using std::vector;string generateRandomNumber() {vector<char> digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};// Initialize random number generatorrandom_device rd; // Obtain a random number from hardwaremt19937 g(rd()); // Seed the generator- static const std::string msgs[]={
- "Enter your guess (a 4-digit number with non-repeating digits): ",
- "Correct numbers: {} Correct position: {}",
- "Congratulations! You guessed the number {} correctly in {} attempts!",
- "Oups.. You could not guess the number in {} attempts!",
- "Invalid input. Please enter a 4-digit number with non-repeating digits."
- };
- // Initialize random number generator outside functions
- static std::random_device rd; // Obtain a random number from hardware
- static std::mt19937 g(rd()); // Seed the generator
- std::string generateRandomNumber() {
- static std::string base{"0123456789"};
- // Shuffle digits
shuffle(digits.begin(), digits.end(), g);- std::shuffle(base.begin(), base.end(), g);
- // Return the first 4 digits as a string
return string(digits.begin(), digits.begin() + 4);- return base.substr(0,4);
- }
bool hasDuplicateDigits(const string &number) {vector<bool> seen(10, false);for (const auto c : number) {if (seen[c - '0']) return true;seen[c - '0'] = true;}return false;- bool hasDuplicateDigits(const std::string &number) {
- return std::accumulate(number.cbegin(),number.cend(), std::bitset<10>{0},
- [](auto &bs,auto c) {return bs.set(c-'0');}
- ).count()!=number.size();
- }
bool isNumeric(const string &s) {return all_of(s.begin(), s.end(), [](char c){ return isdigit(c); });- bool isNumeric(const std::string &s) {
- return std::all_of(s.begin(), s.end(), ::isdigit);
- }
string getUserGuess(istream &in = cin, ostream &out = cout) {string guess;out << "Enter your guess (a 4-digit number with non-repeating digits): ";- std::string getUserGuess(std::istream &in = std::cin, std::ostream &out = std::cout) {
- std::string guess;
- out << msgs[0];
- in >> guess;
- return guess;
- }
pair<int, int> checkGuess(const string &randomNumber, const string &userGuess) {int correctNumbers = 0;int correctPosition = 0;- std::pair<int, int> checkGuess(const std::string &randomNumber, const std::string &userGuess) {
- std::pair<int, int> ret {0,0};
- for (int i = 0; i < 4; ++i) {
- if (randomNumber[i] == userGuess[i]) {
correctNumbers++;correctPosition++;} else if (count(randomNumber.begin(), randomNumber.end(), userGuess[i])) {correctNumbers++;- ++std::get<0>(ret), ++std::get<1>(ret);
- } else if (std::count(randomNumber.begin(), randomNumber.end(), userGuess[i])) {
- ++std::get<0>(ret);
- }
- }
return make_pair(correctNumbers, correctPosition);- return ret;
- }
int acceptGuess(const string &expected, istream &in = cin, ostream &out = cout) {- int acceptGuess(const std::string &expected, std::istream &in = std::cin, std::ostream &out = std::cout, int maxattempts=20) {
- int attempts = 0;
while (true) {string userGuess = getUserGuess(in, out);- std::pair status{0,0};
- do {
- std::string userGuess = getUserGuess(in, out);
- if (userGuess.length() != 4 || hasDuplicateDigits(userGuess) || !isNumeric(userGuess)) {
out << "Invalid input. Please enter a 4-digit number with non-repeating digits." << endl;continue;- out << msgs[4] << std::endl;
- } else {
- status = checkGuess(expected, userGuess);
- out << fmt::format(msgs[1],status.first,status.second) << std::endl;
- }
auto [corNum, corPos] = checkGuess(expected, userGuess);out << "Correct numbers: " << corNum << " Correct position: " << corPos << endl;- attempts++;
if (corPos == 4) {out << "Congratulations! You guessed the number " << expected << " correctly in " << attempts << " attempts!" << endl;break;}}- } while (status.second!=4 && attempts<maxattempts);
- if (attempts==maxattempts)
- out << fmt::format(msgs[3],attempts)<< std::endl;
- else
- out << fmt::format(msgs[2],expected,attempts)<< std::endl;
- return attempts;
- }
int _main(istream &in = cin, ostream &out = cout) {- int _main(std::istream &in = std::cin, std::ostream &out = std::cout) {
- // Seed rand since random_shuffle _probably_ uses it.
- srand(static_cast<unsigned>(time(0)));
string randomNumber = generateRandomNumber();- std::string randomNumber = generateRandomNumber();
- acceptGuess(randomNumber, in, out);
- return 0;
- }
Actuallly ... accumulates returns... what you specify ??
#include <vector> #include <numeric> template <typename T> using add_t=decltype(T() + T()); template <typename T = double> add_t<T> sum(const std::vector<T>& v) { return std::accumulate(v.cbegin(),v.cend(),add_t<T>{0}); }
- #include <vector>
- #include <numeric>
- template <typename T> using add_t=decltype(T() + T());
- template <typename T = double>
decltype(T() + T()) sum(const std::vector<T>& v) {decltype(T() + T()) res = 0;for (const T &num : v) res += num;return res;- add_t<T> sum(const std::vector<T>& v) {
- return std::accumulate(v.cbegin(),v.cend(),add_t<T>{0});
- }