Datasets:

Modalities:
Text
Formats:
json
Languages:
code
Size:
< 1K
Libraries:
Datasets
pandas
License:
task_id
stringlengths
6
8
prompt
stringlengths
31
1.16k
declaration
stringlengths
214
270
cannonical_solution
stringlengths
17
2.16k
test
stringlengths
176
2.54k
Rust/0
/* Check if in given list of numbers, are any two numbers closer to each other than given threshold. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn has_close_elements(numbers:Vec<f32>, threshold: f32) -> bool{
for i in 0..numbers.len(){ for j in 1..numbers.len(){ if i != j { let distance:f32 = numbers[i] - numbers[j]; if distance.abs() < threshold{ return true; } } } } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_has_close_elements() { assert_eq!(has_close_elements(vec![11.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3), true); assert_eq!(has_close_elements(vec![1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05), false); assert_eq!(has_close_elements(vec![1.0, 2.0, 5.9, 4.0, 5.0], 0.95), true); assert_eq!(has_close_elements(vec![1.0, 2.0, 5.9, 4.0, 5.0], 0.8), false); assert_eq!(has_close_elements(vec![1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1), true); assert_eq!(has_close_elements(vec![1.1, 2.2, 3.1, 4.1, 5.1], 1.0), true); assert_eq!(has_close_elements(vec![1.1, 2.2, 3.1, 4.1, 5.1], 0.5), false); } }
Rust/1
/* Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn separate_paren_groups(paren_string: String) -> Vec<String>{
let mut result:Vec<String> = vec![]; let mut current_string:String = String::new(); let mut current_depth:u32 = 0; for c in paren_string.chars(){ if c == '('{ current_depth += 1; current_string.push(c); } else if c == ')' { current_depth -= 1; current_string.push(c); if current_depth == 0{ result.push(current_string.clone()); current_string.clear() } } } return result; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_separate_paren_groups() { assert_eq!( separate_paren_groups(String::from("(()()) ((())) () ((())()())")), vec!["(()())", "((()))", "()", "((())()())"] ); assert_eq!( separate_paren_groups(String::from("() (()) ((())) (((())))")), vec!["()", "(())", "((()))", "(((())))"] ); assert_eq!( separate_paren_groups(String::from("(()(())((())))")), vec!["(()(())((())))"] ); assert_eq!( separate_paren_groups(String::from("( ) (( )) (( )( ))")), vec!["()", "(())", "(()())"] ); } }
Rust/2
/* Given a positive floating point number, it can be decomposed into and integer part (largest integer smaller than given number) and decimals (leftover part always smaller than 1). Return the decimal part of the number. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn truncate_number(number: &f32) -> f32{
return number % 1.0; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_truncate_number() { assert_eq!(truncate_number(&3.5), 0.5); let t1: f32 = 1.33 - 0.33; assert!(truncate_number(&t1) < 0.000001); let t2: f32 = 123.456 - 0.456; assert!(truncate_number(&t2) < 0.000001); } }
Rust/3
/* You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn below_zero(operations:Vec<i32>) -> bool{
let mut balance:i32 = 0; for op in operations { balance = balance + op; if balance < 0 { return true; } } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_below_zero() { assert_eq!(below_zero(vec![]), false); assert_eq!(below_zero(vec![1, 2, -3, 1, 2, -3]), false); assert_eq!(below_zero(vec![1, 2, -4, 5, 6]), true); assert_eq!(below_zero(vec![1, -1, 2, -2, 5, -5, 4, -4]), false); assert_eq!(below_zero(vec![1, -1, 2, -2, 5, -5, 4, -5]), true); assert_eq!(below_zero(vec![1, -2, 2, -2, 5, -5, 4, -4]), true); } }
Rust/4
/* For a given list of input numbers, calculate Mean Absolute Deviation around the mean of this dataset. Mean Absolute Deviation is the average absolute difference between each element and a centerpoint (mean in this case): MAD = average | x - x_mean | *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn mean_absolute_deviation(numbers:Vec<f32>) -> f32{
let mean:f32 = numbers.iter().fold(0.0,|acc:f32, x:&f32| acc + x) / numbers.len() as f32; return numbers.iter().map(|x:&f32| (x - mean).abs()).sum::<f32>() / numbers.len() as f32; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_mean_absolute_deviation() { assert!(mean_absolute_deviation(vec![1.0, 2.0, 3.0]) - 2.0 / 3.0 < 0.000001); assert!(mean_absolute_deviation(vec![1.0, 2.0, 3.0, 4.0]) - 1.0 < 0.000001); assert!(mean_absolute_deviation(vec![1.0, 2.0, 3.0, 4.0, 5.0]) - 6.0 / 5.0 < 0.000001); } }
Rust/5
/* Insert a number 'delimeter' between every two consecutive elements of input list `numbers' *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn intersperse(numbers:Vec<u32>, delimeter: u32) -> Vec<u32>{
let mut res:Vec<u32> = vec![]; numbers.iter().for_each(|item:&u32| {res.push(*item); res.push(delimeter);}); res.pop(); return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_intersperse() { assert!(intersperse(vec![], 7) == vec![]); assert!(intersperse(vec![5, 6, 3, 2], 8) == vec![5, 8, 6, 8, 3, 8, 2]); assert!(intersperse(vec![2, 2, 2], 2) == vec![2, 2, 2, 2, 2]); } }
Rust/6
/* Input to this function is a string represented multiple groups for nested parentheses separated by spaces. For each of the group, output the deepest level of nesting of parentheses. E.g. (()()) has maximum two levels of nesting while ((())) has three. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn parse_nested_parens(paren_string:String) -> Vec<i32>{
let mut result:Vec<i32> = vec![]; let mut depth:i32 = 0; let mut max_depth:i32 = 0; for splits in paren_string.split(' '){ for c in splits.chars(){ if c == '('{ depth = depth + 1; max_depth = max(depth, max_depth); } else{ depth = depth - 1; } } if depth == 0 { result.push(max_depth); max_depth = 0; } } return result; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_parse_nested_parens() { assert!( parse_nested_parens(String::from("(()()) ((())) () ((())()())")) == vec![2, 3, 1, 3] ); assert!(parse_nested_parens(String::from("() (()) ((())) (((())))")) == vec![1, 2, 3, 4]); assert!(parse_nested_parens(String::from("(()(())((())))")) == vec![4]); } }
Rust/7
/* Filter an input list of strings only for ones that contain given substring *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn filter_by_substring(strings: Vec<String>, substring:String) -> Vec<String>{
return strings.iter().filter(|x:&&String| x.contains(&substring)).map(String::from).collect(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_filter_by_substring() { let v_empty: Vec<String> = vec![]; assert!(filter_by_substring(vec![], String::from("john")) == v_empty); assert!( filter_by_substring( vec![ "xxx".to_string(), "asd".to_string(), "xxy".to_string(), "john doe".to_string(), "xxxAAA".to_string(), "xxx".to_string() ], String::from("xxx") ) == vec!["xxx", "xxxAAA", "xxx"] ); assert!( filter_by_substring( vec![ "xxx".to_string(), "asd".to_string(), "aaaxxy".to_string(), "john doe".to_string(), "xxxAAA".to_string(), "xxx".to_string() ], String::from("xx") ) == vec!["xxx", "aaaxxy", "xxxAAA", "xxx"] ); assert!( filter_by_substring( vec![ "grunt".to_string(), "trumpet".to_string(), "prune".to_string(), "gruesome".to_string() ], String::from("run") ) == ["grunt", "prune"] ); } }
Rust/8
/* For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn sum_product(numbers:Vec<i32>) -> (i32,i32){
let sum = |xs: &Vec<i32>| xs.iter() .fold(0, |mut sum, &val| { sum += val; sum } ); let product = |xs: &Vec<i32>| xs.iter() .fold(1, |mut prod, &val| { prod *= val; prod } ); return (sum(&numbers),product(&numbers)); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_sum_product() { assert!(sum_product(vec![]) == (0, 1)); assert!(sum_product(vec![1, 1, 1]) == (3, 1)); assert!(sum_product(vec![100, 0]) == (100, 0)); assert!(sum_product(vec![3, 5, 7]) == (3 + 5 + 7, 3 * 5 * 7)); assert!(sum_product(vec![10]) == (10, 10)); } }
Rust/9
/* From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn rolling_max(numbers:Vec<i32>) -> Vec<i32>{
let mut running_max :Option<i32> = None; let mut result:Vec<i32> = vec![]; for n in numbers{ if running_max == None { running_max = Some(n); }else{ running_max = max(running_max, Some(n)); } result.push(running_max.unwrap()); } return result; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_rolling_max() { assert!(rolling_max(vec![]) == vec![]); assert!(rolling_max(vec![1, 2, 3, 4]) == vec![1, 2, 3, 4]); assert!(rolling_max(vec![4, 3, 2, 1]) == vec![4, 4, 4, 4]); assert!(rolling_max(vec![3, 2, 3, 100, 3]) == vec![3, 3, 3, 100, 100]); } }
Rust/10
/* Find the shortest palindrome that begins with a supplied string. Algorithm idea is simple: - Find the longest postfix of supplied string that is a palindrome. - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn is_palindrome_10(str: &str) -> bool {
let s: String = str.chars().rev().collect(); return s==str; } fn make_palindrome(str: &str) -> String { let mut i: usize = 0; for i in 0..str.len() { let rstr: &str = &str[i..]; if is_palindrome_10(rstr) { let nstr: &str = &str[0..i]; let n2str: String = nstr.chars().rev().collect(); return str.to_string()+&n2str; } } let n2str: String = str.chars().rev().collect(); return str.to_string()+&n2str; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_make_palindrome() { assert_eq!(make_palindrome(""), ""); assert_eq!(make_palindrome("x"), "x"); assert_eq!(make_palindrome("xyz"), "xyzyx"); assert_eq!(make_palindrome("xyx"), "xyx"); assert_eq!(make_palindrome("jerry"), "jerryrrej"); } }
Rust/11
/* Input are two strings a and b consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn string_xor(a:String, b:String) -> String{
fn string_xor(a:String, b:String) -> String{ let xor = |i:char, j:char| {if i == j{return "0".to_string()}else{return "1".to_string()}}; return a.chars().into_iter().zip(b.chars().into_iter()).map(|(i,j)| "".to_string() + &xor(i,j)).collect(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_string_xor() { assert!(string_xor("111000".to_string(), "101010".to_string()) == "010010"); assert!(string_xor("1".to_string(), "1".to_string()) == "0"); assert!(string_xor("0101".to_string(), "0000".to_string()) == "0101"); } }
Rust/12
/* Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list is empty. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn longest(strings:Vec<String>) -> Option<String>{
if strings.is_empty(){ return None; } let mut max:i32 = 0; let mut res:String = String::new(); for s in strings{ if s.len() as i32 > max { res = s; max = res.len() as i32; } } return Some(res); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_longest() { assert!(longest(vec![]) == None); assert!( longest(vec!["x".to_string(), "y".to_string(), "z".to_string()]) == Some("x".to_string()) ); assert!( longest(vec![ "x".to_string(), "yyy".to_string(), "zzzz".to_string(), "www".to_string(), "kkkk".to_string(), "abc".to_string() ]) == Some("zzzz".to_string()) ); } }
Rust/13
/* Return a greatest common divisor of two integers a and b *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn greatest_common_divisor(mut a:i32,mut b:i32) -> i32{
while b > 0 { (a, b) = (b, a % b); } return a; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_greatest_common_divisor() { assert!(greatest_common_divisor(3, 7) == 1); assert!(greatest_common_divisor(10, 15) == 5); assert!(greatest_common_divisor(49, 14) == 7); assert!(greatest_common_divisor(144, 60) == 12); } }
Rust/14
/* Return list of all prefixes from shortest to longest of the input string *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn all_prefixes(string: String) -> Vec<String>{
let mut res:Vec<String> = vec![]; let mut res_str:String = String::new(); for c in string.chars(){ res_str.push(c); res.push(res_str.clone()); } return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_all_prefixes() { let v_empty: Vec<String> = vec![]; assert!(all_prefixes(String::from("")) == v_empty); assert!( all_prefixes(String::from("asdfgh")) == vec!["a", "as", "asd", "asdf", "asdfg", "asdfgh"] ); assert!(all_prefixes(String::from("WWW")) == vec!["W", "WW", "WWW"]); } }
Rust/15
/* Return a string containing space-delimited numbers starting from 0 upto n inclusive. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn string_sequence(n:i32) -> String{
let mut res:String = String::new(); for number in 0..n + 1{ res = res + &number.to_string() + " "; } return res.trim_end().to_string(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_string_sequence() { assert!(string_sequence(0) == "0".to_string()); assert!(string_sequence(3) == "0 1 2 3".to_string()); assert!(string_sequence(10) == "0 1 2 3 4 5 6 7 8 9 10".to_string()); } }
Rust/16
/* Given a string, find out how many distinct characters (regardless of case) does it consist of *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn count_distinct_characters(str:String) -> i32{
let res:HashSet<char> = str.chars().into_iter().map(|x:char| x.to_ascii_lowercase()).collect(); return res.len() as i32; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_count_distinct_characters() { assert!(count_distinct_characters("".to_string()) == 0); assert!(count_distinct_characters("abcde".to_string()) == 5); assert!( count_distinct_characters( "abcde".to_string() + &"cade".to_string() + &"CADE".to_string() ) == 5 ); assert!(count_distinct_characters("aaaaAAAAaaaa".to_string()) == 1); assert!(count_distinct_characters("Jerry jERRY JeRRRY".to_string()) == 5); } }
Rust/17
/* Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return list of integers corresponding to how many beats does each not last. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn parse_music(music_string:String) -> Vec<i32>{
let map = |x:&str| {match x { "o" => 4, "o|" => 2, ".|" => 1, _ => 0 } }; return music_string.split(" ").map(|x:&str| map(&x.to_string())).filter(|x:&i32| x != &0).collect(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_parse_music() { assert!(parse_music(" ".to_string()) == []); assert!(parse_music("o o o o".to_string()) == vec![4, 4, 4, 4]); assert!(parse_music(".| .| .| .|".to_string()) == vec![1, 1, 1, 1]); assert!(parse_music("o| o| .| .| o o o o".to_string()) == vec![2, 2, 1, 1, 4, 4, 4, 4]); assert!(parse_music("o| .| o| .| o o| o o|".to_string()) == vec![2, 1, 2, 1, 4, 2, 4, 2]); } }
Rust/18
/* Find how many times a given substring can be found in the original string. Count overlaping cases. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn how_many_times(string: String, substring:String) -> i32{
let mut times:i32 = 0; for i in 0..(string.len() as i32 - substring.len() as i32 + 1){ if string.get(i as usize..(i + substring.len() as i32) as usize).unwrap().to_string() == substring { times += 1; } } return times; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_how_many_times() { assert!(how_many_times("".to_string(), "x".to_string()) == 0); assert!(how_many_times("xyxyxyx".to_string(), "x".to_string()) == 4); assert!(how_many_times("cacacacac".to_string(), "cac".to_string()) == 4); assert!(how_many_times("john doe".to_string(), "john".to_string()) == 1); } }
Rust/19
/* Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from smallest to largest *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn sort_numbers(numbers:String) -> String {
let str_to_i32 = |x:&str| {match x{ "zero" => 0, "one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5, "six" => 6, "seven" => 7, "eight" => 8, "nine" => 9, _ => 1000 }}; let i32_to_str = |x:&i32| {match x{ 0 => "zero".to_string(), 1 => "one".to_string(), 2 => "two".to_string(), 3 => "three".to_string(), 4 => "four".to_string(), 5 => "five".to_string(), 6 => "six".to_string(), 7 => "seven".to_string(), 8 => "eight".to_string(), 9 => "nine".to_string(), _ => "none".to_string() }}; let mut nmbrs:Vec<i32> = numbers.split_ascii_whitespace().map(|x:&str| str_to_i32(x)).collect(); nmbrs.sort(); let res:String = nmbrs.iter().map(|x:&i32| i32_to_str(x) + " ").collect(); return res.trim_end().to_string(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_sort_numbers() { assert!(sort_numbers("".to_string()) == "".to_string()); assert!(sort_numbers("three".to_string()) == "three".to_string()); assert!(sort_numbers("three five nine".to_string()) == "three five nine"); assert!( sort_numbers("five zero four seven nine eight".to_string()) == "zero four five seven eight nine".to_string() ); assert!( sort_numbers("six five four three two one zero".to_string()) == "zero one two three four five six".to_string() ); } }
Rust/20
/* From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn find_closest_elements(numbers:Vec<f32>) -> (f32,f32){
let mut closest_pair = (0.0,0.0); let mut distance:Option<f32> = None; for (idx, elem) in numbers.iter().enumerate(){ for (idx2, elem2) in numbers.iter().enumerate() { if idx != idx2 { if distance == None { distance = Some((elem - elem2).abs()); if *elem < *elem2{ closest_pair = (*elem, *elem2); }else{ closest_pair = (*elem2, *elem); } }else{ let new_distance:f32= (elem - elem2).abs(); if new_distance < distance.unwrap(){ distance = Some(new_distance); if *elem < *elem2{ closest_pair = (*elem, *elem2); }else{ closest_pair = (*elem2, *elem); } } } } } } return closest_pair; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_find_closest_elements() { assert!(find_closest_elements(vec![1.0, 2.0, 3.9, 4.0, 5.0, 2.2]) == (3.9, 4.0)); assert!(find_closest_elements(vec![1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9)); assert!(find_closest_elements(vec![1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)); assert!(find_closest_elements(vec![1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)); assert!(find_closest_elements(vec![1.1, 2.2, 3.1, 4.1, 5.1]) == (2.2, 3.1)); } }
Rust/21
/* Given list of numbers (of at least two elements), apply a linear transform to that list, such that the smallest number will become 0 and the largest will become 1 *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn rescale_to_unit(numbers:Vec<f32>) -> Vec<f32> {
let min_number= *numbers.iter().min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap(); let max_number= *numbers.iter().max_by(|a, b| a.partial_cmp(b).unwrap()).unwrap(); return numbers.iter().map(|x:&f32| (x-min_number) / (max_number - min_number)).collect(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_rescale_to_unit() { assert!(rescale_to_unit(vec![2.0, 49.9]) == [0.0, 1.0]); assert!(rescale_to_unit(vec![100.0, 49.9]) == [1.0, 0.0]); assert!(rescale_to_unit(vec![1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]); assert!(rescale_to_unit(vec![2.0, 1.0, 5.0, 3.0, 4.0]) == [0.25, 0.0, 1.0, 0.5, 0.75]); assert!(rescale_to_unit(vec![12.0, 11.0, 15.0, 13.0, 14.0]) == [0.25, 0.0, 1.0, 0.5, 0.75]); } }
Rust/22
/* Filter given list of any python values only for integers *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn filter_integers(values: Vec<Box<dyn Any>>) -> Vec<i32> {
let mut out: Vec<i32> = Vec::new(); for value in values { if let Some(i) = value.downcast_ref::<i32>() { out.push(*i); } } out }
#[cfg(test)] mod tests { use super::*; #[test] fn test_filter_integers() { assert_eq!(filter_integers(vec![]), vec![]); let v_empty: Vec<Box<dyn Any>> = vec![]; assert_eq!( filter_integers(vec![ Box::new(4), Box::new(v_empty), Box::new(23.2), Box::new(9), Box::new(String::from("adasd")) ]), vec![4, 9] ); assert_eq!( filter_integers(vec![ Box::new(3), Box::new('c'), Box::new(3), Box::new(3), Box::new('a'), Box::new('b') ]), vec![3, 3, 3] ); } }
Rust/23
/* Return length of given string *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn strlen(strings:String) -> i32{
return strings.len() as i32; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_strlen() { assert!(strlen("".to_string()) == 0); assert!(strlen("x".to_string()) == 1); assert!(strlen("asdasnakj".to_string()) == 9); } }
Rust/24
/* For a given number n, find the largest number that divides n evenly, smaller than n *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn largest_divisor(n:i32) -> i32{
let mut res:i32 = 0; let sqn = 1..n; for i in sqn.rev(){ if n % i == 0 { res = i; break; } } return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_largest_divisor() { assert!(largest_divisor(3) == 1); assert!(largest_divisor(7) == 1); assert!(largest_divisor(10) == 5); assert!(largest_divisor(100) == 50); assert!(largest_divisor(49) == 7); } }
Rust/25
/* Return list of prime factors of given integer in the order from smallest to largest. Each of the factors should be listed number of times corresponding to how many times it appeares in factorization. Input number should be equal to the product of all factors *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn factorize(n: i32) -> Vec<i32> {
let mut n = n; let mut factors = vec![]; let mut divisor = 2; while divisor * divisor <= n { while n % divisor == 0 { factors.push(divisor); n = n / divisor; } divisor = divisor + 1; } if n > 1 { factors.push(n); } factors }
#[cfg(test)] mod tests { use super::*; #[test] fn test_factorize() { assert_eq!(factorize(2), vec![2]); assert_eq!(factorize(4), vec![2, 2]); assert_eq!(factorize(8), vec![2, 2, 2]); assert_eq!(factorize(3 * 19), vec![3, 19]); assert_eq!(factorize(3 * 19 * 3 * 19), vec![3, 3, 19, 19]); assert_eq!( factorize(3 * 19 * 3 * 19 * 3 * 19), vec![3, 3, 3, 19, 19, 19] ); assert_eq!(factorize(3 * 19 * 19 * 19), vec![3, 19, 19, 19]); assert_eq!(factorize(3 * 2 * 3), vec![2, 3, 3]); } }
Rust/26
/* From a list of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn remove_duplicates(numbers: Vec<i32>) -> Vec<i32>{
let mut m: HashMap<i32, i32> = HashMap::new(); for n in &numbers { *m.entry(*n).or_default() += 1; } let res:Vec<i32> = numbers.into_iter().filter(|x| m.get(x) == Some(&1)).collect(); return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_remove_duplicates() { assert!(remove_duplicates(vec![]) == []); assert!(remove_duplicates(vec![1, 2, 3, 4]) == vec![1, 2, 3, 4]); assert!(remove_duplicates(vec![1, 2, 3, 2, 4, 3, 5]) == [1, 4, 5]); } }
Rust/27
/* For a given string, flip lowercase characters to uppercase and uppercase to lowercase. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; pub fn flip_case(string: String) -> String{
return string.chars().into_iter().fold(String::new(), |res:String, c:char| {if c.is_ascii_lowercase(){return res + &c.to_uppercase().to_string();}else{return res + &c.to_ascii_lowercase().to_string();}}); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_flip_case() { assert!(flip_case("".to_string()) == "".to_string()); assert!(flip_case("Hello!".to_string()) == "hELLO!".to_string()); assert!( flip_case("These violent delights have violent ends".to_string()) == "tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS".to_string() ); } }
Rust/28
/* Concatenate list of strings into a single string *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn concatenate(strings:Vec<String>) -> String{
return strings.iter().fold(String::new(),|res: String, x:&String| res + &x.to_string()); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_concatenate() { assert!(concatenate(vec![]) == "".to_string()); assert!( concatenate(vec!["x".to_string(), "y".to_string(), "z".to_string()]) == "xyz".to_string() ); assert!( concatenate(vec![ "x".to_string(), "y".to_string(), "z".to_string(), "w".to_string(), "k".to_string() ]) == "xyzwk".to_string() ); } }
Rust/29
/* Filter an input list of strings only for ones that start with a given prefix. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn filter_by_prefix(strings:Vec<String>, prefix:String)-> Vec<String>{
return strings.into_iter().filter(|s| s.starts_with(&prefix)).collect(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_filter_by_prefix() { let v_empty: Vec<String> = vec![]; assert!(filter_by_prefix(vec![], "john".to_string()) == v_empty); assert!( filter_by_prefix( vec![ "xxx".to_string(), "asd".to_string(), "xxy".to_string(), "john doe".to_string(), "xxxAAA".to_string(), "xxx".to_string() ], "xxx".to_string() ) == vec!["xxx", "xxxAAA", "xxx"] ); } }
Rust/30
/* Return only positive numbers in the list. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn get_positive(numbers:Vec<i32>) -> Vec<i32>{
return numbers.into_iter().filter(|n| n.is_positive()).collect(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_get_positive() { assert!(get_positive(vec![-1, -2, 4, 5, 6]) == [4, 5, 6]); assert!( get_positive(vec![5, 3, -5, 2, 3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 3, 9, 123, 1] ); assert!(get_positive(vec![-1, -2]) == []); assert!(get_positive(vec![]) == []); } }
Rust/31
/* Return true if a given number is prime, and false otherwise. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn is_prime(n:i32) -> bool{
if n < 2{ return false; } for k in 2..n-1 { if n % k == 0{ return false; } } return true; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_is_prime() { assert!(is_prime(6) == false); assert!(is_prime(101) == true); assert!(is_prime(11) == true); assert!(is_prime(13441) == true); assert!(is_prime(61) == true); assert!(is_prime(4) == false); assert!(is_prime(1) == false); assert!(is_prime(5) == true); assert!(is_prime(11) == true); assert!(is_prime(17) == true); assert!(is_prime(5 * 17) == false); assert!(is_prime(11 * 7) == false); assert!(is_prime(13441 * 19) == false); } }
Rust/32
/* xs are coefficients of a polynomial. find_zero find x such that poly(x) = 0. find_zero returns only only zero point, even if there are many. Moreover, find_zero only takes list xs having even number of coefficients and largest non zero coefficient as it guarantees a solution. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn poly(xs: &Vec<f64>, x: f64) -> f64 {
let mut sum = 0.0; for i in 0..xs.len() { sum += xs[i] * x.powi(i as i32); } sum } fn find_zero(xs: &Vec<f64>) -> f64 { let mut ans = 0.0; let mut value = poly(xs, ans); while value.abs() > 1e-6 { let mut driv = 0.0; for i in 1..xs.len() { driv += xs[i] * ans.powi((i - 1) as i32) * (i as f64); } ans = ans - value / driv; value = poly(xs, ans); } ans }
#[cfg(test)] mod tests { use super::*; #[test] fn test_poly() { let mut rng = rand::thread_rng(); let mut solution: f64; let mut ncoeff: i32; for _ in 0..100 { ncoeff = 2 * (1 + rng.gen_range(0, 4)); let mut coeffs = vec![]; for _ in 0..ncoeff { let coeff = -10 + rng.gen_range(0, 21); if coeff == 0 { coeffs.push(1.0); } else { coeffs.push(coeff as f64); } } solution = find_zero(&coeffs); assert!(poly(&coeffs, solution).abs() < 1e-3); } } }
Rust/33
/* This function takes a list l and returns a list l' such that l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal to the values of the corresponding indicies of l, but sorted. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn sort_third(l: Vec<i32>) -> Vec<i32> {
let mut third = vec![]; let mut out:Vec<i32> = vec![]; for (indx,elem) in l.iter().enumerate(){ if indx%3 == 0 && indx != 0{ third.push(elem) } } third.sort(); let mut indx_t:usize = 0; for i in 0..l.len() { if i%3 == 0 && i != 0{ if indx_t < third.len(){ out.push(*third[indx_t]); indx_t += 1; } }else{ out.push(l[i]); } } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_sort_third() { let mut l = vec![1, 2, 3]; assert_eq!(sort_third(l), vec![1, 2, 3]); l = vec![5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]; assert_eq!(sort_third(l), vec![5, 3, -5, 1, -3, 3, 2, 0, 123, 9, -10]); l = vec![5, 8, -12, 4, 23, 2, 3, 11, 12, -10]; assert_eq!(sort_third(l), vec![5, 8, -12, -10, 23, 2, 3, 11, 12, 4]); l = vec![5, 6, 3, 4, 8, 9, 2]; assert_eq!(sort_third(l), vec![5, 6, 3, 2, 8, 9, 4]); l = vec![5, 8, 3, 4, 6, 9, 2]; assert_eq!(sort_third(l), vec![5, 8, 3, 2, 6, 9, 4]); l = vec![5, 6, 9, 4, 8, 3, 2]; assert_eq!(sort_third(l), vec![5, 6, 9, 2, 8, 3, 4]); l = vec![5, 6, 3, 4, 8, 9, 2, 1]; assert_eq!(sort_third(l), vec![5, 6, 3, 2, 8, 9, 4, 1]); } }
Rust/34
/* Return sorted unique elements in a list *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn unique(nmbs:Vec<i32>) -> Vec<i32>{
let mut res:Vec<i32> = nmbs.clone(); res.sort(); res.dedup(); return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_unique() { assert!(unique(vec![5, 3, 5, 2, 3, 3, 9, 0, 123]) == vec![0, 2, 3, 5, 9, 123]); } }
Rust/35
/* Return maximum element in the list. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn maximum(nmbs:Vec<i32>) -> i32{
return *nmbs.iter().max().unwrap(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_maximum() { assert!(maximum(vec![1, 2, 3]) == 3); assert!(maximum(vec![5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) == 124); } }
Rust/36
/* Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn fizz_buzz(n:i32) -> i32{
let mut ns:Vec<i32> = vec![]; for i in 0..n{ if i % 11 == 0 || i % 13 == 0{ ns.push(i); } } let s:String = ns.into_iter().fold(String::new(),|s:String, n:i32| {s + &n.to_string()}); let mut ans:i32 = 0; for c in s.chars(){ if c == '7'{ ans += 1; } } return ans; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_fizz_buzz() { assert!(fizz_buzz(50) == 0); assert!(fizz_buzz(78) == 2); assert!(fizz_buzz(79) == 3); assert!(fizz_buzz(100) == 3); assert!(fizz_buzz(200) == 6); assert!(fizz_buzz(4000) == 192); assert!(fizz_buzz(10000) == 639); assert!(fizz_buzz(100000) == 8026); } }
Rust/37
/* This function takes a list l and returns a list l' such that l' is identical to l in the odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn sort_even(nmbs:Vec<i32>) -> Vec<i32>{
let mut even = vec![]; let mut out:Vec<i32> = vec![]; for (indx,elem) in nmbs.iter().enumerate(){ if indx%2 == 0{ even.push(elem) } } even.sort(); let mut indx_t:usize = 0; for i in 0..nmbs.len() { if i%2 == 0{ if indx_t < even.len(){ out.push(*even[indx_t]); indx_t += 1; } }else{ out.push(nmbs[i]); } } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_sort_even() { assert_eq!(sort_even(vec![1, 2, 3]), vec![1, 2, 3]); assert_eq!( sort_even(vec![5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]), vec![-10, 3, -5, 2, -3, 3, 5, 0, 9, 1, 123] ); assert_eq!( sort_even(vec![5, 8, -12, 4, 23, 2, 3, 11, 12, -10]), vec![-12, 8, 3, 4, 5, 2, 12, 11, 23, -10] ); } }
Rust/38
/* takes as input string encoded with encode_cyclic function. Returns decoded string. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn encode_cyclic(s: &str) -> String {
let mut even = vec![]; let mut out:Vec<i32> = vec![]; for (indx,elem) in nmbs.iter().enumerate(){ if indx%2 == 0{ even.push(elem) } } even.sort(); let mut indx_t:usize = 0; for i in 0..nmbs.len() { if i%2 == 0{ if indx_t < even.len(){ out.push(*even[indx_t]); indx_t += 1; } }else{ out.push(nmbs[i]); } } return out; } //HumanEval/38 string decode_cyclic(string s){ pub fn encode_cyclic(s: &str) -> String { // returns encoded string by cycling groups of three characters. // split string to groups. Each of length 3. let l = s.len(); let num = (l + 2) / 3; let mut output = String::new(); for i in 0..num { let group = &s[i * 3..std::cmp::min(l, (i + 1) * 3)]; // cycle elements in each group. Unless group has fewer elements than 3. if group.len() == 3 { let x = format!("{}{}{}", &group[1..2], &group[2..3], &group[0..1]); output.push_str(&x); } else { output.push_str(group); } } output } pub fn decode_cyclic(s: &str) -> String { let l = s.len(); let num = (l + 2) / 3; let mut output = String::new(); for i in 0..num { let group = &s[i * 3..std::cmp::min(l, (i + 1) * 3)]; // revert the cycle performed by the encode_cyclic function if group.len() == 3 { let x = format!("{}{}{}", &group[2..3], &group[0..1], &group[1..2]); output.push_str(&x); } else { output.push_str(group); } } output }
#[cfg(test)] mod tests { use super::*; #[test] fn test_decode_cyclic() { for _ in 0..100 { let l = 10 + rand::random::<u32>() % 11; let mut str = String::new(); for _ in 0..l { let chr = 97 + rand::random::<u32>() % 26; str.push(chr as u8 as char); } let encoded_str = encode_cyclic(&str); assert_eq!(decode_cyclic(&encoded_str), str); } } }
Rust/39
/* prime_fib returns n-th number that is a Fibonacci number and it's also prime. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn prime_fib(n: i32) -> i32 {
let mut f1 = 1; let mut f2 = 2; let mut count = 0; while count < n { f1 = f1 + f2; let m = f1; f1 = f2; f2 = m; let mut isprime = true; for w in 2..(f1 as f32).sqrt() as i32 + 1 { if f1 % w == 0 { isprime = false; break; } } if isprime { count += 1; } if count == n { return f1; } } 0 }
#[cfg(test)] mod tests { use super::*; #[test] fn test_prime_fib() { assert_eq!(prime_fib(1), 2); assert_eq!(prime_fib(2), 3); assert_eq!(prime_fib(3), 5); assert_eq!(prime_fib(4), 13); assert_eq!(prime_fib(5), 89); assert_eq!(prime_fib(6), 233); assert_eq!(prime_fib(7), 1597); assert_eq!(prime_fib(8), 28657); assert_eq!(prime_fib(9), 514229); assert_eq!(prime_fib(10), 433494437); } }
Rust/40
/* triples_sum_to_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn triples_sum_to_zero(nmbs:Vec<i32>) -> bool{
for i in 0.. nmbs.len(){ for j in i + 1.. nmbs.len(){ for k in j + 1.. nmbs.len(){ if *nmbs.get(i).unwrap() + *nmbs.get(j).unwrap() + *nmbs.get(k).unwrap() == 0{ return true; } } } } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_triples_sum_to_zero() { assert!(triples_sum_to_zero(vec![1, 3, 5, 0]) == false); assert!(triples_sum_to_zero(vec![1, 3, 5, -1]) == false); assert!(triples_sum_to_zero(vec![1, 3, -2, 1]) == true); assert!(triples_sum_to_zero(vec![1, 2, 3, 7]) == false); assert!(triples_sum_to_zero(vec![1, 2, 5, 7]) == false); assert!(triples_sum_to_zero(vec![2, 4, -5, 3, 9, 7]) == true); assert!(triples_sum_to_zero(vec![1]) == false); assert!(triples_sum_to_zero(vec![1, 3, 5, -100]) == false); assert!(triples_sum_to_zero(vec![100, 3, 5, -100]) == false); } }
Rust/41
/* Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn car_race_collision(n:i32)-> i32{
return n*n; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_car_race_collision() { assert!(car_race_collision(2) == 4); assert!(car_race_collision(3) == 9); assert!(car_race_collision(4) == 16); assert!(car_race_collision(8) == 64); assert!(car_race_collision(10) == 100); } }
Rust/42
/* Return list with elements incremented by 1. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn incr_list(l:Vec<i32>) -> Vec<i32>{
return l.into_iter().map(|n:i32| n + 1).collect(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_incr_list() { assert!(incr_list(vec![]) == vec![]); assert!(incr_list(vec![3, 2, 1]) == [4, 3, 2]); assert!(incr_list(vec![5, 2, 5, 2, 3, 3, 9, 0, 123]) == [6, 3, 6, 3, 4, 4, 10, 1, 124]); } }
Rust/43
/* pairs_sum_to_zero takes a list of integers as an input. it returns True if there are two distinct elements in the list that sum to zero, and False otherwise. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn pairs_sum_to_zero(l:Vec<i32>) -> bool{
for (i, l1) in l.iter().enumerate(){ for j in i + 1.. l.len(){ if l1 + l[j] == 0{ return true; } } } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_pairs_sum_to_zero() { assert!(pairs_sum_to_zero(vec![1, 3, 5, 0]) == false); assert!(pairs_sum_to_zero(vec![1, 3, -2, 1]) == false); assert!(pairs_sum_to_zero(vec![1, 2, 3, 7]) == false); assert!(pairs_sum_to_zero(vec![2, 4, -5, 3, 5, 7]) == true); assert!(pairs_sum_to_zero(vec![1]) == false); assert!(pairs_sum_to_zero(vec![-3, 9, -1, 3, 2, 30]) == true); assert!(pairs_sum_to_zero(vec![-3, 9, -1, 3, 2, 31]) == true); assert!(pairs_sum_to_zero(vec![-3, 9, -1, 4, 2, 30]) == false); assert!(pairs_sum_to_zero(vec![-3, 9, -1, 4, 2, 31]) == false); } }
Rust/44
/* Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn change_base(x:i32, base:i32) -> String{
let mut ret:String = "".to_string(); let mut x1 = x; while x1 > 0{ ret = (x1 % base).to_string() + &ret; x1 = x1 / base; } return ret; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_change_base() { assert!(change_base(8, 3) == "22".to_string()); assert!(change_base(9, 3) == "100".to_string()); assert!(change_base(234, 2) == "11101010".to_string()); assert!(change_base(16, 2) == "10000".to_string()); assert!(change_base(8, 2) == "1000".to_string()); assert!(change_base(7, 2) == "111".to_string()); } }
Rust/45
/* Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn triangle_area(a:i32, h:i32) -> f64{
return (a * h) as f64 / 2.0; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_triangle_area() { assert!(triangle_area(5, 3) == 7.5); assert!(triangle_area(2, 2) == 2.0); assert!(triangle_area(10, 8) == 40.0); } }
Rust/46
/* The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fib4(0) -> 0 fib4(1) -> 0 fib4(2) -> 2 fib4(3) -> 0 fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn fib4(n:i32) -> i32{
let mut results:Vec<i32> = vec![0, 0, 2, 0]; if n < 4 { return *results.get(n as usize).unwrap(); } for _ in 4.. n + 1{ results.push(results.get(results.len()-1).unwrap() + results.get(results.len()-2).unwrap() + results.get(results.len()-3).unwrap() + results.get(results.len()-4).unwrap()); results.remove(0); } return *results.get(results.len()-1).unwrap(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_fib4() { assert!(fib4(5) == 4); assert!(fib4(8) == 28); assert!(fib4(10) == 104); assert!(fib4(12) == 386); } }
Rust/47
/* Return median of elements in the list l. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn median(l:Vec<i32>) -> f64{
let mut res:Vec<i32> = l.clone(); res.sort(); if res.len() % 2 == 1{ return *res.get(res.len() / 2).unwrap() as f64; }else{ return (res.get(res.len() / 2 -1).unwrap() + res.get(res.len() / 2).unwrap()) as f64/ 2.0; } }
#[cfg(test)] mod tests { use super::*; #[test] fn test_median() { assert!(median(vec![3, 1, 2, 4, 5]) == 3.0); assert!(median(vec![-10, 4, 6, 1000, 10, 20]) == 8.0); assert!(median(vec![5]) == 5.0); assert!(median(vec![6, 5]) == 5.5); assert!(median(vec![8, 1, 3, 9, 9, 2, 7]) == 7.0); } }
Rust/48
/* Checks if given string is a palindrome *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn is_palindrome(text: String) -> bool {
let pr: String = text.chars().rev().collect(); return pr == text; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_is_palindrome() { assert!(is_palindrome("".to_string()) == true); assert!(is_palindrome("aba".to_string()) == true); assert!(is_palindrome("aaaaa".to_string()) == true); assert!(is_palindrome("zbcd".to_string()) == false); assert!(is_palindrome("xywyx".to_string()) == true); assert!(is_palindrome("xywyz".to_string()) == false); assert!(is_palindrome("xywzx".to_string()) == false); } }
Rust/49
/* Return 2^n modulo p (be aware of numerics). *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn modp(n: i32, p: i32) -> i32 {
if n == 0 { return 1; } else { return (modp(n - 1, p) * 2) % p; } }
#[cfg(test)] mod tests { use super::*; #[test] fn test_modp() { assert!(modp(3, 5) == 3); assert!(modp(1101, 101) == 2); assert!(modp(0, 101) == 1); assert!(modp(3, 11) == 8); assert!(modp(100, 101) == 1); assert!(modp(30, 5) == 4); assert!(modp(31, 5) == 3); } }
Rust/50
/* takes as input string encoded with encode_shift function. Returns decoded string. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn encode_shift(s: &str) -> String {
let alphabet:Vec<&str> = vec!["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n" , "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; let mut output = String::new(); for c in s.chars() { let mut lower = false; if c.is_ascii_lowercase(){ lower = true; } let mut c_shift:String = "".to_string(); if lower { let index:usize = alphabet.iter().position(|&x| x == c.to_string()).unwrap(); c_shift = alphabet[(index + 5) % 26].to_string(); }else{ let c_lower:String = c.to_ascii_lowercase().to_string(); let index:usize = alphabet.iter().position(|&x| x == c_lower).unwrap(); c_shift = alphabet[(index + 5) % 26].to_string(); c_shift = c_shift.to_ascii_uppercase().to_string(); } output.push_str(&c_shift); } output } pub fn decode_shift(s: &str) -> String { let alphabet:Vec<&str> = vec!["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n" , "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; let mut output = String::new(); for c in s.chars() { let mut lower = false; if c.is_ascii_lowercase(){ lower = true; } let mut c_shift:String = "".to_string(); if lower { let index:usize = alphabet.iter().position(|&x| x == c.to_string()).unwrap(); c_shift = alphabet[((26 + (index as i32 - 5)) % 26) as usize].to_string(); }else{ let c_lower:String = c.to_ascii_lowercase().to_string(); let index:usize = alphabet.iter().position(|&x| x == c_lower).unwrap(); c_shift = alphabet[((26 + (index as i32 - 5)) % 26) as usize].to_string(); c_shift = c_shift.to_ascii_uppercase().to_string(); } output.push_str(&c_shift); } output }
#[cfg(test)] mod tests { use super::*; #[test] //Imposing that random characters that can be generated are solely from the alphabet fn test_decode_encode() { fn random_char() -> char { let mut rng = rand::thread_rng(); let letter: char = match rng.gen_range(0, 2) { 0 => rng.gen_range(b'a', b'z' + 1).into(), 1 => rng.gen_range(b'A', b'Z' + 1).into(), _ => unreachable!(), }; return letter; } let mut rng = rand::thread_rng(); for _ in 0..100 { let r1: i32 = rng.gen(); let l: i32 = 10 + r1 % 11; let mut str: String = "".to_string(); for _ in 0..l { let chr: char = random_char(); println!("{}", chr); str.push(chr); } let encoded_str: String = encode_shift(&str); assert!(decode_shift(&encoded_str) == str); } } }
Rust/51
/* remove_vowels is a function that takes string and returns string without vowels. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn remove_vowels(text: &str) -> String {
let vowels = "AEIOUaeiou"; let mut out = String::new(); for c in text.chars() { if !vowels.contains(c) { out.push(c); } } out }
#[cfg(test)] mod tests { use super::*; #[test] fn test_remove_vowels() { assert!(remove_vowels("") == ""); assert!(remove_vowels("abcdef\nghijklm") == "bcdf\nghjklm"); assert!(remove_vowels("fedcba") == "fdcb"); assert!(remove_vowels("eeeee") == ""); assert!(remove_vowels("acBAA") == "cB"); assert!(remove_vowels("EcBOO") == "cB"); assert!(remove_vowels("ybcd") == "ybcd"); } }
Rust/52
/* Return True if all numbers in the list l are below threshold t. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn below_threshold(l: Vec<i32>, t: i32) -> bool {
for i in l { if i >= t { return false; } } return true; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_below_threshold() { assert!(below_threshold(vec![1, 2, 4, 10], 100)); assert!(!below_threshold(vec![1, 20, 4, 10], 5)); assert!(below_threshold(vec![1, 20, 4, 10], 21)); assert!(below_threshold(vec![1, 20, 4, 10], 22)); assert!(below_threshold(vec![1, 8, 4, 10], 11)); assert!(!below_threshold(vec![1, 8, 4, 10], 10)); } }
Rust/53
/* Add two numbers x and y *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn add(x:i32, y:i32) -> i32{
return x + y; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_add() { assert!(add(0, 1) == 1); assert!(add(1, 0) == 1); assert!(add(2, 3) == 5); assert!(add(5, 7) == 12); assert!(add(7, 5) == 12); for _ in 0..100 { let mut rng = rand::thread_rng(); let mut x: i32 = rng.gen(); x = x % 1000; let mut y: i32 = rng.gen(); y = y % 1000; assert!(add(x, y) == x + y); } } }
Rust/54
/* Check if two words have the same characters. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn same_chars(str1:&str, str2:&str) -> bool{
let mut v1:Vec<char> = str1.chars().into_iter().collect(); v1.sort(); v1.dedup(); let mut v2:Vec<char> = str2.chars().into_iter().collect(); v2.sort(); v2.dedup(); return v1 == v2; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_same_chars() { assert!(same_chars("eabcdzzzz", "dddzzzzzzzddeddabc") == true); assert!(same_chars("abcd", "dddddddabc") == true); assert!(same_chars("dddddddabc", "abcd") == true); assert!(same_chars("eabcd", "dddddddabc") == false); assert!(same_chars("abcd", "dddddddabcf") == false); assert!(same_chars("eabcdzzzz", "dddzzzzzzzddddabc") == false); assert!(same_chars("aabb", "aaccc") == false); } }
Rust/55
/* Return n-th Fibonacci number. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn fib(n:i32) -> i32{
if n == 0{ return 0; } if n == 1{ return 1; } return fib(n-1) + fib(n-2); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_fib() { assert!(fib(10) == 55); assert!(fib(1) == 1); assert!(fib(8) == 21); assert!(fib(11) == 89); assert!(fib(12) == 144); } }
Rust/56
/* brackets is a string of "<" and ">". return True if every opening bracket has a corresponding closing bracket. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn correct_bracketing(bkts:&str) -> bool{
let mut level:i32=0; for i in 0..bkts.len(){ if bkts.chars().nth(i).unwrap()== '<' {level+=1;} if bkts.chars().nth(i).unwrap() == '>' { level-=1;} if level<0 {return false;} } if level!=0 {return false;} return true; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_correct_bracketing() { assert!(correct_bracketing("<>")); assert!(correct_bracketing("<<><>>")); assert!(correct_bracketing("<><><<><>><>")); assert!(correct_bracketing("<><><<<><><>><>><<><><<>>>")); assert!(!(correct_bracketing("<<<><>>>>"))); assert!(!(correct_bracketing("><<>"))); assert!(!(correct_bracketing("<"))); assert!(!(correct_bracketing("<<<<"))); assert!(!(correct_bracketing(">"))); assert!(!(correct_bracketing("<<>"))); assert!(!(correct_bracketing("<><><<><>><>><<>"))); assert!(!(correct_bracketing("<><><<><>><>>><>"))); } }
Rust/57
/* Return True is list elements are monotonically increasing or decreasing. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn monotonic( l:Vec<i32>) -> bool{
let mut l1:Vec<i32> = l.clone(); let mut l2:Vec<i32> = l.clone(); l2.sort(); l2.reverse(); l1.sort(); if l == l1 || l == l2 {return true} return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_monotonic() { assert!(monotonic(vec![1, 2, 4, 10]) == true); assert!(monotonic(vec![1, 2, 4, 20]) == true); assert!(monotonic(vec![1, 20, 4, 10]) == false); assert!(monotonic(vec![4, 1, 0, -10]) == true); assert!(monotonic(vec![4, 1, 1, 0]) == true); assert!(monotonic(vec![1, 2, 3, 2, 5, 60]) == false); assert!(monotonic(vec![1, 2, 3, 4, 5, 60]) == true); assert!(monotonic(vec![9, 9, 9, 9]) == true); } }
Rust/58
/* Return sorted unique common elements for two lists. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn common(l1:Vec<i32>, l2:Vec<i32>) -> Vec<i32>{
let mut res:Vec<i32> = l1.into_iter().filter(|n:&i32| l2.contains(n)).collect(); res.sort(); return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_common() { assert!( common(vec![1, 4, 3, 34, 653, 2, 5], vec![5, 7, 1, 5, 9, 653, 121]) == vec![1, 5, 653] ); assert!(common(vec![5, 3, 2, 8], vec![3, 2]) == vec![2, 3]); assert!(common(vec![4, 3, 2, 8], vec![3, 2, 4]) == vec![2, 3, 4]); assert!(common(vec![4, 3, 2, 8], vec![]) == vec![]); } }
Rust/59
/* Return the largest prime factor of n. Assume n > 1 and is not a prime. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn largest_prime_factor(n:i32) -> i32{
let mut n1 = n.clone(); for i in 2.. n1{ while n1%i == 0 && n1>i{n1 = n1/i;} } return n1; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_largest_prime_factor() { assert!(largest_prime_factor(15) == 5); assert!(largest_prime_factor(27) == 3); assert!(largest_prime_factor(63) == 7); assert!(largest_prime_factor(330) == 11); assert!(largest_prime_factor(13195) == 29); } }
Rust/60
/* sum_to_n is a function that sums numbers from 1 to n. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn sum_to_n(n: i32) -> i32 {
n*(n+1)/2 }
#[cfg(test)] mod tests { use super::*; #[test] fn test_sum_to_n() { assert!(sum_to_n(1) == 1); assert!(sum_to_n(6) == 21); assert!(sum_to_n(11) == 66); assert!(sum_to_n(30) == 465); assert!(sum_to_n(100) == 5050); } }
Rust/61
/* brackets is a string of "(" and ")". return True if every opening bracket has a corresponding closing bracket. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn correct_bracketing_parenthesis(bkts:&str) -> bool{
let mut level:i32=0; for i in 0..bkts.len(){ if bkts.chars().nth(i).unwrap()== '(' {level+=1;} if bkts.chars().nth(i).unwrap() == ')' { level-=1;} if level<0 {return false;} } if level!=0 {return false;} return true; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_correct_bracketing_parenthesis() { assert!(correct_bracketing_parenthesis("()")); assert!(correct_bracketing_parenthesis("(()())")); assert!(correct_bracketing_parenthesis("()()(()())()")); assert!(correct_bracketing_parenthesis("()()((()()())())(()()(()))")); assert!(!(correct_bracketing_parenthesis("((()())))"))); assert!(!(correct_bracketing_parenthesis(")(()"))); assert!(!(correct_bracketing_parenthesis("("))); assert!(!(correct_bracketing_parenthesis("(((("))); assert!(!(correct_bracketing_parenthesis(")"))); assert!(!(correct_bracketing_parenthesis("(()"))); assert!(!(correct_bracketing_parenthesis("()()(()())())(()"))); assert!(!(correct_bracketing_parenthesis("()()(()())()))()"))); } }
Rust/62
/* xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn derivative(xs:Vec<i32>) -> Vec<i32>{
let mut res:Vec<i32> =vec![]; for i in 1..xs.len(){ res.push(i as i32 * xs.get(i).unwrap()); } return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_derivative() { assert!(derivative(vec![3, 1, 2, 4, 5]) == vec![1, 4, 12, 20]); assert!(derivative(vec![1, 2, 3]) == vec![2, 6]); assert!(derivative(vec![3, 2, 1]) == vec![2, 2]); assert!(derivative(vec![3, 2, 1, 0, 4]) == vec![2, 2, 0, 16]); assert!(derivative(vec![1]) == vec![]); } }
Rust/63
/* The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fibfib(0) == 0 fibfib(1) == 0 fibfib(2) == 1 fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). Please write a function to efficiently compute the n-th element of the fibfib number sequence. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn fibfib(n:i32) -> i32{
if n == 0 || n == 1{ return 0; } if n == 2{ return 1; } return fibfib(n-1) + fibfib(n-2) + fibfib(n-3); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_fibfib() { assert!(fibfib(2) == 1); assert!(fibfib(1) == 0); assert!(fibfib(5) == 4); assert!(fibfib(8) == 24); assert!(fibfib(10) == 81); assert!(fibfib(12) == 274); assert!(fibfib(14) == 927); } }
Rust/64
/* Write a function vowels_count which takes a string representing a word as input and returns the number of vowels in the string. Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn vowels_count(s:&str) -> i32 {
let vowels:&str = "aeiouAEIOU"; let mut count:i32 = 0; for i in 0..s.len() { let c:char = s.chars().nth(i).unwrap(); if vowels.contains(c){ count += 1; } } if s.chars().nth(s.len() -1).unwrap() == 'y' || s.chars().nth(s.len() -1).unwrap() == 'Y' {count+=1;} return count; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_vowels_count() { assert!(vowels_count("abcde") == 2); assert!(vowels_count("Alone") == 3); assert!(vowels_count("key") == 2); assert!(vowels_count("bye") == 1); assert!(vowels_count("keY") == 2); assert!(vowels_count("bYe") == 1); assert!(vowels_count("ACEDY") == 3); } }
Rust/65
/* Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn circular_shift(x:i32, shift:i32) -> String{
let mut xcp:Vec<char> = x.to_string().chars().into_iter().collect(); let mut res:Vec<char> = x.to_string().chars().into_iter().collect(); for (indx,c) in xcp.iter().enumerate(){ let despl = (indx as i32 + shift) % x.to_string().len() as i32; replace(&mut res[despl as usize], *c); } return res.into_iter().collect(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_circular_shift() { assert!(circular_shift(100, 2) == "001"); assert!(circular_shift(12, 8) == "12"); // original test asert (circular_shift(97, 8) == "79"); DATASET ERROR assert!(circular_shift(97, 8) == "97"); assert!(circular_shift(12, 1) == "21"); assert!(circular_shift(11, 101) == "11"); } }
Rust/66
/* Task Write a function that takes a string as input and returns the sum of the upper characters only' ASCII codes. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn digitSum(s:&str) -> i32{
return s.chars().into_iter().filter(|c:&char| c.is_uppercase()).map(|c:char| c as i32).sum(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_digitSum() { assert!(digitSum("") == 0); assert!(digitSum("abAB") == 131); assert!(digitSum("abcCd") == 67); assert!(digitSum("helloE") == 69); assert!(digitSum("woArBld") == 131); assert!(digitSum("aAaaaXa") == 153); assert!(digitSum(" How are yOu?") == 151); assert!(digitSum("You arE Very Smart") == 327); } }
Rust/67
/* In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn fruit_distribution(s:&str, n:i32) -> i32 {
let sub:i32 = s.split_ascii_whitespace().into_iter().filter(|c| c.parse::<i32>().is_ok()).map(|c| c.parse::<i32>().unwrap()).sum(); return n-sub; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_fruit_distribution() { assert!(fruit_distribution("5 apples and 6 oranges", 19) == 8); assert!(fruit_distribution("5 apples and 6 oranges", 21) == 10); assert!(fruit_distribution("0 apples and 1 oranges", 3) == 2); assert!(fruit_distribution("1 apples and 0 oranges", 3) == 2); assert!(fruit_distribution("2 apples and 3 oranges", 100) == 95); assert!(fruit_distribution("2 apples and 3 oranges", 5) == 0); assert!(fruit_distribution("1 apples and 100 oranges", 120) == 19); } }
Rust/68
/* "Given an array representing a branch of a tree that has non-negative integer nodes your task is to pluck one of the nodes and return it. The plucked node should be the node with the smallest even value. If multiple nodes with the same smallest even value are found return the node that has smallest index. The plucked node should be returned in a list, [ smalest_value, its index ], If there are no even values or the given array is empty, return []. Constraints: * 1 <= nodes.length <= 10000 * 0 <= node.value *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn pluck(arr:Vec<i32>) -> Vec<i32> {
let mut out:Vec<i32> = vec![]; for i in 0.. arr.len(){ if arr[i]%2 == 0 && (out.len() == 0 || arr[i]<out[0]){ out = vec![arr[i], i as i32]; } } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_pluck() { assert!(pluck(vec![4, 2, 3]) == vec![2, 1]); assert!(pluck(vec![1, 2, 3]) == vec![2, 1]); assert!(pluck(vec![]) == vec![]); assert!(pluck(vec![5, 0, 3, 0, 4, 2]) == vec![0, 1]); assert!(pluck(vec![1, 2, 3, 0, 5, 3]) == vec![0, 3]); assert!(pluck(vec![5, 4, 8, 4, 8]) == vec![4, 1]); assert!(pluck(vec![7, 6, 7, 1]) == vec![6, 1]); assert!(pluck(vec![7, 9, 7, 1]) == vec![]); } }
Rust/69
/* You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn search(lst: Vec<i32>) -> i32 {
let mut freq: Vec<Vec<i32>> = Vec::new(); let mut max = -1; for i in 0..lst.len() { let mut has = false; for j in 0..freq.len() { if lst[i] == freq[j][0] { freq[j][1] += 1; has = true; if freq[j][1] >= freq[j][0] && freq[j][0] > max { max = freq[j][0]; } } } if !has { freq.push(vec![lst[i], 1]); if max == -1 && lst[i] == 1 { max = 1; } } } return max; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_search() { assert!(search(vec![5, 5, 5, 5, 1]) == 1); assert!(search(vec![4, 1, 4, 1, 4, 4]) == 4); assert!(search(vec![3, 3]) == -1); assert!(search(vec![8, 8, 8, 8, 8, 8, 8, 8]) == 8); assert!(search(vec![2, 3, 3, 2, 2]) == 2); assert!( search(vec![ 2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1 ]) == 1 ); assert!(search(vec![3, 2, 8, 2]) == 2); assert!(search(vec![6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]) == 1); assert!(search(vec![8, 8, 3, 6, 5, 6, 4]) == -1); assert!( search(vec![ 6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9 ]) == 1 ); assert!(search(vec![1, 9, 10, 1, 3]) == 1); assert!( search(vec![ 6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10 ]) == 5 ); assert!(search(vec![1]) == 1); assert!( search(vec![ 8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5 ]) == 4 ); assert!( search(vec![ 2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10 ]) == 2 ); assert!(search(vec![1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]) == 1); assert!( search(vec![ 9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4 ]) == 4 ); assert!( search(vec![ 2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7 ]) == 4 ); assert!( search(vec![ 9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1 ]) == 2 ); assert!( search(vec![ 5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8 ]) == -1 ); assert!(search(vec![10]) == -1); assert!(search(vec![9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]) == 2); assert!(search(vec![5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]) == 1); assert!( search(vec![ 7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6 ]) == 1 ); assert!(search(vec![3, 10, 10, 9, 2]) == -1); } }
Rust/70
/* Given list of integers, return list in strange order. Strange sorting, is when you start with the minimum value, then maximum of the remaining integers, then minimum and so on. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn strange_sort_list(lst: Vec<i32>) -> Vec<i32>{
let mut cp:Vec<i32> = lst.clone(); let mut res:Vec<i32> = vec![]; for (indx, _) in lst.iter().enumerate(){ if indx%2 == 1 { let max:i32 = *cp.iter().max().unwrap(); res.push(max); cp.remove(cp.iter().position(|x| *x == max).unwrap()); } else{ let min:i32 = *cp.iter().min().unwrap(); res.push(min); cp.remove(cp.iter().position(|x| *x == min).unwrap()); } } return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_strange_sort_list() { assert!(strange_sort_list(vec![1, 2, 3, 4]) == vec![1, 4, 2, 3]); assert!(strange_sort_list(vec![5, 6, 7, 8, 9]) == vec![5, 9, 6, 8, 7]); assert!(strange_sort_list(vec![1, 2, 3, 4, 5]) == vec![1, 5, 2, 4, 3]); assert!(strange_sort_list(vec![5, 6, 7, 8, 9, 1]) == vec![1, 9, 5, 8, 6, 7]); assert!(strange_sort_list(vec![5, 5, 5, 5]) == vec![5, 5, 5, 5]); assert!(strange_sort_list(vec![]) == vec![]); assert!(strange_sort_list(vec![1, 2, 3, 4, 5, 6, 7, 8]) == vec![1, 8, 2, 7, 3, 6, 4, 5]); assert!( strange_sort_list(vec![0, 2, 2, 2, 5, 5, -5, -5]) == vec![-5, 5, -5, 5, 0, 2, 2, 2] ); assert!(strange_sort_list(vec![111111]) == vec![111111]); } }
Rust/71
/* Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn triangle_area_f64(a:f64, b:f64, c:f64) -> f64{
if a+b<=c || a+c<=b || b+c<=a {return -1.0;} let h:f64=(a+b+c) / 2.0; let mut area:f64; area = f64::powf(h*(h-a)*(h-b)*(h-c),0.5); return area; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_triangle_area_f64() { assert!(f64::abs(triangle_area_f64(3.0, 4.0, 5.0) - 6.00) < 0.01); assert!(f64::abs(triangle_area_f64(1.0, 2.0, 10.0) + 1.0) < 0.01); assert!(f64::abs(triangle_area_f64(4.0, 8.0, 5.0) - 8.18) < 0.01); assert!(f64::abs(triangle_area_f64(2.0, 2.0, 2.0) - 1.73) < 0.01); assert!(f64::abs(triangle_area_f64(1.0, 2.0, 3.0) + 1.0) < 0.01); assert!(f64::abs(triangle_area_f64(10.0, 5.0, 7.0) - 16.25) < 0.01); assert!(f64::abs(triangle_area_f64(2.0, 6.0, 3.0) + 1.0) < 0.01); assert!(f64::abs(triangle_area_f64(1.0, 1.0, 1.0) - 0.43) < 0.01); assert!(f64::abs(triangle_area_f64(2.0, 2.0, 10.0) + 1.0) < 0.01); } }
Rust/72
/* Write a function that returns True if the object q will fly, and False otherwise. The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn will_it_fly(q:Vec<i32>, w:i32) -> bool{
if q.iter().sum::<i32>() > w { return false; } let mut i = 0; let mut j = q.len() - 1; while i < j { if q[i] != q[j] { return false; } i += 1; j -= 1; } return true; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_will_it_fly() { assert!(will_it_fly(vec![3, 2, 3], 9) == true); assert!(will_it_fly(vec![1, 2], 5) == false); assert!(will_it_fly(vec![3], 5) == true); assert!(will_it_fly(vec![3, 2, 3], 1) == false); assert!(will_it_fly(vec![1, 2, 3], 6) == false); assert!(will_it_fly(vec![5], 5) == true); } }
Rust/73
/* Given an array arr of integers, find the minimum number of elements that need to be changed to make the array palindromic. A palindromic array is an array that is read the same backwards and forwards. In one change, you can change one element to any other element. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn smallest_change(arr:Vec<i32>) -> i32{
let mut ans: i32 = 0; for i in 0..arr.len() / 2 { if arr[i] != arr[arr.len() - i - 1] { ans += 1 } } return ans; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_smallest_change() { assert!(smallest_change(vec![1, 2, 3, 5, 4, 7, 9, 6]) == 4); assert!(smallest_change(vec![1, 2, 3, 4, 3, 2, 2]) == 1); assert!(smallest_change(vec![1, 4, 2]) == 1); assert!(smallest_change(vec![1, 4, 4, 2]) == 1); assert!(smallest_change(vec![1, 2, 3, 2, 1]) == 0); assert!(smallest_change(vec![3, 1, 1, 3]) == 0); assert!(smallest_change(vec![1]) == 0); assert!(smallest_change(vec![0, 1]) == 1); } }
Rust/74
/* Write a function that accepts two lists of strings and returns the list that has total number of chars in the all strings of the list less than the other list. if the two lists have the same number of chars, return the first list. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn total_match(lst1:Vec<&str>, lst2:Vec<&str>) -> Vec<String>{
let total_1: usize = lst1 .iter() .fold(0, |acc: usize, str: &&str| acc + str.chars().count()); let total_2: usize = lst2 .iter() .fold(0, |acc: usize, str: &&str| acc + str.chars().count()); if total_1 <= total_2 { return lst1.into_iter().map(|x| x.to_string()).collect(); } else { return lst2.into_iter().map(|x| x.to_string()).collect(); } }
#[cfg(test)] mod tests { use super::*; #[test] fn test_total_match() { let v_empty: Vec<String> = vec![]; assert!(total_match(vec![], vec![]) == v_empty); assert!(total_match(vec!["hi", "admin"], vec!["hi", "hi"]) == vec!["hi", "hi"]); assert!( total_match(vec!["hi", "admin"], vec!["hi", "hi", "admin", "project"]) == vec!["hi", "admin"] ); assert!(total_match(vec!["4"], vec!["1", "2", "3", "4", "5"]) == vec!["4"]); assert!(total_match(vec!["hi", "admin"], vec!["hI", "Hi"]) == vec!["hI", "Hi"]); assert!(total_match(vec!["hi", "admin"], vec!["hI", "hi", "hi"]) == vec!["hI", "hi", "hi"]); assert!(total_match(vec!["hi", "admin"], vec!["hI", "hi", "hii"]) == vec!["hi", "admin"]); assert!(total_match(vec![], vec!["this"]) == v_empty); assert!(total_match(vec!["this"], vec![]) == v_empty); } }
Rust/75
/* Write a function that returns true if the given number is the multiplication of 3 prime numbers and false otherwise. Knowing that (a) is less then 100. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn is_multiply_prime(a: i32) -> bool {
let mut a1 = a; let mut num = 0; for i in 2..a { while a1 % i == 0 && a1 > i { a1 /= i; num += 1; } } if num == 2 { return true; } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_is_multiply_prime() { assert!(is_multiply_prime(5) == false); assert!(is_multiply_prime(30) == true); assert!(is_multiply_prime(8) == true); assert!(is_multiply_prime(10) == false); assert!(is_multiply_prime(125) == true); assert!(is_multiply_prime(3 * 5 * 7) == true); assert!(is_multiply_prime(3 * 6 * 7) == false); assert!(is_multiply_prime(9 * 9 * 9) == false); assert!(is_multiply_prime(11 * 9 * 9) == false); assert!(is_multiply_prime(11 * 13 * 7) == true); } }
Rust/76
/* Your task is to write a function that returns true if a number x is a simple power of n and false in other cases. x is a simple power of n if n**int=x *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn is_simple_power(x:i32, n:i32) -> bool{
let mut p: i32 = 1; let mut count: i32 = 0; while p <= x && count < 100 { if p == x { return true; }; p = p * n; count += 1; } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_is_simple_power() { assert!(is_simple_power(1, 4) == true); assert!(is_simple_power(2, 2) == true); assert!(is_simple_power(8, 2) == true); assert!(is_simple_power(3, 2) == false); assert!(is_simple_power(3, 1) == false); assert!(is_simple_power(5, 3) == false); assert!(is_simple_power(16, 2) == true); assert!(is_simple_power(143214, 16) == false); assert!(is_simple_power(4, 2) == true); assert!(is_simple_power(9, 3) == true); assert!(is_simple_power(16, 4) == true); assert!(is_simple_power(24, 2) == false); assert!(is_simple_power(128, 4) == false); assert!(is_simple_power(12, 6) == false); assert!(is_simple_power(1, 1) == true); assert!(is_simple_power(1, 12) == true); } }
Rust/77
/* Write a function that takes an integer a and returns True if this ingeger is a cube of some integer number. Note: you may assume the input is always valid. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn iscuber(a:i32) -> bool{
let a1: f64 = i32::abs(a) as f64; let sqrt_3 = f64::powf(a1, 1.0 / 3.0).ceil(); return i32::pow(sqrt_3 as i32, 3) == a1 as i32; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_iscuber() { assert!(iscuber(1) == true); assert!(iscuber(2) == false); assert!(iscuber(-1) == true); assert!(iscuber(64) == true); assert!(iscuber(180) == false); assert!(iscuber(1000) == true); assert!(iscuber(0) == true); assert!(iscuber(1729) == false); } }
Rust/78
/* You have been tasked to write a function that receives a hexadecimal number as a string and counts the number of hexadecimal digits that are primes (prime number, or a prime, is a natural number greater than 1 that is not a product of two smaller natural numbers). Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Prime numbers are 2, 3, 5, 7, 11, 13, 17,... So you have to determine a number of the following digits: 2, 3, 5, 7, B (=decimal 11), D (=decimal 13). Note: you may assume the input is always correct or empty string, and symbols A,B,C,D,E,F are always uppercase. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn hex_key(num:&str) -> i32{
let primes: Vec<&str> = vec!["2", "3", "5", "7", "B", "D"]; let mut total: i32 = 0; for i in 0..num.len() { if primes.contains(&num.get(i..i + 1).unwrap()) { total += 1; } } return total; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_hex_key() { assert!(hex_key("AB") == 1); assert!(hex_key("1077E") == 2); assert!(hex_key("ABED1A33") == 4); assert!(hex_key("2020") == 2); assert!(hex_key("123456789ABCDEF0") == 6); assert!(hex_key("112233445566778899AABBCCDDEEFF00") == 12); assert!(hex_key("") == 0); } }
Rust/79
/* You will be given a number in decimal form and your task is to convert it to binary format. The function should return a string, with each character representing a binary number. Each character in the string will be '0' or '1'. There will be an extra couple of characters 'db' at the beginning and at the end of the string. The extra characters are there to help with the format. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn decimal_to_binary(decimal:i32) -> String{
let mut d_cp = decimal; let mut out: String = String::from(""); if d_cp == 0 { return "db0db".to_string(); } while d_cp > 0 { out = (d_cp % 2).to_string() + &out; d_cp = d_cp / 2; } out = "db".to_string() + &out + &"db".to_string(); return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_decimal_to_binary() { assert!(decimal_to_binary(0) == "db0db".to_string()); assert!(decimal_to_binary(32) == "db100000db".to_string()); assert!(decimal_to_binary(103) == "db1100111db".to_string()); assert!(decimal_to_binary(15) == "db1111db".to_string()); } }
Rust/80
/* You are given a string s. Your task is to check if the string is happy or not. A string is happy if its length is at least 3 and every 3 consecutive letters are distinct *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn is_happy(s:&str) -> bool{
let str: Vec<char> = s.chars().into_iter().collect(); if str.len() < 3 { return false; } for i in 2..str.len() { if str[i] == str[i - 1] || str[i] == str[i - 2] { return false; } } return true; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_is_happy() { assert!(is_happy("a") == false); assert!(is_happy("aa") == false); assert!(is_happy("abcd") == true); assert!(is_happy("aabb") == false); assert!(is_happy("adb") == true); assert!(is_happy("xyy") == false); assert!(is_happy("iopaxpoi") == true); assert!(is_happy("iopaxioi") == false); } }
Rust/81
/* It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn numerical_letter_grade(grades:Vec<f64>) -> Vec<String>{
let mut res: Vec<String> = vec![]; for (i, gpa) in grades.iter().enumerate() { if gpa == &4.0 { res.push("A+".to_string()); } else if gpa > &3.7 { res.push("A".to_string()); } else if gpa > &3.3 { res.push("A-".to_string()); } else if gpa > &3.0 { res.push("B+".to_string()); } else if gpa > &2.7 { res.push("B".to_string()); } else if gpa > &2.3 { res.push("B-".to_string()); } else if gpa > &2.0 { res.push("C+".to_string()); } else if gpa > &1.7 { res.push("C".to_string()); } else if gpa > &1.3 { res.push("C-".to_string()); } else if gpa > &1.0 { res.push("D+".to_string()); } else if gpa > &0.7 { res.push("D".to_string()); } else if gpa > &0.0 { res.push("D-".to_string()); } else { res.push("E".to_string()); } } return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_numerical_letter_grade() { assert!( numerical_letter_grade(vec![4.0, 3.0, 1.7, 2.0, 3.5]) == vec!["A+", "B", "C-", "C", "A-"] ); assert!(numerical_letter_grade(vec![1.2]) == vec!["D+"]); assert!(numerical_letter_grade(vec![0.5]) == vec!["D-"]); assert!(numerical_letter_grade(vec![0.0]) == vec!["E"]); assert!( numerical_letter_grade(vec![1.0, 0.3, 1.5, 2.8, 3.3]) == vec!["D", "D-", "C-", "B", "B+"] ); assert!(numerical_letter_grade(vec![0.0, 0.7]) == vec!["E", "D-"]); } }
Rust/82
/* Write a function that takes a string and returns True if the string length is a prime number or False otherwise *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn prime_length(str:&str) -> bool{
let l: usize = str.len(); if l == 0 || l == 1 { return false; } for i in 2..l { if l % i == 0 { return false; } } return true; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_prime_length() { assert!(prime_length("Hello") == true); assert!(prime_length("abcdcba") == true); assert!(prime_length("kittens") == true); assert!(prime_length("orange") == false); assert!(prime_length("wow") == true); assert!(prime_length("world") == true); assert!(prime_length("MadaM") == true); assert!(prime_length("Wow") == true); assert!(prime_length("") == false); assert!(prime_length("HI") == true); assert!(prime_length("go") == true); assert!(prime_length("gogo") == false); assert!(prime_length("aaaaaaaaaaaaaaa") == false); assert!(prime_length("Madam") == true); assert!(prime_length("M") == false); assert!(prime_length("0") == false); } }
Rust/83
/* Given a positive integer n, return the count of the numbers of n-digit positive integers that start or end with 1. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn starts_one_ends(n:i32) -> i32{
if n == 1 { return 1; }; return 18 * i32::pow(10, (n - 2) as u32); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_starts_one_ends() { assert!(starts_one_ends(1) == 1); assert!(starts_one_ends(2) == 18); assert!(starts_one_ends(3) == 180); assert!(starts_one_ends(4) == 1800); assert!(starts_one_ends(5) == 18000); } }
Rust/84
/* Given a positive integer N, return the total sum of its digits in binary. Variables: @N integer Constraints: 0 ≤ N ≤ 10000. Output: a string of binary number *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn solve(n:i32) -> String{
let sum: i32 = n .to_string() .chars() .into_iter() .fold(0, |acc, c| acc + c.to_digit(10).unwrap() as i32); return format!("{sum:b}"); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_solve() { assert!(solve(1000) == "1"); assert!(solve(150) == "110"); assert!(solve(147) == "1100"); assert!(solve(333) == "1001"); assert!(solve(963) == "10010"); } }
Rust/85
/* Given a non-empty list of integers lst. add the even elements that are at odd indices.. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn add_even_odd(lst: Vec<i32>) -> i32{
let mut sum: i32 = 0; for (indx, elem) in lst.iter().enumerate() { if indx % 2 == 1 { if elem % 2 == 0 { sum += elem } } } return sum; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_add_even_odd() { assert!(add_even_odd(vec![4, 88]) == 88); assert!(add_even_odd(vec![4, 5, 6, 7, 2, 122]) == 122); assert!(add_even_odd(vec![4, 0, 6, 7]) == 0); assert!(add_even_odd(vec![4, 4, 6, 8]) == 12); } }
Rust/86
/* Write a function that takes a string and returns an ordered version of it. Ordered version of string, is a string where all words (separated by space) are replaced by a new word where all the characters arranged in ascending order based on ascii value. Note: You should keep the order of words and blank spaces in the sentence. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn anti_shuffle(s:&str) -> String{
let mut res: String = String::new(); for i in s.split_ascii_whitespace() { let mut str: Vec<char> = i.chars().into_iter().collect(); str.sort_by(|a, b| (*a as u32).cmp(&(*b as u32))); let str_sorted: String = str.into_iter().collect(); res.push_str(&(str_sorted + &" ".to_string())); } res = res.trim_end().to_string(); return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_anti_shuffle() { assert!(anti_shuffle("Hi") == "Hi".to_string()); assert!(anti_shuffle("hello") == "ehllo".to_string()); assert!(anti_shuffle("number") == "bemnru".to_string()); assert!(anti_shuffle("abcd") == "abcd".to_string()); assert!(anti_shuffle("Hello World!!!") == "Hello !!!Wdlor".to_string()); assert!(anti_shuffle("") == "".to_string()); assert!( anti_shuffle("Hi. My name is Mister Robot. How are you?") == ".Hi My aemn is Meirst .Rboot How aer ?ouy".to_string() ); } }
Rust/87
/* You are given a 2 dimensional data, as a nested lists, which is similar to matrix, however, unlike matrices, each row may contain a different number of columns. Given lst, and integer x, find integers x in the list, and return list of tuples, [(x1, y1), (x2, y2) ...] such that each tuple is a coordinate - (row, columns), starting with 0. Sort coordinates initially by rows in ascending order. Also, sort coordinates of the row by columns in descending order. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn get_row(lst:Vec<Vec<i32>>, x:i32) -> Vec<Vec<i32>>{
let mut out: Vec<Vec<i32>> = vec![]; for (indxi, elem1) in lst.iter().enumerate() { for (indxj, _) in elem1.iter().rev().enumerate() { if lst[indxi][indxj] == x { out.push(vec![indxi as i32, indxj as i32]); } } } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_get_row() { assert!( get_row( vec![ vec![1, 2, 3, 4, 5, 6], vec![1, 2, 3, 4, 1, 6], vec![1, 2, 3, 4, 5, 1] ], 1 ) == vec![vec![0, 0], vec![1, 0], vec![1, 4], vec![2, 0], vec![2, 5]] ); assert!( get_row( vec![ vec![1, 2, 3, 4, 5, 6], vec![1, 2, 3, 4, 5, 6], vec![1, 2, 3, 4, 5, 6], vec![1, 2, 3, 4, 5, 6], vec![1, 2, 3, 4, 5, 6], vec![1, 2, 3, 4, 5, 6] ], 2 ) == vec![ vec![0, 1], vec![1, 1], vec![2, 1], vec![3, 1], vec![4, 1], vec![5, 1] ] ); assert!( get_row( vec![ vec![1, 2, 3, 4, 5, 6], vec![1, 2, 3, 4, 5, 6], vec![1, 1, 3, 4, 5, 6], vec![1, 2, 1, 4, 5, 6], vec![1, 2, 3, 1, 5, 6], vec![1, 2, 3, 4, 1, 6], vec![1, 2, 3, 4, 5, 1] ], 1 ) == vec![ vec![0, 0], vec![1, 0], vec![2, 0], vec![2, 1], vec![3, 0], vec![3, 2], vec![4, 0], vec![4, 3], vec![5, 0], vec![5, 4], vec![6, 0], vec![6, 5] ] ); let v: Vec<Vec<i32>> = vec![]; assert!(get_row(vec![], 1) == v); assert!(get_row(vec![vec![1]], 2) == v); assert!(get_row(vec![vec![], vec![1], vec![1, 2, 3]], 3) == vec![vec![2, 2]]); } }
Rust/88
/* In this Kata, you have to sort an array of non-negative integers according to number of ones in their binary representation in ascending order. For similar number of ones, sort based on decimal value. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn sort_array(array:Vec<i32>) -> Vec<i32>{
let mut res: Vec<i32> = array.clone(); if array.len() == 0 { return res; } if (array[0] + array[array.len() - 1]) % 2 == 0 { res.sort(); return res.into_iter().rev().collect(); } else { res.sort(); return res; } }
#[cfg(test)] mod tests { use super::*; #[test] fn test_sort_array() { assert!(sort_array(vec![]) == vec![]); assert!(sort_array(vec![5]) == vec![5]); assert!(sort_array(vec![2, 4, 3, 0, 1, 5]) == vec![0, 1, 2, 3, 4, 5]); assert!(sort_array(vec![2, 4, 3, 0, 1, 5, 6]) == vec![6, 5, 4, 3, 2, 1, 0]); assert!(sort_array(vec![2, 1]) == vec![1, 2]); assert!(sort_array(vec![15, 42, 87, 32, 11, 0]) == vec![0, 11, 15, 32, 42, 87]); assert!(sort_array(vec![21, 14, 23, 11]) == vec![23, 21, 14, 11]); } }
Rust/89
/* Create a function encrypt that takes a string as an argument and returns a string encrypted with the alphabet being rotated. The alphabet should be rotated in a manner such that the letters shift down by two multiplied to two places. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn encrypt(s:&str) -> String{
let d: Vec<char> = "abcdefghijklmnopqrstuvwxyz" .to_string() .chars() .into_iter() .collect(); let mut out: String = String::new(); for c in s.chars() { if d.contains(&c) { let indx: usize = (d.iter().position(|x| c == *x).unwrap() + 2 * 2) % 26; out += &d[indx].to_string(); } else { out += &c.to_string(); } } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_encrypt() { assert!(encrypt("hi") == "lm"); assert!(encrypt("asdfghjkl") == "ewhjklnop"); assert!(encrypt("gf") == "kj"); assert!(encrypt("et") == "ix"); assert!(encrypt("faewfawefaewg") == "jeiajeaijeiak"); assert!(encrypt("hellomyfriend") == "lippsqcjvmirh"); assert!( encrypt("dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh") == "hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl" ); assert!(encrypt("a") == "e"); } }
Rust/90
/* You are given a list of integers. Write a function next_smallest() that returns the 2nd smallest element of the list. Return None if there is no such element. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn next_smallest(lst:Vec<i32>) -> i32{
let mut res = 0; let mut lst_cp = lst.clone(); let mut first: i32 = 0; let mut second: i32 = 0; if lst.iter().min() == None { res = -1; } else { if lst.iter().min() != None { first = *lst.iter().min().unwrap(); let indx = lst.iter().position(|x| *x == first).unwrap(); lst_cp.remove(indx); if lst_cp.iter().min() != None { second = *lst_cp.iter().min().unwrap(); } if first != second { res = second; } else { res = -1; } } } return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_next_smallest() { assert!(next_smallest(vec![1, 2, 3, 4, 5]) == 2); assert!(next_smallest(vec![5, 1, 4, 3, 2]) == 2); assert!(next_smallest(vec![]) == -1); assert!(next_smallest(vec![1, 1]) == -1); assert!(next_smallest(vec![1, 1, 1, 1, 0]) == 1); assert!(next_smallest(vec![-35, 34, 12, -45]) == -35); } }
Rust/91
/* You'll be given a string of words, and your task is to count the number of boredoms. A boredom is a sentence that starts with the word "I". Sentences are delimited by '.', '?' or '!'. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn is_bored(s:&str) -> i32 {
let mut count = 0; let regex = Regex::new(r"[.?!]\s*").expect("Invalid regex"); let sqn: Vec<&str> = regex.split(s).into_iter().collect(); for s in sqn { if s.starts_with("I ") { count += 1; } } return count; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_is_bored() { assert!(is_bored("Hello world") == 0); assert!(is_bored("Is the sky blue?") == 0); assert!(is_bored("I love It !") == 1); assert!(is_bored("bIt") == 0); assert!(is_bored("I feel good today. I will be productive. will kill It") == 2); assert!(is_bored("You and I are going for a walk") == 0); } }
Rust/92
/* Create a function that takes 3 numbers. Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers. Returns false in any other cases. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn any_int(a:f64, b:f64, c:f64) -> bool{
if a.fract() == 0.0 && b.fract() == 0.0 && c.fract() == 0.0 { return a + b == c || a + c == b || b + c == a; } else { return false; } }
#[cfg(test)] mod tests { use super::*; #[test] fn test_any_int() { assert!(any_int(2.0, 3.0, 1.0) == true); assert!(any_int(2.5, 2.0, 3.0) == false); assert!(any_int(1.5, 5.0, 3.5) == false); assert!(any_int(2.0, 6.0, 2.0) == false); assert!(any_int(4.0, 2.0, 2.0) == true); assert!(any_int(2.2, 2.2, 2.2) == false); assert!(any_int(-4.0, 6.0, 2.0) == true); assert!(any_int(2.0, 1.0, 1.0) == true); assert!(any_int(3.0, 4.0, 7.0) == true); assert!(any_int(3.01, 4.0, 7.0) == false); } }
Rust/93
/* Write a function that takes a message, and encodes in such a way that it swaps case of all letters, replaces all vowels in the message with the letter that appears 2 places ahead of that vowel in the english alphabet. Assume only letters. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn encode(message:&str) -> String{
let mut res: String = String::new(); let v: Vec<char> = "aeiouAEIOU".to_string().chars().into_iter().collect(); let d: Vec<char> = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" .to_string() .chars() .into_iter() .collect(); for (indx, elem) in message.chars().into_iter().enumerate() { let mut c = elem.to_string(); if v.contains(&elem) { let indx: usize = d.iter().position(|x| &elem == x).unwrap(); c = d[indx + 2 as usize].to_string(); } if elem.is_uppercase() { c = c.to_lowercase().to_string(); } else { c = c.to_uppercase().to_string(); } res.push_str(&c); } return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_encode() { assert!(encode("TEST") == "tgst"); assert!(encode("Mudasir") == "mWDCSKR"); assert!(encode("YES") == "ygs"); assert!(encode("This is a message") == "tHKS KS C MGSSCGG"); assert!(encode("I DoNt KnOw WhAt tO WrItE") == "k dQnT kNqW wHcT Tq wRkTg"); } }
Rust/94
/* You are given a list of integers. You need to find the largest prime value and return the sum of its digits. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn skjkasdkd(lst:Vec<i32>) -> i32{
let mut largest = 0; for i in 0..lst.len() { if lst[i] > largest { let mut prime = true; let mut j = 2; while j * j <= lst[i] { if lst[i] % j == 0 { prime = false; } j += 1; } if prime { largest = lst[i]; } } } let mut sum: i32 = 0; let mut s: String = String::new(); s = largest.to_string(); for n in s.chars().into_iter() { sum += n.to_digit(10).unwrap() as i32; } return sum; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_skjkasdkd() { assert!( skjkasdkd(vec![ 0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3 ]) == 10 ); assert!( skjkasdkd(vec![ 1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1 ]) == 25 ); assert!( skjkasdkd(vec![ 1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3 ]) == 13 ); assert!(skjkasdkd(vec![0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11); assert!(skjkasdkd(vec![0, 81, 12, 3, 1, 21]) == 3); assert!(skjkasdkd(vec![0, 8, 1, 2, 1, 7]) == 7); assert!(skjkasdkd(vec![8191]) == 19); assert!(skjkasdkd(vec![8191, 123456, 127, 7]) == 19); assert!(skjkasdkd(vec![127, 97, 8192]) == 10); } }
Rust/95
/* Given a dictionary, return True if all keys are strings in lower case or all keys are strings in upper case, else return False. The function should return False is the given dictionary is empty. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn check_dict_case(dict:HashMap<&str, &str>) -> bool{
if dict.is_empty() { return false; } let string_lower: fn(str: &str) -> bool = |str: &str| { return str.chars().into_iter().all(|c| c.is_ascii_lowercase()); }; let string_upper: fn(str: &str) -> bool = |str: &str| { return str.chars().into_iter().all(|c| c.is_ascii_uppercase()); }; let lower: bool = dict.keys().into_iter().all(|str| string_lower(str)); let upper: bool = dict.keys().into_iter().all(|str| string_upper(str)); return lower || upper; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_check_dict_case() { assert!(check_dict_case(HashMap::from([("p", "pineapple"), ("b", "banana")])) == true); assert!( check_dict_case(HashMap::from([ ("p", "pineapple"), ("A", "banana"), ("B", "banana") ])) == false ); assert!( check_dict_case(HashMap::from([ ("p", "pineapple"), ("5", "banana"), ("a", "apple") ])) == false ); assert!( check_dict_case(HashMap::from([ ("Name", "John"), ("Age", "36"), ("City", "Houston") ])) == false ); assert!(check_dict_case(HashMap::from([("STATE", "NC"), ("ZIP", "12345")])) == true); assert!(check_dict_case(HashMap::from([("fruit", "Orange"), ("taste", "Sweet")])) == true); assert!(check_dict_case(HashMap::new()) == false); } }
Rust/96
/* Implement a function that takes an non-negative integer and returns an array of the first n integers that are prime numbers and less than n. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn count_up_to(n:i32) -> Vec<i32> {
let mut primes: Vec<i32> = vec![]; for i in 2..n { let mut is_prime: bool = true; for j in 2..i { if i % j == 0 { is_prime = false; break; } } if is_prime { primes.push(i); } } return primes; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_count_up_to() { assert!(count_up_to(5) == vec![2, 3]); assert!(count_up_to(6) == vec![2, 3, 5]); assert!(count_up_to(7) == vec![2, 3, 5]); assert!(count_up_to(10) == vec![2, 3, 5, 7]); assert!(count_up_to(0) == vec![]); assert!(count_up_to(22) == vec![2, 3, 5, 7, 11, 13, 17, 19]); assert!(count_up_to(1) == vec![]); assert!(count_up_to(18) == vec![2, 3, 5, 7, 11, 13, 17]); assert!(count_up_to(47) == vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]); assert!( count_up_to(101) == vec![ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ] ); } }
Rust/97
/* Complete the function that takes two integers and returns the product of their unit digits. Assume the input is always valid. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn multiply(a:i32, b:i32) -> i32{
return (i32::abs(a) % 10) * (i32::abs(b) % 10); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_multiply() { assert!(multiply(148, 412) == 16); assert!(multiply(19, 28) == 72); assert!(multiply(2020, 1851) == 0); assert!(multiply(14, -15) == 20); assert!(multiply(76, 67) == 42); assert!(multiply(17, 27) == 49); assert!(multiply(0, 1) == 0); assert!(multiply(0, 0) == 0); } }
Rust/98
/* Given a string s, count the number of uppercase vowels in even indices. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn count_upper(s:&str) -> i32 {
let uvowel: &str = "AEIOU"; let mut count: i32 = 0; for (indx, elem) in s.chars().into_iter().enumerate() { if indx % 2 == 0 { if uvowel.contains(elem) { count += 1; } } } return count; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_count_upper() { assert!(count_upper("aBCdEf") == 1); assert!(count_upper("abcdefg") == 0); assert!(count_upper("dBBE") == 0); assert!(count_upper("B") == 0); assert!(count_upper("U") == 1); assert!(count_upper("") == 0); assert!(count_upper("EEEE") == 2); } }
Rust/99
/* Create a function that takes a value (string) representing a number and returns the closest integer to it. If the number is equidistant from two integers, round it away from zero. Note: Rounding away from zero means that if the given number is equidistant from two integers, the one you should return is the one that is the farthest from zero. For example closest_integer("14.5") should return 15 and closest_integer("-14.5") should return -15. *\
use std::{slice::Iter, cmp::{max, self}, mem::replace, collections::{HashSet, HashMap}, ops::Index, ascii::AsciiExt}; use rand::Rng; use regex::Regex; use md5; use std::any::{Any, TypeId}; fn closest_integer(value:&str) -> i32 {
return value.parse::<f64>().unwrap().round() as i32; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_closest_integer() { assert!(closest_integer("10") == 10); assert!(closest_integer("14.5") == 15); assert!(closest_integer("-15.5") == -16); assert!(closest_integer("15.3") == 15); assert!(closest_integer("0") == 0); } }
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
39
Edit dataset card