const RGB_MAX: f64 = 255.; fn rgb_to_hsv(rgb: (u8, u8, u8)) -> (u16, u8, u8) { let (r, g, b) = rgb; let v = r.max(g).max(b) as f64 / RGB_MAX; if v == 0. { return (0, 0, 0); } let r = r as f64 / v; let g = g as f64 / v; let b = b as f64 / v; let s = 1. - r.min(g).min(b) as f64 / RGB_MAX; if s == 0. { return (0, 0, (v * 100.) as u8); } let hue_offset = |color| 60. * (1. - (1. - color / RGB_MAX) / s); let r = hue_offset(r); let g = hue_offset(g); let b = hue_offset(b); let peak = r.max(g).max(b); let h = if r == peak { // mostly red if g < b { 360. - b } else { 000. + g } } else if g == peak { // mostly green if b < r { 120. - r } else { 120. + b } } else { // mostly blue if r < g { 240. - g } else { 240. + r } }; let h = h.round() as u16; let s = (s * 100.).round() as u8; let v = (v * 100.).round() as u8; let hsv = (h, s, v); hsv }
function rgbToHsv(rgb) {let r = rgb[0], g = rgb[1], b = rgb[2];const v = Math.max(r, g, b) / 255;if (v == 0) return Array.of(0, 0, 0);r /= v;g /= v;b /= v;const s = 1 - Math.min(r, g, b) / 255;if (s == 0) return Array.of(0, 0, v * 100);r = 255 - (255 - r) / s;g = 255 - (255 - g) / s;b = 255 - (255 - b) / s;const peak = Math.max(r, g, b);let h = 0;if (r == peak) h = g < b ? 360 - b * 60 / 255 : g * 60 / 255;else if (g == peak) h = r > b ? 120 - r * 60 / 255 : 120 + b * 60 / 255;else h = r > g ? 240 + r * 60 / 255 : 240 - g * 60 / 255;return Array.of(Math.round(h), Math.round(s * 100), Math.round(v * 100));- const RGB_MAX: f64 = 255.;
- fn rgb_to_hsv(rgb: (u8, u8, u8)) -> (u16, u8, u8) {
- let (r, g, b) = rgb;
- let v = r.max(g).max(b) as f64 / RGB_MAX;
- if v == 0. {
- return (0, 0, 0);
- }
- let r = r as f64 / v;
- let g = g as f64 / v;
- let b = b as f64 / v;
- let s = 1. - r.min(g).min(b) as f64 / RGB_MAX;
- if s == 0. {
- return (0, 0, (v * 100.) as u8);
- }
- let hue_offset = |color| 60. * (1. - (1. - color / RGB_MAX) / s);
- let r = hue_offset(r);
- let g = hue_offset(g);
- let b = hue_offset(b);
- let peak = r.max(g).max(b);
- let h = if r == peak { // mostly red
- if g < b { 360. - b } else { 000. + g }
- } else if g == peak { // mostly green
- if b < r { 120. - r } else { 120. + b }
- } else { // mostly blue
- if r < g { 240. - g } else { 240. + r }
- };
- let h = h.round() as u16;
- let s = (s * 100.).round() as u8;
- let v = (v * 100.).round() as u8;
- let hsv = (h, s, v);
- hsv
- }
#[cfg(test)] mod tests { use super::rgb_to_hsv; #[test] fn rainbow() { assert_eq!(rgb_to_hsv((255, 000, 000)), (000, 100, 100)); // red assert_eq!(rgb_to_hsv((255, 128, 000)), (030, 100, 100)); // orange assert_eq!(rgb_to_hsv((255, 255, 000)), (060, 100, 100)); // yellow assert_eq!(rgb_to_hsv((000, 255, 000)), (120, 100, 100)); // green assert_eq!(rgb_to_hsv((000, 255, 255)), (180, 100, 100)); // cyan assert_eq!(rgb_to_hsv((000, 000, 255)), (240, 100, 100)); // blue assert_eq!(rgb_to_hsv((128, 000, 255)), (270, 100, 100)); // purple assert_eq!(rgb_to_hsv((255, 000, 255)), (300, 100, 100)); // magenta } #[test] fn grey() { assert_eq!(rgb_to_hsv((000, 000, 000)), (0, 0, 000)); // black assert_eq!(rgb_to_hsv((051, 051, 051)), (0, 0, 020)); // off-black assert_eq!(rgb_to_hsv((102, 102, 102)), (0, 0, 040)); // dark grey assert_eq!(rgb_to_hsv((153, 153, 153)), (0, 0, 060)); // light grey assert_eq!(rgb_to_hsv((204, 204, 204)), (0, 0, 080)); // off-white assert_eq!(rgb_to_hsv((255, 255, 255)), (0, 0, 100)); // white } #[test] fn grey_rainbow() { assert_eq!(rgb_to_hsv((204, 102, 102)), (000, 50, 80)); // red assert_eq!(rgb_to_hsv((204, 153, 102)), (030, 50, 80)); // orange assert_eq!(rgb_to_hsv((204, 204, 102)), (060, 50, 80)); // yellow assert_eq!(rgb_to_hsv((102, 204, 102)), (120, 50, 80)); // green assert_eq!(rgb_to_hsv((102, 204, 204)), (180, 50, 80)); // cyan assert_eq!(rgb_to_hsv((102, 102, 204)), (240, 50, 80)); // blue assert_eq!(rgb_to_hsv((153, 102, 204)), (270, 50, 80)); // purple assert_eq!(rgb_to_hsv((204, 102, 204)), (300, 50, 80)); // magenta } }
const assert = require("chai").assert;function arraysEqual(a, b) {assert.strictEqual((a == null), (b == null));assert.strictEqual(a.length, b.length);for (let i = 0; i < a.length; ++i) assert.strictEqual(a[i], b[i]);}describe("Solution", function() {it("Rainbow", function() {arraysEqual(rgbToHsv(Array.of(255, 0, 0)), Array.of(0, 100, 100));arraysEqual(rgbToHsv(Array.of(255, 128, 0)), Array.of(30, 100, 100));arraysEqual(rgbToHsv(Array.of(255, 255, 0)), Array.of(60, 100, 100));arraysEqual(rgbToHsv(Array.of(0, 255, 0)), Array.of(120, 100, 100));arraysEqual(rgbToHsv(Array.of(0, 255, 255)), Array.of(180, 100, 100));arraysEqual(rgbToHsv(Array.of(0, 0, 255)), Array.of(240, 100, 100));arraysEqual(rgbToHsv(Array.of(128, 0, 255)), Array.of(270, 100, 100));});it("Grey", function() {arraysEqual(rgbToHsv(Array.of(0, 0, 0)), Array.of(0, 0, 0));arraysEqual(rgbToHsv(Array.of(51, 51, 51)), Array.of(0, 0, 20));arraysEqual(rgbToHsv(Array.of(102, 102, 102)), Array.of(0, 0, 40));arraysEqual(rgbToHsv(Array.of(153, 153, 153)), Array.of(0, 0, 60));arraysEqual(rgbToHsv(Array.of(204, 204, 204)), Array.of(0, 0, 80));arraysEqual(rgbToHsv(Array.of(255, 255, 255)), Array.of(0, 0, 100));});it("Grey_Rainbow", function() {arraysEqual(rgbToHsv(Array.of(204, 102, 102)), Array.of(0, 50, 80));arraysEqual(rgbToHsv(Array.of(204, 153, 102)), Array.of(30, 50, 80));arraysEqual(rgbToHsv(Array.of(204, 204, 102)), Array.of(60, 50, 80));arraysEqual(rgbToHsv(Array.of(102, 204, 102)), Array.of(120, 50, 80));arraysEqual(rgbToHsv(Array.of(102, 204, 204)), Array.of(180, 50, 80));arraysEqual(rgbToHsv(Array.of(102, 102, 204)), Array.of(240, 50, 80));arraysEqual(rgbToHsv(Array.of(153, 102, 204)), Array.of(270, 50, 80));});});- #[cfg(test)]
- mod tests {
- use super::rgb_to_hsv;
- #[test]
- fn rainbow() {
- assert_eq!(rgb_to_hsv((255, 000, 000)), (000, 100, 100)); // red
- assert_eq!(rgb_to_hsv((255, 128, 000)), (030, 100, 100)); // orange
- assert_eq!(rgb_to_hsv((255, 255, 000)), (060, 100, 100)); // yellow
- assert_eq!(rgb_to_hsv((000, 255, 000)), (120, 100, 100)); // green
- assert_eq!(rgb_to_hsv((000, 255, 255)), (180, 100, 100)); // cyan
- assert_eq!(rgb_to_hsv((000, 000, 255)), (240, 100, 100)); // blue
- assert_eq!(rgb_to_hsv((128, 000, 255)), (270, 100, 100)); // purple
- assert_eq!(rgb_to_hsv((255, 000, 255)), (300, 100, 100)); // magenta
- }
- #[test]
- fn grey() {
- assert_eq!(rgb_to_hsv((000, 000, 000)), (0, 0, 000)); // black
- assert_eq!(rgb_to_hsv((051, 051, 051)), (0, 0, 020)); // off-black
- assert_eq!(rgb_to_hsv((102, 102, 102)), (0, 0, 040)); // dark grey
- assert_eq!(rgb_to_hsv((153, 153, 153)), (0, 0, 060)); // light grey
- assert_eq!(rgb_to_hsv((204, 204, 204)), (0, 0, 080)); // off-white
- assert_eq!(rgb_to_hsv((255, 255, 255)), (0, 0, 100)); // white
- }
- #[test]
- fn grey_rainbow() {
- assert_eq!(rgb_to_hsv((204, 102, 102)), (000, 50, 80)); // red
- assert_eq!(rgb_to_hsv((204, 153, 102)), (030, 50, 80)); // orange
- assert_eq!(rgb_to_hsv((204, 204, 102)), (060, 50, 80)); // yellow
- assert_eq!(rgb_to_hsv((102, 204, 102)), (120, 50, 80)); // green
- assert_eq!(rgb_to_hsv((102, 204, 204)), (180, 50, 80)); // cyan
- assert_eq!(rgb_to_hsv((102, 102, 204)), (240, 50, 80)); // blue
- assert_eq!(rgb_to_hsv((153, 102, 204)), (270, 50, 80)); // purple
- assert_eq!(rgb_to_hsv((204, 102, 204)), (300, 50, 80)); // magenta
- }
- }
Mixing procedural while loops and functional iterator chaining? Why not! Theoretically just as fast, assuming the compiler is smart enough.
use std::iter::repeat; pub fn sort_desc(mut n: u64) -> u64 { let mut digit_counts = [0; 10]; while n > 0 { digit_counts[n as usize % 10] += 1; n /= 10; } digit_counts .into_iter() .enumerate() .rev() .flat_map(|(digit, count)| repeat(digit as u64).take(count)) .fold(0, |result, digit| result * 10 + digit) }
- use std::iter::repeat;
- pub fn sort_desc(mut n: u64) -> u64 {
- let mut digit_counts = [0; 10];
- while n > 0 {
let digit = (n % 10) as usize;digit_counts[digit] += 1;- digit_counts[n as usize % 10] += 1;
- n /= 10;
- }
let mut result = 0;for digit in (0..10).rev() {for _ in 0..digit_counts[digit] {result *= 10;result += digit as u64;}}result- digit_counts
- .into_iter()
- .enumerate()
- .rev()
- .flat_map(|(digit, count)| repeat(digit as u64).take(count))
- .fold(0, |result, digit| result * 10 + digit)
- }
I used a different accumulation strategy. It's probably the same speed.
pub fn sort_desc(mut n: u64) -> u64 { let mut digit_counts = [0; 10]; while n > 0 { let digit = (n % 10) as usize; digit_counts[digit] += 1; n /= 10; } let mut result = 0; for digit in (0..10).rev() { for _ in 0..digit_counts[digit] { result *= 10; result += digit as u64; } } result }
- pub fn sort_desc(mut n: u64) -> u64 {
- let mut digit_counts = [0; 10];
- while n > 0 {
- let digit = (n % 10) as usize;
- digit_counts[digit] += 1;
- n /= 10;
- }
- let mut result = 0;
let mut fac = 1;for digit in 0..10 {- for digit in (0..10).rev() {
- for _ in 0..digit_counts[digit] {
result += (digit as u64) * fac;fac *= 10;- result *= 10;
- result += digit as u64;
- }
- }
- result
- }
use itertools::Itertools; use std::ops::Neg; fn shannon_entropy(s: &str) -> f64 { let symbols: Vec<char> = s.chars().collect(); let len = symbols.len() as f64; symbols .iter() .unique() .map(|x| { let p = symbols.iter().filter(|&n| n == x).count() as f64 / len; p * p.log2() }) .sum::<f64>() .neg() }
import math- use itertools::Itertools;
- use std::ops::Neg;
def shannon_entropy(s):symbols = list(s)unique_symbols = set(s)M = float(len(s))entropy_list = []for x in unique_symbols:n_i = symbols.count(x)P_i = n_i / Mentropy_i = P_i * (math.log(P_i, 2))entropy_list.append(entropy_i)sh_entropy = -(sum(entropy_list))return sh_entropy- fn shannon_entropy(s: &str) -> f64 {
- let symbols: Vec<char> = s.chars().collect();
- let len = symbols.len() as f64;
- symbols
- .iter()
- .unique()
- .map(|x| {
- let p = symbols.iter().filter(|&n| n == x).count() as f64 / len;
- p * p.log2()
- })
- .sum::<f64>()
- .neg()
- }
const EPSILON: f64 = 1e-5; fn test(input: &str, output: f64) { assert!((shannon_entropy(input) - output).abs() < EPSILON); } #[test] fn tests() { test("Lorem ipsum", 3.27761); test("110010111001011100101110010111001011100101", 0.98523); test("0000000", 0.0); }
import codewars_test as testfrom solution import shannon_entropy- const EPSILON: f64 = 1e-5;
@test.describe("Solution tests")def test_group():@test.it("Should correctly calculate Shannon entropy")def _():test.assert_equals(round(shannon_entropy("Lorem ipsum"),5), 3.27761)test.assert_equals(round(shannon_entropy("110010111001011100101110010111001011100101"),5), 0.98523)test.assert_equals(round(shannon_entropy("0000000"),5), 0)- fn test(input: &str, output: f64) {
- assert!((shannon_entropy(input) - output).abs() < EPSILON);
- }
- #[test]
- fn tests() {
- test("Lorem ipsum", 3.27761);
- test("110010111001011100101110010111001011100101", 0.98523);
- test("0000000", 0.0);
- }
Algorithms
Strings
fn remove_string(input: &str, n: usize) -> Option<&str> { if n == 0 { return None } input.split('\0').nth(n - 1) }
#include <stdlib.h>#include <string.h>/*Heap allocate the string and return it.*/char* remove_string(const char *input, const int n){if (n <= 0 || input == NULL) return NULL;size_t len = 0;for (size_t i = 0; i < (size_t)n; ++i){input += len;len = strlen(input) + 1;if (len == 1) return NULL;}size_t index = 0;char *res = (char*)malloc(sizeof(char) * (len + 1));for (; *input != '\0'; input++) res[index++] = *input; res[index] = '\0';return res;- fn remove_string(input: &str, n: usize) -> Option<&str> {
- if n == 0 { return None }
- input.split('\0').nth(n - 1)
- }
#[test] fn test() { assert_eq!(remove_string("hello\0world", 1), Some("hello")); assert_eq!(remove_string("well\0done", 2), Some("done")); assert_eq!(remove_string("you\0are\0close", 3), Some("close")); assert_eq!(remove_string("you\0almost\0finished\0the\0kumite", 5), Some("kumite")); assert_eq!(remove_string("not\0the\0last\0string", 3), Some("last")); assert_eq!(remove_string("edge\0case", 0), None); assert_eq!(remove_string("another\0edge\0case", 4), None); }
#include <criterion/criterion.h>#include <stdlib.h>#include <string.h>char* remove_string(const char *input, const int n);Test(remove_string, should_pass_all_the_tests_provided){char* result = remove_string("hello\0world\0", 1);cr_assert_str_eq(result, "hello");free(result);result = remove_string("well\0done\0", 2);cr_assert_str_eq(result, "done");free(result);result = remove_string("you\0are\0close\0", 3);cr_assert_str_eq(result, "close");free(result);result = remove_string("you\0almost\0finished\0the\0kumite\0", 5);cr_assert_str_eq(result, "kumite");free(result);result = remove_string("not\0the\0last\0string\0", 3);cr_assert_str_eq(result, "last");free(result);result = remove_string("edge\0case\0", 0);cr_assert_eq(result, NULL);free(result);result = remove_string("another\0edge\0case\0", 4);cr_assert_eq(result, NULL);free(result);}- #[test]
- fn test() {
- assert_eq!(remove_string("hello\0world", 1), Some("hello"));
- assert_eq!(remove_string("well\0done", 2), Some("done"));
- assert_eq!(remove_string("you\0are\0close", 3), Some("close"));
- assert_eq!(remove_string("you\0almost\0finished\0the\0kumite", 5), Some("kumite"));
- assert_eq!(remove_string("not\0the\0last\0string", 3), Some("last"));
- assert_eq!(remove_string("edge\0case", 0), None);
- assert_eq!(remove_string("another\0edge\0case", 4), None);
- }
fn missing_number(nums: &[u32]) -> u32 { (0..=nums.len() as u32).find(|n| !nums.contains(&n)).unwrap() }
class Solution {public:int missingNumber(vector<int>& nums) {}};- fn missing_number(nums: &[u32]) -> u32 {
- (0..=nums.len() as u32).find(|n| !nums.contains(&n)).unwrap()
- }
#[test] fn test() { assert_eq!(missing_number(&[0, 1, 2, 3, 4, 6, 7, 8, 9]), 5); assert_eq!(missing_number(&[0, 1, 3, 4]), 2); assert_eq!(missing_number(&[1, 2, 3, 4, 5]), 0); assert_eq!(missing_number(&[0, 1, 2, 3, 4]), 5); assert_eq!(missing_number(&[0]), 1); assert_eq!(missing_number(&[1]), 0); }
#include <criterion/criterion.h>// Function to find the missing number in an array of integersint findMissingNumber(int arr[], int n) {// Code to find the missing number- #[test]
- fn test() {
- assert_eq!(missing_number(&[0, 1, 2, 3, 4, 6, 7, 8, 9]), 5);
- assert_eq!(missing_number(&[0, 1, 3, 4]), 2);
- assert_eq!(missing_number(&[1, 2, 3, 4, 5]), 0);
- assert_eq!(missing_number(&[0, 1, 2, 3, 4]), 5);
- assert_eq!(missing_number(&[0]), 1);
- assert_eq!(missing_number(&[1]), 0);
- }
Test(findMissingNumber, should_return_5_for_given_array) {int arr[] = {1, 2, 3, 4, 6, 7, 8, 9, 10};int n = sizeof(arr) / sizeof(arr[0]);cr_assert_eq(findMissingNumber(arr, n), 5);}Test(findMissingNumber, should_return_2_for_given_array) {int arr[] = {1, 3, 4, 5};int n = sizeof(arr) / sizeof(arr[0]);cr_assert_eq(findMissingNumber(arr, n), 2);}
fn split(string: &str, separator: char) -> Vec<&str> { string.split(separator).collect() }
#include <string>#include <sstream>#include <vector>auto split(const std::string& str, char sep) {auto result = std::vector<std::string>{};auto stream = std::stringstream(str);auto buffer = std::string{};while (std::getline(stream, buffer, sep)) result.emplace_back(buffer);return result;- fn split(string: &str, separator: char) -> Vec<&str> {
- string.split(separator).collect()
- }
#[test] fn test() { assert_eq!(split("Hello World", ' '), ["Hello", "World"]); assert_eq!(split("John-brings-his-cat", '-'), ["John", "brings", "his", "cat"]); }
// TODO: Replace examples and use TDD by writing your own testsDescribe(any_group_name_you_want){It(should_do_something){Assert::That(split("Hello World", ' '), Equals(std::vector<std::string>{"Hello", "World"}));Assert::That(split("John-brings-his-cat", '-'), Equals(std::vector<std::string>{"John","brings","his","cat"}));}};- #[test]
- fn test() {
- assert_eq!(split("Hello World", ' '), ["Hello", "World"]);
- assert_eq!(split("John-brings-his-cat", '-'), ["John", "brings", "his", "cat"]);
- }
fn mean(x: &[u64]) -> u64 { x.iter().sum::<u64>() / x.len() as u64 }
#include <iostream>double Mean(double x[], int n){double sum = 0;for(int i = 0; i < n; i++){sum += x[i];}return sum / n;}- fn mean(x: &[u64]) -> u64 {
- x.iter().sum::<u64>() / x.len() as u64
- }
#[test] fn test() { assert_eq!(mean(&[4, 8, 4, 8]), 6); }
// TODO: Replace examples and use TDD by writing your own testsDescribe(any_group_name_you_want){It(should_do_something){int n = 4;double x[] = {4,8,4,8};double mean;mean = Mean(x ,n);Assert::That(6, Equals(mean));}};- #[test]
- fn test() {
- assert_eq!(mean(&[4, 8, 4, 8]), 6);
- }
fn total_fine(speed: i32, signals: &[i32]) -> u32 { signals.iter().map(|&signal| fine(speed, signal)).sum() } fn fine(speed: i32, signal: i32) -> u32 { match speed - signal { ..=9 => 0, 10..=19 => 100, 20..=29 => 250, 30.. => 500 } }
public class Kata {public static int speedLimit(int speed, int[] signals) {int penalty = 0;for (int i = 0; i < signals.length; i++){if (speed > signals[i]){if (speed - signals[i] >= 30){penalty += 500;} else if (speed - signals[i] >= 20 && speed - signals[i] < 30){penalty += 250;} else if (speed - signals[i] >= 10 && speed - signals[i] < 20){penalty += 100;}}}return penalty;- fn total_fine(speed: i32, signals: &[i32]) -> u32 {
- signals.iter().map(|&signal| fine(speed, signal)).sum()
- }
- fn fine(speed: i32, signal: i32) -> u32 {
- match speed - signal {
- ..=9 => 0,
- 10..=19 => 100,
- 20..=29 => 250,
- 30.. => 500
- }
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test_add() { assert_eq!(total_fine(70, &[]), 0); assert_eq!(total_fine(60, &[80, 70, 60]), 0); assert_eq!(total_fine(0, &[15, 25, 35, 46]), 0); assert_eq!(total_fine(100, &[110, 100, 80]), 250); assert_eq!(total_fine(130, &[140, 130, 100]), 500); } }
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;- #[cfg(test)]
- mod tests {
- use super::*;
// TODO: Replace examples and use TDD by writing your own testsclass SolutionTest {@Testvoid testSomething() {// assertEquals("expected", "actual");- #[test]
- fn test_add() {
- assert_eq!(total_fine(70, &[]), 0);
- assert_eq!(total_fine(60, &[80, 70, 60]), 0);
- assert_eq!(total_fine(0, &[15, 25, 35, 46]), 0);
- assert_eq!(total_fine(100, &[110, 100, 80]), 250);
- assert_eq!(total_fine(130, &[140, 130, 100]), 500);
- }
- }
Optimized for conciseness
use itertools::Itertools; fn print(number: u64) -> u64 { number.to_string().chars().sorted().rev().collect::<String>().parse().unwrap() }
fn print(mut number: u64) -> u64 {let mut digits = Vec::new();while number > 0 {digits.push(number % 10);number /= 10;}digits.sort();digits.into_iter().rev().fold(0, |result, digit| result * 10 + digit)- use itertools::Itertools;
- fn print(number: u64) -> u64 {
- number.to_string().chars().sorted().rev().collect::<String>().parse().unwrap()
- }
Optimized for speed
fn print(mut number: u64) -> u64 { let mut digits = Vec::new(); while number > 0 { digits.push(number % 10); number /= 10; } digits.sort(); digits.into_iter().rev().fold(0, |result, digit| result * 10 + digit) }
import java.util.Arrays;public class MaxNumber {public static long print(long number) {return number- fn print(mut number: u64) -> u64 {
- let mut digits = Vec::new();
- while number > 0 {
- digits.push(number % 10);
- number /= 10;
- }
- digits.sort();
- digits.into_iter().rev().fold(0, |result, digit| result * 10 + digit)
- }
#[test] fn test() { assert_eq!(print(4), 4); assert_eq!(print(12), 21); assert_eq!(print(101), 110); assert_eq!(print(400000005000007000), 754000000000000000); assert_eq!(print(307778062924466824), 988777666444322200); }
import static org.junit.Assert.assertEquals;import org.junit.Test;import java.util.Random;public class MaxNumberTest {@Testpublic void testFour() {assertEquals(4, MaxNumber.print(4));}@Testpublic void testTwelve() {assertEquals(21, MaxNumber.print(12));}@Testpublic void testOneHundred() {assertEquals(110, MaxNumber.print(101));}@Testpublic void testHuge1() {assertEquals(754000000000000000L, MaxNumber.print(400000005000007000L));}@Testpublic void testHuge2() {assertEquals(988777666444322200L, MaxNumber.print(307778062924466824L));}- #[test]
- fn test() {
- assert_eq!(print(4), 4);
- assert_eq!(print(12), 21);
- assert_eq!(print(101), 110);
- assert_eq!(print(400000005000007000), 754000000000000000);
- assert_eq!(print(307778062924466824), 988777666444322200);
- }
struct Test { a: Option<String>, b: Option<String>, } impl Test { fn new() -> Self { Self { a: Default::default(), b: None, } } }
namespace Test {public class Test {public string a;public string b = null;}- struct Test {
- a: Option<String>,
- b: Option<String>,
- }
- impl Test {
- fn new() -> Self {
- Self {
- a: Default::default(),
- b: None,
- }
- }
- }
#[test] fn test() { let test = Test::new(); assert_eq!(test.a, test.b); }
namespace Solution {using NUnit.Framework;using System;using Test;[TestFixture]public class SolutionTest{[Test]public void MyTest(){var test = new Test();Assert.AreEqual(test.a, test.b);}}}- #[test]
- fn test() {
- let test = Test::new();
- assert_eq!(test.a, test.b);
- }
fn find_max(array: &[i32]) -> i32 { *array.iter().max().unwrap() }
public class Kata {public static int findMax(int[] my_array) {// Write a method that returns the largest integer in the list.// You can assume that the list has at least one element.return 7;}}- fn find_max(array: &[i32]) -> i32 {
- *array.iter().max().unwrap()
- }
#[test] fn test() { assert_eq!(find_max(&[4, 5, 6, 7]), 7); }
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;// TODO: Write more tests to prove your code bleowclass SolutionTest {@Testvoid testSomething() {assertEquals(Kata.findMax(new int[]{4, 5, 6, 7}), 7);}- #[test]
- fn test() {
- assert_eq!(find_max(&[4, 5, 6, 7]), 7);
- }
Algorithms
Logic
fn get_nth_words(string: &str, n: usize) -> String { if n == 0 { return String::new() } string.split(" ").skip(n - 1).step_by(n).collect::<Vec<_>>().join(" ") }
def get_nth_words(string, n):if n < 1: return ""return ' '.join(['',*string.split()][::n][1:])- fn get_nth_words(string: &str, n: usize) -> String {
- if n == 0 { return String::new() }
- string.split(" ").skip(n - 1).step_by(n).collect::<Vec<_>>().join(" ")
- }
#[cfg(test)] mod tests { use super::get_nth_words; #[test] fn basic_tests() { assert_eq!(get_nth_words("Hello World", 2), "World"); assert_eq!(get_nth_words("1 2 3 4 5 6 7 8 9", 3), "3 6 9"); assert_eq!(get_nth_words("Lorem ipsum dolor sit amet", 1), "Lorem ipsum dolor sit amet"); assert_eq!(get_nth_words("And a one and a two and a three and a four", 3), "one two three four"); } #[test] fn not_enough_words() { assert_eq!(get_nth_words("There aren't enough words.", 5), ""); assert_eq!(get_nth_words("What if there weren't enough words?", 15), ""); assert_eq!(get_nth_words("What are the chances of there being enough words?", 150), ""); assert_eq!(get_nth_words("", 5000), ""); } #[test] fn attempt_errors() { assert_eq!(get_nth_words("", 1), ""); assert_eq!(get_nth_words("error 1 2 3 4", 0), ""); } }
import codewars_test as test- #[cfg(test)]
- mod tests {
- use super::get_nth_words;
- #[test]
- fn basic_tests() {
- assert_eq!(get_nth_words("Hello World", 2), "World");
- assert_eq!(get_nth_words("1 2 3 4 5 6 7 8 9", 3), "3 6 9");
- assert_eq!(get_nth_words("Lorem ipsum dolor sit amet", 1), "Lorem ipsum dolor sit amet");
- assert_eq!(get_nth_words("And a one and a two and a three and a four", 3), "one two three four");
- }
- #[test]
- fn not_enough_words() {
- assert_eq!(get_nth_words("There aren't enough words.", 5), "");
- assert_eq!(get_nth_words("What if there weren't enough words?", 15), "");
- assert_eq!(get_nth_words("What are the chances of there being enough words?", 150), "");
- assert_eq!(get_nth_words("", 5000), "");
- }
from solution import get_nth_wordsbasictests = [["Hello World", 2, "World"],["1 2 3 4 5 6 7 8 9", 3, "3 6 9"],["Lorem ipsum dolor sit amet", 1, "Lorem ipsum dolor sit amet"],["And a one and a two and a three and a four", 3, "one two three four"]]notenoughwords = [["There aren't enough words.", 5, ""],["What if there weren't enough words?", 15, ""],["What are the chances of there being enough words?", 150, ""],["", 5000, ""]]attempterrors = [["", 1, ""],["error 1 2 3 4", 0, ""],["Hmm... What about this?", -1, ""],["", -5, ""]]@test.describe("Basic Tests")def basic_test_group():@test.it("Basic Tests")def basic_tests():for tst in basictests:test.assert_equals(get_nth_words(tst[0], tst[1]), tst[2])@test.it("Not Enough Words")def not_enough_words():for tst in notenoughwords:test.assert_equals(get_nth_words(tst[0], tst[1]), tst[2])@test.it("Exception Handling")def cause_errors():for tst in attempterrors:test.assert_equals(get_nth_words(tst[0], tst[1]), tst[2])- #[test]
- fn attempt_errors() {
- assert_eq!(get_nth_words("", 1), "");
- assert_eq!(get_nth_words("error 1 2 3 4", 0), "");
- }
- }
fn find_multiples(base: usize, limit: usize) -> Vec<usize> { (base..=limit).step_by(base).collect() }
def find_multiples(b, l):a=[]for i in range(b,l+1,b):a.append(i)return a- fn find_multiples(base: usize, limit: usize) -> Vec<usize> {
- (base..=limit).step_by(base).collect()
- }
#[test] fn test() { assert_eq!(find_multiples(5, 25), [5, 10, 15, 20, 25]); assert_eq!(find_multiples(1, 2), [1, 2]); assert_eq!(find_multiples(6, 30), [6, 12, 18, 24, 30]); }
import codewars_test as testfrom solution import find_multiples@test.describe("Fixed Tests")def fixed_tests():@test.it('Basic Test Cases')def basic_test_cases():test.assert_equals(find_multiples(5, 25), [5, 10, 15, 20, 25])test.assert_equals(find_multiples(1, 2), [1, 2])test.assert_equals(find_multiples(6, 30), [6, 12, 18, 24, 30])- #[test]
- fn test() {
- assert_eq!(find_multiples(5, 25), [5, 10, 15, 20, 25]);
- assert_eq!(find_multiples(1, 2), [1, 2]);
- assert_eq!(find_multiples(6, 30), [6, 12, 18, 24, 30]);
- }