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.
fn binary_search(arr: &[i32], val: i32) -> Option<usize> { arr.binary_search(&val).ok() }
#returns the index of val if val is in the array, else -1 if val is not in the array.#precondition: arr must be sorted in ascending orderdef binary_search(arr,val):i=-1j=len(arr)while i+1!=j:m=i+(j-i)//2if arr[m]<val:i=melif arr[m]>val:j=melse:return mreturn -1- fn binary_search(arr: &[i32], val: i32) -> Option<usize> {
- arr.binary_search(&val).ok()
- }
#[test] fn test() { assert_eq!(binary_search(&[1,2,3,4,5,6,7,8], 3), Some(2)); assert_eq!(binary_search(&[1,2,3,4,5,6,7,8], 100), None); assert_eq!(binary_search(&[1,2,3,4,5,6,7,8], -1), None); assert_eq!(binary_search(&[0], 0), Some(0)); assert_eq!(binary_search(&[0], -10), None); assert_eq!(binary_search(&[0], 10), None); assert_eq!(binary_search(&[], 42), None); }
import codewars_test as test# TODO Write tests# import solution # or from solution import examplefrom solution import binary_search# test.assert_equals(actual, expected, [optional] message)arr=[1,2,3,4,5,6,7,8]val1=3val2=100val3=-1arr2=[0]val4=0val5=-10val6=10empty=[]val10=42@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(binary_search(arr,val1), 2)test.assert_equals(binary_search(arr,val2), -1)test.assert_equals(binary_search(arr,val3), -1)test.assert_equals(binary_search(arr2,val4), 0)test.assert_equals(binary_search(arr2,val5), -1)test.assert_equals(binary_search(arr2,val6), -1)test.assert_equals(binary_search(empty,val10), -1)- #[test]
- fn test() {
- assert_eq!(binary_search(&[1,2,3,4,5,6,7,8], 3), Some(2));
- assert_eq!(binary_search(&[1,2,3,4,5,6,7,8], 100), None);
- assert_eq!(binary_search(&[1,2,3,4,5,6,7,8], -1), None);
- assert_eq!(binary_search(&[0], 0), Some(0));
- assert_eq!(binary_search(&[0], -10), None);
- assert_eq!(binary_search(&[0], 10), None);
- assert_eq!(binary_search(&[], 42), None);
- }
use rand::seq::SliceRandom; const EYES: [char; 4] = [':', ';', '=', 'X']; const ACCESSORIES: [char; 5] = ['\'', '.', '-', '~', '^']; const MOUTHS: [char; 10] = [']', '}', ')', '>', 'D', '\\', '(', '[', '{', 'O']; fn random_face() -> String { let mut rng = rand::thread_rng(); format!( "{}{}{}", EYES.choose(&mut rng).unwrap(), ACCESSORIES.choose(&mut rng).unwrap(), MOUTHS.choose(&mut rng).unwrap() ) }
from random import choiceeyes=":;=X"accessory=["","'",".","-","~","^",""]mouth="]})>D|\\([{O"def random_smiley():return choice(eyes)+choice(accessory)+choice(mouth)- use rand::seq::SliceRandom;
def many_faces():acc=[]for _ in range(100):acc.append(random_smiley())return " ".join(acc)- const EYES: [char; 4] = [':', ';', '=', 'X'];
- const ACCESSORIES: [char; 5] = ['\'', '.', '-', '~', '^'];
- const MOUTHS: [char; 10] = [']', '}', ')', '>', 'D', '\\', '(', '[', '{', 'O'];
# def garfield_the_1000_faced():# acc=[]# for _ in range(100)- fn random_face() -> String {
- let mut rng = rand::thread_rng();
- format!(
- "{}{}{}",
- EYES.choose(&mut rng).unwrap(),
- ACCESSORIES.choose(&mut rng).unwrap(),
- MOUTHS.choose(&mut rng).unwrap()
- )
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test_eyes() { for _ in 0..100 { assert!(EYES.contains(&random_face().chars().next().unwrap())); } } #[test] fn test_accessories() { for _ in 0..100 { assert!(ACCESSORIES.contains(&random_face().chars().nth(1).unwrap())); } } #[test] fn test_mouths() { for _ in 0..100 { assert!(MOUTHS.contains(&random_face().chars().nth(2).unwrap())); } } }
import codewars_test as test# TODO Write testsimport 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():print(random_smiley())print(many_faces())test.assert_equals(True, True)- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test_eyes() {
- for _ in 0..100 {
- assert!(EYES.contains(&random_face().chars().next().unwrap()));
- }
- }
- #[test]
- fn test_accessories() {
- for _ in 0..100 {
- assert!(ACCESSORIES.contains(&random_face().chars().nth(1).unwrap()));
- }
- }
- #[test]
- fn test_mouths() {
- for _ in 0..100 {
- assert!(MOUTHS.contains(&random_face().chars().nth(2).unwrap()));
- }
- }
- }
mod preloaded; use preloaded::Stats; use std::cmp::Ordering; const THRESHOLD: u32 = 8; fn compute_progress(trainee: Stats, milestone: Stats) -> &'static str { let attendance = check(trainee.attendance, milestone.attendance); let codewars = check(milestone.codewars, trainee.codewars); let tests = check(trainee.tests, milestone.tests); let pulls = check(trainee.pull_requests, milestone.pull_requests); let sum_factors = attendance + codewars + tests + pulls; match sum_factors.cmp(&THRESHOLD) { Ordering::Greater => "Beyond Milestone", Ordering::Equal => "At Milestone", Ordering::Less => "Behind Milestone" } } fn check(a: u32, b: u32) -> u32 { match a.cmp(&b) { Ordering::Greater => 3, Ordering::Equal => 2, Ordering::Less => 1, } }
const Deepa = {attendance: 100,tests: 4,codewars: 7,pullRequests: 12}const Bilal = {attendance: 95,tests: 3,codewars: 7,pullRequests: 12}const milestoneDay = {attendance: 100,tests: 4,codewars: 7,pullRequests: 12}- mod preloaded;
- use preloaded::Stats;
- use std::cmp::Ordering;
const computeProgress = (trainee, milestone) => {const comparator = Object.entries(milestoneDay).length * 2;const checkMilestone = (factor, milestone) => factor > milestone ? 3 : factor === milestone ? 2 : 1;// codewars ranks go downconst checkCodewars = (factor, milestone) => factor < milestone ? 3 : factor === milestone ? 2 : 1;- const THRESHOLD: u32 = 8;
// 1 behind, 2 at, 3 ahead, and there are currently 4 measures// therefore at each milestone 8 is the currently the comparator- fn compute_progress(trainee: Stats, milestone: Stats) -> &'static str {
- let attendance = check(trainee.attendance, milestone.attendance);
- let codewars = check(milestone.codewars, trainee.codewars);
- let tests = check(trainee.tests, milestone.tests);
- let pulls = check(trainee.pull_requests, milestone.pull_requests);
- let sum_factors = attendance + codewars + tests + pulls;
- match sum_factors.cmp(&THRESHOLD) {
- Ordering::Greater => "Beyond Milestone",
- Ordering::Equal => "At Milestone",
- Ordering::Less => "Behind Milestone"
- }
- }
let attendance = checkMilestone(trainee.attendance, milestone.attendance);let codewars = checkCodewars(trainee.codewars, milestone.codewars);let tests = checkMilestone(trainee.tests, milestone.tests);let pulls = checkMilestone(trainee.pullRequests, milestone.pullRequests);const sumFactors = codewars + tests + attendance + pulls;return sumFactors > comparator ? 'Beyond Milestone' : sumFactors === comparator ? 'At Milestone' : 'Behind Milestone'- fn check(a: u32, b: u32) -> u32 {
- match a.cmp(&b) {
- Ordering::Greater => 3,
- Ordering::Equal => 2,
- Ordering::Less => 1,
- }
- }
#[cfg(test)] mod tests { use super::*; const DEEPA: Stats = Stats { attendance: 100, tests: 4, codewars: 7, pull_requests: 12 }; const BILAL: Stats = Stats { attendance: 95, tests: 3, codewars: 7, pull_requests: 12 }; const MILESTONE_DAY: Stats = Stats { attendance: 100, tests: 4, codewars: 7, pull_requests: 12 }; #[test] fn test_at_milestone() { assert_eq!(compute_progress(DEEPA, MILESTONE_DAY), "At Milestone"); } #[test] fn test_behind_milestone() { assert_eq!(compute_progress(BILAL, MILESTONE_DAY), "Behind Milestone"); } }
// 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("Solution", function() {it("Deepa should be At Milestone", function() {assert.equal('At Milestone', computeProgress(Deepa,milestoneDay))});it("Bilal should be Behind Milestone", function() {assert.equal('Behind Milestone', computeProgress(Bilal,milestoneDay))});});- #[cfg(test)]
- mod tests {
- use super::*;
- const DEEPA: Stats = Stats {
- attendance: 100,
- tests: 4,
- codewars: 7,
- pull_requests: 12
- };
- const BILAL: Stats = Stats {
- attendance: 95,
- tests: 3,
- codewars: 7,
- pull_requests: 12
- };
- const MILESTONE_DAY: Stats = Stats {
- attendance: 100,
- tests: 4,
- codewars: 7,
- pull_requests: 12
- };
- #[test]
- fn test_at_milestone() {
- assert_eq!(compute_progress(DEEPA, MILESTONE_DAY), "At Milestone");
- }
- #[test]
- fn test_behind_milestone() {
- assert_eq!(compute_progress(BILAL, MILESTONE_DAY), "Behind Milestone");
- }
- }
mod preloaded; use preloaded::*; fn total_age_younger_than(people: &[Person], age: u32) -> u32 { people_younger_than(people, age) .map(|person| person.age) .sum() } fn hair_colors_younger_than(people: &[Person], age: u32) -> Vec<HairColor> { people_younger_than(people, age) .map(|person| person.hair_color) .collect() } fn people_younger_than(people: &[Person], age: u32) -> impl Iterator<Item = &Person> { people.iter().filter(move |person| person.age < age) }
// this code should fail the tests// const totalAgeYoungerThan = (people, age) => {// let totalAge = 0;// for (let i = 0; i < people.length; i++) {// if (people[i].age < age) totalAge += people[i].age;// }// return totalAge;// }- mod preloaded;
// this code should fail the tests// const totalAgeYoungerThan = (people, age) => {// let totalAge = 0;// for (let person of people) {// if (person < age) totalAge += person.age;// }// return totalAge;// }- use preloaded::*;
// this code should fail the tests// const totalAgeYoungerThan = (people, age) => {// if (people.length === 0) return 0;// const [first, ...rest] = people;// return (first.age < age ? first.age : 0) + totalAgeYoungerThan(rest, age);// }// this code should theoretically pass the tests// it includes the word `for` but not in a for loop// const totalAgeYoungerThan = (people, age) => {// return people// .filter(person => person.age < age)// .reduce((formula, person) => formula + person.age, 0)// }- fn total_age_younger_than(people: &[Person], age: u32) -> u32 {
- people_younger_than(people, age)
- .map(|person| person.age)
- .sum()
- }
const totalAgeYoungerThan = (people, age) => {return people.filter(person => person.age < age).reduce((sum, person) => sum + person.age, 0)- fn hair_colors_younger_than(people: &[Person], age: u32) -> Vec<HairColor> {
- people_younger_than(people, age)
- .map(|person| person.hair_color)
- .collect()
- }
const hairColorsYoungerThan = (people, age) => {return people.filter(person => person.age < age).map(person => person.hairColor)- fn people_younger_than(people: &[Person], age: u32) -> impl Iterator<Item = &Person> {
- people.iter().filter(move |person| person.age < age)
- }
#[cfg(test)] mod tests { use super::*; const PEOPLE: [Person; 4] = [ Person { age: 10, hair_color: HairColor::Brown }, Person { age: 30, hair_color: HairColor::Red }, Person { age: 20, hair_color: HairColor::Brown }, Person { age: 40, hair_color: HairColor::Black } ]; #[test] fn test_total_age_younger_than() { assert_eq!(total_age_younger_than(&PEOPLE, 30), 30); assert_eq!(total_age_younger_than(&[], 30), 0); assert_eq!(total_age_younger_than(&PEOPLE, 0), 0); assert_eq!(total_age_younger_than(&PEOPLE, 0), 0); } #[test] fn test_hair_colors_younger_than() { assert_eq!(hair_colors_younger_than(&PEOPLE, 30), [HairColor::Brown, HairColor::Brown]); assert_eq!(hair_colors_younger_than(&[], 30), []); assert_eq!(hair_colors_younger_than(&PEOPLE, 0), []); } }
const chai = require('chai');const expect = chai.expect;chai.config.truncateThreshold = 0;const people = [{age: 10, hairColor: "brown"},{age: 30, hairColor: "red"},{age: 20, hairColor: "brown"},{age: 40, hairColor: "black"},];people.forEach(person => Object.freeze(person));Object.freeze(people);describe("challenge", () => {let originalMap, originalFilter, originalReduce;let mapCallCount = 0, filterCallCount = 0, reduceCallCount = 0;beforeEach(function() {originalMap = Array.prototype.map;originalFilter = Array.prototype.filter;originalReduce = Array.prototype.reduce;- #[cfg(test)]
- mod tests {
- use super::*;
Array.prototype.map = function() {mapCallCount++;return originalMap.apply(this, arguments);}- const PEOPLE: [Person; 4] = [
- Person { age: 10, hair_color: HairColor::Brown },
- Person { age: 30, hair_color: HairColor::Red },
- Person { age: 20, hair_color: HairColor::Brown },
- Person { age: 40, hair_color: HairColor::Black }
- ];
Array.prototype.filter = function() {filterCallCount++;return originalFilter.apply(this, arguments);- #[test]
- fn test_total_age_younger_than() {
- assert_eq!(total_age_younger_than(&PEOPLE, 30), 30);
- assert_eq!(total_age_younger_than(&[], 30), 0);
- assert_eq!(total_age_younger_than(&PEOPLE, 0), 0);
- assert_eq!(total_age_younger_than(&PEOPLE, 0), 0);
- }
Array.prototype.reduce = function() {reduceCallCount++;return originalReduce.apply(this, arguments);}});afterEach(function() {Array.prototype.map = originalMap;Array.prototype.filter = originalFilter;Array.prototype.reduce = originalReduce;});describe("totalAgeYoungerThan",() => {it("returns the correct answer", () => {expect(totalAgeYoungerThan(people, 30)).to.deep.eq(30);})it("returns 0 when there are no people", () => {expect(totalAgeYoungerThan([], 30)).to.deep.eq(0);})it("returns 0 when there are no people who meet the criteria", () => {expect(totalAgeYoungerThan(people, -1)).to.deep.eq(0);})it("does not use a for loop", () => {// TODO: toString can be overwritten - find out how to read solution.txt?expect(totalAgeYoungerThan.toString()).to.not.include("for");})it("uses reduce", () => {totalAgeYoungerThan(people, 30);expect(reduceCallCount).to.be.at.least(1);})});describe("hairColorsYoungerThan",() => {it("returns the correct answer", () => {expect(hairColorsYoungerThan(people, 30)).to.deep.eq(["brown", "brown"]);})it("returns an empty array when there are no people", () => {expect(hairColorsYoungerThan([], 30)).to.deep.eq([]);})it("returns an empty array when there are no people who meet the criteria", () => {expect(hairColorsYoungerThan(people, -1)).to.deep.eq([]);})it("does not use a for loop", () => {expect(hairColorsYoungerThan.toString()).to.not.include("for");})it("does use .map and .filter", () => {totalAgeYoungerThan(people, 30);expect(mapCallCount).to.be.at.least(1);expect(filterCallCount).to.be.at.least(1);})});describe("random tests", () => {const dataSets = [];for(let i = 0; i < 10; i++) {const hairColors = ["brown", "black", "blue", "red", "yellow", "orange"];const people = [];const numberOfPeople = Math.random() * 20 + 5;for(let j = 0; j < numberOfPeople; j++) {people.push({age: j, hairColor: hairColors[Math.floor(Math.random() * hairColors.length)]});}people.forEach(person => Object.freeze(person));Object.freeze(people);dataSets.push(people);- #[test]
- fn test_hair_colors_younger_than() {
- assert_eq!(hair_colors_younger_than(&PEOPLE, 30), [HairColor::Brown, HairColor::Brown]);
- assert_eq!(hair_colors_younger_than(&[], 30), []);
- assert_eq!(hair_colors_younger_than(&PEOPLE, 0), []);
- }
describe("totalAgeYoungerThan", () => {const totalAgeYoungerThanSolution = (people, age) => {return people.filter(person => person.age < age).reduce((sum, person) => sum + person.age, 0)}dataSets.forEach((people, i) => {const randomAges = [people[Math.floor(Math.random() * people.length)].age,people[Math.floor(Math.random() * people.length)].age,people[Math.floor(Math.random() * people.length)].age,];randomAges.forEach(randomAge => {it(`passes for random data #${i} and age ${randomAge}`, () => {expect(totalAgeYoungerThan(people, randomAge)).to.deep.eq(totalAgeYoungerThanSolution(people, randomAge));});});});});describe("hairColorsYoungerThan", () => {const hairColorsYoungerThanSolution = (people, age) => {return people.filter(person => person.age < age).map(person => person.hairColor)}dataSets.forEach((people, i) => {const randomAges = [people[Math.floor(Math.random() * people.length)].age,people[Math.floor(Math.random() * people.length)].age,people[Math.floor(Math.random() * people.length)].age,];randomAges.forEach(randomAge => {it(`passes for random data #${i} and age ${randomAge}`, () => {expect(hairColorsYoungerThan(people, randomAge)).to.deep.eq(hairColorsYoungerThanSolution(people, randomAge));});});});});});})- }
fn amongus(s: &str) -> Vec<usize> { (0..s.len().saturating_sub(2)) .filter(|&i| s[i..i+3].to_ascii_lowercase() == "sus") .collect() }
def amongus(sus):i=0acc=[]while i<len(sus)-2:if sus[i:i+3].lower()=="sus":acc.append(i)i+=1return acc- fn amongus(s: &str) -> Vec<usize> {
- (0..s.len().saturating_sub(2))
- .filter(|&i| s[i..i+3].to_ascii_lowercase() == "sus")
- .collect()
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test_basic() { assert_eq!(amongus("sus"), [0]); assert_eq!(amongus("sussy baka"), [0]); assert_eq!(amongus("red is sus!"), [7]); } #[test] fn test_complex() { assert_eq!(amongus(""), []); assert_eq!(amongus("su"), []); assert_eq!(amongus("ssu"), []); assert_eq!(amongus("sususus"), [0, 2, 4]); assert_eq!(amongus("sussus sussy"), [0, 3, 7]); } }
import codewars_test as test# TODO Write testsimport 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(1 + 1, 2)test.assert_equals(amongus("sus"), [0])test.assert_equals(amongus("sussy baka"), [0])test.assert_equals(amongus("red is sus!"), [7])- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test_basic() {
- assert_eq!(amongus("sus"), [0]);
- assert_eq!(amongus("sussy baka"), [0]);
- assert_eq!(amongus("red is sus!"), [7]);
- }
- #[test]
- fn test_complex() {
- assert_eq!(amongus(""), []);
- assert_eq!(amongus("su"), []);
- assert_eq!(amongus("ssu"), []);
- assert_eq!(amongus("sususus"), [0, 2, 4]);
- assert_eq!(amongus("sussus sussy"), [0, 3, 7]);
- }
- }
fn to_upper_first(xs: &str) -> String { if xs.is_empty() { String::new() } else { xs[..1].to_uppercase() + &xs[1..] } }
module ToupperFirst whereimport Data.ChartoUpperFirst "" = ""toUpperFirst xs = [toUpper (x) | x <- xs, x == head (xs)] ++ tail (xs)- fn to_upper_first(xs: &str) -> String {
- if xs.is_empty() {
- String::new()
- } else {
- xs[..1].to_uppercase() + &xs[1..]
- }
- }
#[test] fn test() { assert_eq!(to_upper_first(""), ""); assert_eq!(to_upper_first("finn the human"), "Finn the human"); assert_eq!(to_upper_first("alice"), "Alice"); }
module ExampleSpec where-- Tests can be written using Hspec http://hspec.github.io/-- Replace this with your own tests.- #[test]
- fn test() {
- assert_eq!(to_upper_first(""), "");
- assert_eq!(to_upper_first("finn the human"), "Finn the human");
- assert_eq!(to_upper_first("alice"), "Alice");
- }
import Test.Hspecimport ToUpperFirst- --- `spec` of type `Spec` must exist
spec :: Specspec = dodescribe "toUpperFirst" $ doit "capitalize forst character of a string" $ dotoUpperFirst "" `shouldBe` ""toUpperFirst "finn the human" `shouldBe` "Finn the human"toUpperFirst "alice" `shouldBe` "Alice"- --- the following line is optional for 8.2
main = hspec spec
use std::iter::Sum; fn sum<T: Copy + Sum>(arr: &[T]) -> T { arr.iter().copied().sum() }
module Sum (Sum.sum) where- use std::iter::Sum;
import Prelude hiding (sum)sum :: [Word] -> Wordsum = foldr1 (+)- fn sum<T: Copy + Sum>(arr: &[T]) -> T {
- arr.iter().copied().sum()
- }
#[test] fn test() { assert_eq!(sum(&[1, 2, 3]), 6) }
module SumSpec (spec) whereimport Prelude hiding (sum)import qualified Prelude as Pre (sum)import Sum (sum)import Test.Hspecspec :: Specspec = doit "tests" $ doSum.sum [1] `shouldBe` Pre.sum [1]- #[test]
- fn test() {
- assert_eq!(sum(&[1, 2, 3]), 6)
- }
fn fibonacci(n: usize) -> u128 { let (mut n1, mut n2) = (1, 1); for _ in 2..n { (n1, n2) = (n2, n1 + n2); } n2 }
import java.util.HashMap;import java.util.Map;public class Fibonacci {private static Map<Integer, Long> memoizationMap = new HashMap<>();public static long calcFibo(int n) {if (n <= 1) {return n;}if (memoizationMap.containsKey(n)) {return memoizationMap.get(n);}long fiboValue = calcFibo(n - 1) + calcFibo(n - 2);memoizationMap.put(n, fiboValue);return fiboValue;}- fn fibonacci(n: usize) -> u128 {
- let (mut n1, mut n2) = (1, 1);
- for _ in 2..n {
- (n1, n2) = (n2, n1 + n2);
- }
- n2
- }
#[cfg(test)] mod tests { use super::*; use std::time::Instant; fn test_fibonacci(input: usize, expected: u128) { let start = Instant::now(); let output = fibonacci(input); let micros = start.elapsed().as_nanos() as f64 / 1_000.0; assert_eq!(output, expected); println!("Fibonacci({input}) = {output} and takes {micros:.3}µs"); } #[test] fn test() { test_fibonacci(1, 1); // <0.1µs test_fibonacci(2, 1); // <0.1µs test_fibonacci(4, 3); // <0.1µs test_fibonacci(8, 21); // <0.1µs test_fibonacci(16, 987); // <0.1µs test_fibonacci(32, 2178309); // ~0.1µs test_fibonacci(64, 10610209857723); // ~0.2µs test_fibonacci(128, 251728825683549488150424261); // ~0.3µs test_fibonacci(186, 332825110087067562321196029789634457848); // ~0.5µs } }
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;// TODO: Replace examples and use TDD by writing your own testsclass SolutionTest {@Testvoid testSomething() {int n = 6;long start = System.currentTimeMillis();Long fibo = Fibonacci.calcFibo(n);long end = System.currentTimeMillis();- #[cfg(test)]
- mod tests {
- use super::*;
- use std::time::Instant;
- fn test_fibonacci(input: usize, expected: u128) {
- let start = Instant::now();
- let output = fibonacci(input);
- let micros = start.elapsed().as_nanos() as f64 / 1_000.0;
- assert_eq!(output, expected);
- println!("Fibonacci({input}) = {output} and takes {micros:.3}µs");
- }
- #[test]
- fn test() {
- test_fibonacci(1, 1); // <0.1µs
- test_fibonacci(2, 1); // <0.1µs
- test_fibonacci(4, 3); // <0.1µs
- test_fibonacci(8, 21); // <0.1µs
- test_fibonacci(16, 987); // <0.1µs
- test_fibonacci(32, 2178309); // ~0.1µs
- test_fibonacci(64, 10610209857723); // ~0.2µs
- test_fibonacci(128, 251728825683549488150424261); // ~0.3µs
- test_fibonacci(186, 332825110087067562321196029789634457848); // ~0.5µs
System.out.println("Fibonacci(" + n + ") = "+ fibo + " and takes " +(end - start) + "ms");- }
- }