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);
- }
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]);
- }
Manually checked lock. Contains unsafe and is most likely to be unsound since I'm still learning concurrency.
use std::{thread, sync::atomic::{AtomicBool, Ordering::*}}; fn count() -> u32 { let lock = AtomicBool::new(false); let count = 0; thread::scope(|s| { for _ in 0..10 { s.spawn(|| { for _ in 0..100 { while lock.compare_exchange(false, true, Acquire, Relaxed).is_err() {} let count_ptr = &count as *const u32 as *mut u32; unsafe { *count_ptr += 1; } lock.store(false, Release); } }); } }); count }
use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};- use std::{thread, sync::atomic::{AtomicBool, Ordering::*}};
- fn count() -> u32 {
let count = AtomicU32::new(0);- let lock = AtomicBool::new(false);
- let count = 0;
- thread::scope(|s| {
- for _ in 0..10 {
- s.spawn(|| {
- for _ in 0..100 {
let current = count.load(Relaxed);count.store(current + 1, Relaxed);- while lock.compare_exchange(false, true, Acquire, Relaxed).is_err() {}
- let count_ptr = &count as *const u32 as *mut u32;
- unsafe { *count_ptr += 1; }
- lock.store(false, Release);
- }
- });
- }
- });
count.into_inner()- count
- }
use std::time::Instant; #[test] fn test_count() { let start = Instant::now(); for _ in 0..10_000 { assert_eq!(count(), 1_000); } let elapsed = start.elapsed(); println!("{}ms", elapsed.as_millis()); }
- use std::time::Instant;
- #[test]
- fn test_count() {
- let start = Instant::now();
- for _ in 0..10_000 {
- assert_eq!(count(), 1_000);
- }
- let elapsed = start.elapsed();
- println!("{}ms", elapsed.as_millis());
- }
Seems like it should be worse than an atomic since there's additional overhead, but isn't notably slower.
use std::{thread, sync::Mutex}; fn count() -> u32 { let count = Mutex::new(0); thread::scope(|s| { for _ in 0..10 { s.spawn(|| { for _ in 0..100 { *count.lock().unwrap() += 1; } }); } }); count.into_inner().unwrap() }
use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};- use std::{thread, sync::Mutex};
- fn count() -> u32 {
let count = AtomicU32::new(0);- let count = Mutex::new(0);
- thread::scope(|s| {
- for _ in 0..10 {
- s.spawn(|| {
- for _ in 0..100 {
let current = count.load(Relaxed);count.store(current + 1, Relaxed);- *count.lock().unwrap() += 1;
- }
- });
- }
- });
count.into_inner()- count.into_inner().unwrap()
- }
use std::time::Instant; #[test] fn test_count() { let start = Instant::now(); for _ in 0..10_000 { assert_eq!(count(), 1_000); } let elapsed = start.elapsed(); println!("{}ms", elapsed.as_millis()); }
- use std::time::Instant;
- #[test]
- fn test_count() {
- let start = Instant::now();
- for _ in 0..10_000 {
- assert_eq!(count(), 1_000);
- }
- let elapsed = start.elapsed();
- println!("{}ms", elapsed.as_millis());
- }
Feels kinda like cheating. Surprisingly not faster. Maybe the thread spawning dominates the runtime anyways?
use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}}; fn count() -> u32 { let global_count = AtomicU32::new(0); thread::scope(|s| { for _ in 0..10 { s.spawn(|| { let mut local_count = 0; for _ in 0..100 { local_count += 1; } global_count.fetch_add(local_count, Relaxed); }); } }); global_count.into_inner() }
- use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
- fn count() -> u32 {
let count = AtomicU32::new(0);- let global_count = AtomicU32::new(0);
- thread::scope(|s| {
- for _ in 0..10 {
- s.spawn(|| {
- let mut local_count = 0;
- for _ in 0..100 {
let current = count.load(Relaxed);count.store(current + 1, Relaxed);- local_count += 1;
- }
- global_count.fetch_add(local_count, Relaxed);
- });
- }
- });
count.into_inner()- global_count.into_inner()
- }
use std::time::Instant; #[test] fn test_count() { let start = Instant::now(); for _ in 0..10_000 { assert_eq!(count(), 1_000); } let elapsed = start.elapsed(); println!("{}ms", elapsed.as_millis()); }
- use std::time::Instant;
- #[test]
- fn test_count() {
- let start = Instant::now();
- for _ in 0..10_000 {
- assert_eq!(count(), 1_000);
- }
- let elapsed = start.elapsed();
- println!("{}ms", elapsed.as_millis());
- }
fn encode(string: &str) -> String { string.chars().map(|ch| { match ch { 'a' => '1', 'e' => '2', 'i' => '3', 'o' => '4', 'u' => '5', _ => ch } }).collect() } fn decode(string: &str) -> String { string.chars().map(|ch| { match ch { '1' => 'a', '2' => 'e', '3' => 'i', '4' => 'o', '5' => 'u', _ => ch } }).collect() }
function encode(string){return [...string].map(el => {return ( "aeiou".includes(el))? "aeiou".indexOf(el) + 1 : el}).join('')}- fn encode(string: &str) -> String {
- string.chars().map(|ch| {
- match ch {
- 'a' => '1',
- 'e' => '2',
- 'i' => '3',
- 'o' => '4',
- 'u' => '5',
- _ => ch
- }
- }).collect()
- }
function decode(string){return [...string].map(el => {return ("12345".includes(el)) ? {'1':"a","2":"e","3":"i","4":"o","5":"u"}[el] : el}).join('')}- fn decode(string: &str) -> String {
- string.chars().map(|ch| {
- match ch {
- '1' => 'a',
- '2' => 'e',
- '3' => 'i',
- '4' => 'o',
- '5' => 'u',
- _ => ch
- }
- }).collect()
- }
#[cfg(test)] mod tests { use super::{encode, decode}; #[test] fn encode_vowels() { assert_eq!(encode("hello"), "h2ll4"); assert_eq!(encode("codewars"), "c4d2w1rs"); assert_eq!(encode("a"), "1"); assert_eq!(encode("e"), "2"); assert_eq!(encode("i"), "3"); assert_eq!(encode("o"), "4"); assert_eq!(encode("u"), "5"); } #[test] fn ignore_consonants() { assert_eq!(encode("bcdfghjklmnpqrstvwxyz"), "bcdfghjklmnpqrstvwxyz"); assert_eq!(decode("bcdfghjklmnpqrstvwxyz"), "bcdfghjklmnpqrstvwxyz"); } #[test] fn decode_digits() { assert_eq!(decode("h2ll4"), "hello"); assert_eq!(decode("c4d2w1rs"), "codewars"); assert_eq!(decode("1"), "a"); assert_eq!(decode("2"), "e"); assert_eq!(decode("3"), "i"); assert_eq!(decode("4"), "o"); assert_eq!(decode("5"), "u"); } #[test] fn ignore_other_digits() { assert_eq!(decode("67890"), "67890"); } #[test] fn empty_string() { assert_eq!(encode(""), ""); assert_eq!(decode(""), ""); } #[test] fn mixed_letters() { assert_eq!(encode("hello world"), "h2ll4 w4rld"); assert_eq!(decode("h2ll4 w4rld"), "hello world"); } #[test] fn ignore_already_transformed() { assert_eq!(encode("h2ll4"), "h2ll4"); assert_eq!(decode("codewarsaei"), "codewarsaei"); } }
// 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");- #[cfg(test)]
- mod tests {
- use super::{encode, decode};
describe("Solution", function() {it("should test for something", function() {// Test.assertEquals(1 + 1, 2);// assert.strictEqual(1 + 1, 2);});});- #[test]
- fn encode_vowels() {
- assert_eq!(encode("hello"), "h2ll4");
- assert_eq!(encode("codewars"), "c4d2w1rs");
- assert_eq!(encode("a"), "1");
- assert_eq!(encode("e"), "2");
- assert_eq!(encode("i"), "3");
- assert_eq!(encode("o"), "4");
- assert_eq!(encode("u"), "5");
- }
- #[test]
- fn ignore_consonants() {
- assert_eq!(encode("bcdfghjklmnpqrstvwxyz"), "bcdfghjklmnpqrstvwxyz");
- assert_eq!(decode("bcdfghjklmnpqrstvwxyz"), "bcdfghjklmnpqrstvwxyz");
- }
- #[test]
- fn decode_digits() {
- assert_eq!(decode("h2ll4"), "hello");
- assert_eq!(decode("c4d2w1rs"), "codewars");
- assert_eq!(decode("1"), "a");
- assert_eq!(decode("2"), "e");
- assert_eq!(decode("3"), "i");
- assert_eq!(decode("4"), "o");
- assert_eq!(decode("5"), "u");
- }
- #[test]
- fn ignore_other_digits() {
- assert_eq!(decode("67890"), "67890");
- }
- #[test]
- fn empty_string() {
- assert_eq!(encode(""), "");
- assert_eq!(decode(""), "");
- }
- #[test]
- fn mixed_letters() {
- assert_eq!(encode("hello world"), "h2ll4 w4rld");
- assert_eq!(decode("h2ll4 w4rld"), "hello world");
- }
- #[test]
- fn ignore_already_transformed() {
- assert_eq!(encode("h2ll4"), "h2ll4");
- assert_eq!(decode("codewarsaei"), "codewarsaei");
- }
- }
The simple fix. Runtime around 3 seconds for 10000 calls.
use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}}; fn count() -> u32 { let count = AtomicU32::new(0); thread::scope(|s| { for _ in 0..10 { s.spawn(|| { for _ in 0..100 { count.fetch_add(1, Relaxed); } }); } }); count.into_inner() }
- use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
- fn count() -> u32 {
- let count = AtomicU32::new(0);
- thread::scope(|s| {
- for _ in 0..10 {
- s.spawn(|| {
- for _ in 0..100 {
let current = count.load(Relaxed);count.store(current + 1, Relaxed);- count.fetch_add(1, Relaxed);
- }
- });
- }
- });
- count.into_inner()
- }
use std::time::Instant; #[test] fn test_count() { let start = Instant::now(); for _ in 0..10_000 { assert_eq!(count(), 1_000); } let elapsed = start.elapsed(); println!("{}ms", elapsed.as_millis()); }
- use std::time::Instant;
- #[test]
- fn test_count() {
- let start = Instant::now();
- for _ in 0..10_000 {
- assert_eq!(count(), 1_000);
- }
- let elapsed = start.elapsed();
- println!("{}ms", elapsed.as_millis());
- }
Try fixing the race condition while keeping the program multithreaded.
use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
fn count() -> u32 {
let count = AtomicU32::new(0);
thread::scope(|s| {
for _ in 0..10 {
s.spawn(|| {
for _ in 0..100 {
let current = count.load(Relaxed);
count.store(current + 1, Relaxed);
}
});
}
});
count.into_inner()
}
#[test]
fn test_count() {
for _ in 0..10_000 {
assert_eq!(count(), 1_000);
}
}
use std::collections::BTreeSet; fn is_unique(string: &str) -> bool { string.chars().collect::<BTreeSet<_>>().len() == string.len() }
- use std::collections::BTreeSet;
- fn is_unique(string: &str) -> bool {
let mut known = BTreeSet::new();for character in string.chars() {if known.contains(&character) {return false;}known.insert(character);}true- string.chars().collect::<BTreeSet<_>>().len() == string.len()
- }
fn make_move(init: (i32, i32), sequence: &str) -> (i32, i32) { sequence.chars().fold(init, |(x, y), c| ( x + match c { 'r' => 1, 'l' => -1, _ => 0 }, y + match c { 't' => 1, 'b' => -1, _ => 0 }, )) }
fn make_move(init: [i32; 2], sequence: &str) -> [i32; 2] {sequence.chars().fold(init, |[x, y], c| [x + (c == 'r') as i32 - (c == 'l') as i32,y + (c == 't') as i32 - (c == 'b') as i32,])- fn make_move(init: (i32, i32), sequence: &str) -> (i32, i32) {
- sequence.chars().fold(init, |(x, y), c| (
- x + match c { 'r' => 1, 'l' => -1, _ => 0 },
- y + match c { 't' => 1, 'b' => -1, _ => 0 },
- ))
- }
#[test] fn test() { assert_eq!(make_move((0, 0), "ttrbrrbllrt"), (2, 1)); assert_eq!(make_move((4, 1), "bllbrt"), (3, 0)); assert_eq!(make_move((-2, 4), "trlbb"), (-2, 3)); assert_eq!(make_move((5, 5), "trlbrb"), (6, 4)); }
- #[test]
- fn test() {
assert_eq!(make_move([0, 0], "ttrbrrbllrt"), [2, 1]);assert_eq!(make_move([4,1], "bllbrt"), [3,0]);assert_eq!(make_move([-2, 4], "trlbb"), [-2,3]);assert_eq!(make_move([5,5], "trlbrb"), [6, 4]);- assert_eq!(make_move((0, 0), "ttrbrrbllrt"), (2, 1));
- assert_eq!(make_move((4, 1), "bllbrt"), (3, 0));
- assert_eq!(make_move((-2, 4), "trlbb"), (-2, 3));
- assert_eq!(make_move((5, 5), "trlbrb"), (6, 4));
- }
fn make_move(init: [i32; 2], sequence: &str) -> [i32; 2] { sequence.chars().fold(init, |[x, y], c| [ x + (c == 'r') as i32 - (c == 'l') as i32, y + (c == 't') as i32 - (c == 'b') as i32, ]) }
fn make_move(mut init: [i32; 2], sequence: &str) -> [i32; 2] {for c in sequence.chars() {match c {'t' => init[1] += 1,'b' => init[1] -= 1,'r' => init[0] += 1,'l' => init[0] -= 1,_ => {}}}init- fn make_move(init: [i32; 2], sequence: &str) -> [i32; 2] {
- sequence.chars().fold(init, |[x, y], c| [
- x + (c == 'r') as i32 - (c == 'l') as i32,
- y + (c == 't') as i32 - (c == 'b') as i32,
- ])
- }
fn make_move(mut init: [i32; 2], sequence: &str) -> [i32; 2] { for c in sequence.chars() { match c { 't' => init[1] += 1, 'b' => init[1] -= 1, 'r' => init[0] += 1, 'l' => init[0] -= 1, _ => {} } } init }
function makeMove(init, sequence) {[...sequence].forEach(move => {switch (move) {case 't':init[1]++;break;case 'b':init[1]--;break;case 'r':init[0]++;break;case 'l':init[0]--;break;default:break;- fn make_move(mut init: [i32; 2], sequence: &str) -> [i32; 2] {
- for c in sequence.chars() {
- match c {
- 't' => init[1] += 1,
- 'b' => init[1] -= 1,
- 'r' => init[0] += 1,
- 'l' => init[0] -= 1,
- _ => {}
- }
- }
});return init;- init
- }
#[test] fn test() { assert_eq!(make_move([0, 0], "ttrbrrbllrt"), [2, 1]); assert_eq!(make_move([4,1], "bllbrt"), [3,0]); assert_eq!(make_move([-2, 4], "trlbb"), [-2,3]); assert_eq!(make_move([5,5], "trlbrb"), [6, 4]); }
// 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 deprecateddescribe("Solution", function() {it("should test for something", function() {assert.deepEqual(makeMove([0, 0], "ttrbrrbllrt"), [2, 1]);assert.deepEqual(makeMove([4,1], "bllbrt"), [3,0]);assert.deepEqual(makeMove([-2, 4], "trlbb"), [-2,3]);assert.deepEqual(makeMove([5,5], "trlbrb"), [6, 4]);});});- #[test]
- fn test() {
- assert_eq!(make_move([0, 0], "ttrbrrbllrt"), [2, 1]);
- assert_eq!(make_move([4,1], "bllbrt"), [3,0]);
- assert_eq!(make_move([-2, 4], "trlbb"), [-2,3]);
- assert_eq!(make_move([5,5], "trlbrb"), [6, 4]);
- }