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/100
/* Given a positive integer n, you have to make a pile of n levels of stones. The first level has n stones. The number of stones in the next level is: - the next odd number if n is odd. - the next even number if n is even. Return the number of stones in each level in a list, where element at index i represents the number of stones in the level (i+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 make_a_pile(n:i32) -> Vec<i32>{
let mut out: Vec<i32> = vec![n]; for i in 1..n { out.push(out[out.len() - 1] + 2); } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_make_a_pile() { assert!(make_a_pile(3) == vec![3, 5, 7]); assert!(make_a_pile(4) == vec![4, 6, 8, 10]); assert!(make_a_pile(5) == vec![5, 7, 9, 11, 13]); assert!(make_a_pile(6) == vec![6, 8, 10, 12, 14, 16]); assert!(make_a_pile(8) == vec![8, 10, 12, 14, 16, 18, 20, 22]); } }
Rust/101
/* You will be given a string of words separated by commas or spaces. Your task is to split the string into words and return an array of the words. *\
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 words_string(s:&str) -> Vec<String> {
return s .to_string() .split(|c: char| c == ',' || c.is_whitespace()) .into_iter() .filter(|x| x != &"") .map(|x| x.to_string()) .collect(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_words_string() { assert!(words_string("Hi, my name is John") == vec!["Hi", "my", "name", "is", "John"]); assert!( words_string("One, two, three, four, five, six") == vec!["One", "two", "three", "four", "five", "six"] ); assert!(words_string("Hi, my name") == vec!["Hi", "my", "name"]); assert!( words_string("One,, two, three, four, five, six,") == vec!["One", "two", "three", "four", "five", "six"] ); let v_empty: Vec<String> = vec![]; assert!(words_string("") == v_empty); assert!(words_string("ahmed , gamal") == vec!["ahmed", "gamal"]); } }
Rust/102
/* This function takes two positive numbers x and y and returns the biggest even integer number that is in the range [x, y] inclusive. If there's no such number, then the function should 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 choose_num(x:i32, y:i32) -> i32{
if y < x { return -1; } if y == x && y % 2 == 1 { return -1; } if y % 2 == 1 { return y - 1; } return y; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_choose_num() { assert!(choose_num(12, 15) == 14); assert!(choose_num(13, 12) == -1); assert!(choose_num(33, 12354) == 12354); assert!(choose_num(6, 29) == 28); assert!(choose_num(27, 10) == -1); assert!(choose_num(7, 7) == -1); assert!(choose_num(546, 546) == 546); } }
Rust/103
/* You are given two positive integers n and m, and your task is to compute the average of the integers from n through m (including n and m). Round the answer to the nearest integer and convert that to binary. If n is greater than m, 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 rounded_avg(n:i32, m:i32) -> String{
if n > m { return "-1".to_string(); }; let mut num: i32 = (m + n) / 2; let mut out: String = String::from(""); while num > 0 { out = (num % 2).to_string() + &out; num = num / 2; } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_rounded_avg() { assert!(rounded_avg(1, 5) == "11"); assert!(rounded_avg(7, 13) == "1010"); assert!(rounded_avg(964, 977) == "1111001010"); assert!(rounded_avg(996, 997) == "1111100100"); assert!(rounded_avg(560, 851) == "1011000001"); assert!(rounded_avg(185, 546) == "101101101"); assert!(rounded_avg(362, 496) == "110101101"); assert!(rounded_avg(350, 902) == "1001110010"); assert!(rounded_avg(197, 233) == "11010111"); assert!(rounded_avg(7, 5) == "-1"); assert!(rounded_avg(5, 1) == "-1"); assert!(rounded_avg(5, 5) == "101"); } }
Rust/104
/* Given a list of positive integers x. return a sorted list of all elements that hasn't any even digit. Note: Returned list should be sorted in increasing 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 unique_digits(x:Vec<i32>) -> Vec<i32>{
let mut res: Vec<i32> = vec![]; for (_, elem) in x.into_iter().enumerate() { let mut elem_cp: i32 = elem; let mut u: bool = true; if elem == 0 { u = false; } while elem_cp > 0 && u { if elem_cp % 2 == 0 { u = false; } elem_cp = elem_cp / 10; } if u { res.push(elem) }; } res.sort(); return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_unique_digits() { assert!(unique_digits(vec![15, 33, 1422, 1]) == vec![1, 15, 33]); assert!(unique_digits(vec![152, 323, 1422, 10]) == vec![]); assert!(unique_digits(vec![12345, 2033, 111, 151]) == vec![111, 151]); assert!(unique_digits(vec![135, 103, 31]) == vec![31, 135]); } }
Rust/105
/* Given an array of integers, sort the integers that are between 1 and 9 inclusive, reverse the resulting array, and then replace each digit by its corresponding name from "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". *\
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 by_length(arr:Vec<i32>) -> Vec<String>{
let mut res: Vec<String> = vec![]; let mut arr_cp: Vec<i32> = arr.clone(); arr_cp.sort(); arr_cp.reverse(); let map: HashMap<i32, &str> = HashMap::from([ (0, "Zero"), (1, "One"), (2, "Two"), (3, "Three"), (4, "Four"), (5, "Five"), (6, "Six"), (7, "Seven"), (8, "Eight"), (9, "Nine"), ]); for elem in arr_cp { if elem >= 1 && elem <= 9 { res.push(map.get(&elem).unwrap().to_string()); } } return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_by_length() { assert!( by_length(vec![2, 1, 1, 4, 5, 8, 2, 3]) == vec!["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] ); let v_empty: Vec<String> = vec![]; assert!(by_length(vec![]) == v_empty); assert!(by_length(vec![1, -1, 55]) == vec!["One"]); assert!(by_length(vec![1, -1, 3, 2]) == vec!["Three", "Two", "One"]); assert!(by_length(vec![9, 4, 8]) == vec!["Nine", "Eight", "Four"]); } }
Rust/106
/* Implement the function f that takes n as a parameter, and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even or the sum of numbers from 1 to i otherwise. i starts from 1. the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). *\
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 f(n:i32) -> Vec<i32>{
let mut sum: i32 = 0; let mut prod: i32 = 1; let mut out: Vec<i32> = vec![]; for i in 1..n + 1 { sum += i; prod *= i; if i % 2 == 0 { out.push(prod); } else { out.push(sum) }; } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_f() { assert!(f(5) == vec![1, 2, 6, 24, 15]); assert!(f(7) == vec![1, 2, 6, 24, 15, 720, 28]); assert!(f(1) == vec![1]); assert!(f(3) == vec![1, 2, 6]); } }
Rust/107
/* Given a positive integer n, return a tuple that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Note: 1. 1 <= n <= 10^3 2. returned tuple has the number of even and odd integer palindromes respectively. *\
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 even_odd_palindrome(n: i32) -> (i32, i32) {
let mut even = 0; let mut odd = 0; for i in 1..n + 1 { let mut w: String = i.to_string(); let mut p: String = w.chars().rev().collect(); if w == p && i % 2 == 1 { odd += 1; } if w == p && i % 2 == 0 { even += 1; } } (even, odd) }
#[cfg(test)] mod tests { use super::*; #[test] fn test_even_odd_palindrome() { assert!(even_odd_palindrome(123) == (8, 13)); assert!(even_odd_palindrome(12) == (4, 6)); assert!(even_odd_palindrome(3) == (1, 2)); assert!(even_odd_palindrome(63) == (6, 8)); assert!(even_odd_palindrome(25) == (5, 6)); assert!(even_odd_palindrome(19) == (4, 6)); assert!(even_odd_palindrome(9) == (4, 5)); assert!(even_odd_palindrome(1) == (0, 1)); } }
Rust/108
/* Write a function count_nums which takes an array of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. *\
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_nums(n:Vec<i32>) -> i32{
let mut num: i32 = 0; for nmbr in n { if nmbr > 0 { num += 1; } else { let mut sum: i32 = 0; let mut w: i32; w = i32::abs(nmbr); while w >= 10 { sum += w % 10; w = w / 10; } sum -= w; if sum > 0 { num += 1; } } } return num; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_count_nums() { assert!(count_nums(vec![]) == 0); assert!(count_nums(vec![-1, -2, 0]) == 0); assert!(count_nums(vec![1, 1, 2, -2, 3, 4, 5]) == 6); assert!(count_nums(vec![1, 6, 9, -6, 0, 1, 5]) == 5); assert!(count_nums(vec![1, 100, 98, -7, 1, -1]) == 4); assert!(count_nums(vec![12, 23, 34, -45, -56, 0]) == 5); assert!(count_nums(vec![-0, 1]) == 1); assert!(count_nums(vec![1]) == 1); } }
Rust/109
/* We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The numbers in the array will be randomly ordered. Your task is to determine if it is possible to get an array sorted in non-decreasing order by performing the following operation on the given array: You are allowed to perform right shift operation any number of times. One right shift operation means shifting all elements of the array by one position in the right direction. The last element of the array will be moved to the starting position in the array i.e. 0th index. If it is possible to obtain the sorted array by performing the above operation then return True else return False. If the given array is empty then return True. Note: The given list is guaranteed to have unique elements. *\
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 move_one_ball(arr:Vec<i32>) -> bool{
let mut num = 0; if arr.len() == 0 { return true; } for i in 1..arr.len() { if arr[i] < arr[i - 1] { num += 1; } } if arr[arr.len() - 1] > arr[0] { num += 1; } if num < 2 { return true; } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_move_one_ball() { assert!(move_one_ball(vec![3, 4, 5, 1, 2]) == true); assert!(move_one_ball(vec![3, 5, 10, 1, 2]) == true); assert!(move_one_ball(vec![4, 3, 1, 2]) == false); assert!(move_one_ball(vec![3, 5, 4, 1, 2]) == false); assert!(move_one_ball(vec![]) == true); } }
Rust/110
/* In this problem, you will implement a function that takes two lists of numbers, and determines whether it is possible to perform an exchange of elements between them to make lst1 a list of only even numbers. There is no limit on the number of exchanged elements between lst1 and lst2. If it is possible to exchange elements between the lst1 and lst2 to make all the elements of lst1 to be even, return "YES". Otherwise, return "NO". It is assumed that the input lists will be non-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 exchange(lst1:Vec<i32>, lst2:Vec<i32>) -> String{
let mut num = 0; for i in 0..lst1.len() { if lst1[i] % 2 == 0 { num += 1; } } for i in 0..lst2.len() { if lst2[i] % 2 == 0 { num += 1; } } if num >= lst1.len() { return "YES".to_string(); } return "NO".to_string(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_exchange() { assert!(exchange(vec![1, 2, 3, 4], vec![1, 2, 3, 4]) == "YES"); assert!(exchange(vec![1, 2, 3, 4], vec![1, 5, 3, 4]) == "NO"); assert!(exchange(vec![1, 2, 3, 4], vec![2, 1, 4, 3]) == "YES"); assert!(exchange(vec![5, 7, 3], vec![2, 6, 4]) == "YES"); assert!(exchange(vec![5, 7, 3], vec![2, 6, 3]) == "NO"); assert!(exchange(vec![3, 2, 6, 1, 8, 9], vec![3, 5, 5, 1, 1, 1]) == "NO"); assert!(exchange(vec![100, 200], vec![200, 200]) == "YES"); } }
Rust/111
/* Given a string representing a space separated lowercase letters, return a dictionary of the letter with the most repetition and containing the corresponding count. If several letters have the same occurrence, return all of them. *\
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 histogram(test:&str) -> HashMap<char, i32>{
let mut res: HashMap<char, i32> = HashMap::new(); if test == "" { return res; } for c in test.split_ascii_whitespace() { if res.contains_key(&c.chars().next().unwrap()) { res.entry(c.chars().next().unwrap()).and_modify(|n| { *n += 1; }); } else { res.insert(c.chars().next().unwrap(), 1); } } let max: i32 = *res.values().max().unwrap(); let non_maxs: Vec<char> = res .keys() .filter(|k: &&char| *res.get(k).unwrap() != max) .map(|c| *c) .collect(); non_maxs.iter().for_each(|c| { res.remove(c); }); return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_histogram() { assert!(histogram("a b b a") == HashMap::from([('a', 2), ('b', 2)])); assert!(histogram("a b c a b") == HashMap::from([('a', 2), ('b', 2)])); assert!( histogram("a b c d g") == HashMap::from([('a', 1), ('b', 1), ('c', 1), ('d', 1), ('g', 1)]) ); assert!(histogram("r t g") == HashMap::from([('r', 1), ('t', 1), ('g', 1)])); assert!(histogram("b b b b a") == HashMap::from([('b', 4)])); assert!(histogram("r t g") == HashMap::from([('r', 1), ('t', 1), ('g', 1)])); assert!(histogram("") == HashMap::new()); assert!(histogram("a") == HashMap::from([(('a', 1))])); } }
Rust/112
/* Task We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c then check if the result string is palindrome. A string is called palindrome if it reads the same backward as forward. You should return a tuple containing the result string and True/False for the check. *\
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 reverse_delete(s:&str, c:&str) -> Vec<String> {
let mut n = String::new(); for i in 0..s.len() { if !c.contains(s.chars().nth(i).unwrap()) { n.push(s.chars().nth(i).unwrap()); } } if n.len() == 0 { return vec![n, "True".to_string()]; } let w: String = n.chars().rev().collect(); if w == n { return vec![n, "True".to_string()]; } return vec![n, "False".to_string()]; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_reverse_delete() { assert!(reverse_delete("abcde", "ae") == ["bcd", "False"]); assert!(reverse_delete("abcdef", "b") == ["acdef", "False"]); assert!(reverse_delete("abcdedcba", "ab") == ["cdedc", "True"]); assert!(reverse_delete("dwik", "w") == ["dik", "False"]); assert!(reverse_delete("a", "a") == ["", "True"]); assert!(reverse_delete("abcdedcba", "") == ["abcdedcba", "True"]); assert!(reverse_delete("abcdedcba", "v") == ["abcdedcba", "True"]); assert!(reverse_delete("vabba", "v") == ["abba", "True"]); assert!(reverse_delete("mamma", "mia") == ["", "True"]); } }
Rust/113
/* Given a list of strings, where each string consists of only digits, return a list. Each element i of the output should be "the number of odd elements in the string i of the input." where all the i's should be replaced by the number of odd digits in the i'th string of 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 odd_count(lst:Vec<&str>) -> Vec<String>{
let mut out: Vec<String> = Vec::new(); for i in 0..lst.len() { let mut sum = 0; for j in 0..lst[i].len() { if lst[i].chars().nth(j).unwrap() >= '0' && lst[i].chars().nth(j).unwrap() <= '9' && lst[i].chars().nth(j).unwrap().to_digit(10).unwrap() % 2 == 1 { sum += 1; } } let mut s = "the number of odd elements in the string i of the input.".to_string(); let mut s2 = "".to_string(); for j in 0..s.len() { if s.chars().nth(j).unwrap() == 'i' { s2.push_str(&sum.to_string()); } else { s2.push(s.chars().nth(j).unwrap()); } } out.push(s2); } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_odd_count() { assert!( odd_count(vec!["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."] ); assert!( odd_count(vec!["3", "11111111"]) == [ "the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput." ] ); assert!( odd_count(vec!["271", "137", "314"]) == [ "the number of odd elements 2n the str2ng 2 of the 2nput.", "the number of odd elements 3n the str3ng 3 of the 3nput.", "the number of odd elements 2n the str2ng 2 of the 2nput." ] ); } }
Rust/114
/* Given an array of integers nums, find the minimum sum of any non-empty sub-array of nums. *\
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 min_sub_array_sum(nums: Vec<i64>) -> i64 {
let mut current = nums[0]; let mut min = nums[0]; for i in 1..nums.len() { if current < 0 { current = current + nums[i]; } else { current = nums[i]; } if current < min { min = current; } } min }
#[cfg(test)] mod tests { use super::*; #[test] fn test_min_sub_array_sum() { assert!(min_sub_array_sum(vec![2, 3, 4, 1, 2, 4]) == 1); assert!(min_sub_array_sum(vec![-1, -2, -3]) == -6); assert!(min_sub_array_sum(vec![-1, -2, -3, 2, -10]) == -14); assert!(min_sub_array_sum(vec![-9999999999999999]) == -9999999999999999); assert!(min_sub_array_sum(vec![0, 10, 20, 1000000]) == 0); assert!(min_sub_array_sum(vec![-1, -2, -3, 10, -5]) == -6); assert!(min_sub_array_sum(vec![100, -1, -2, -3, 10, -5]) == -6); assert!(min_sub_array_sum(vec![10, 11, 13, 8, 3, 4]) == 3); assert!(min_sub_array_sum(vec![100, -33, 32, -1, 0, -2]) == -33); assert!(min_sub_array_sum(vec![-10]) == -10); assert!(min_sub_array_sum(vec![7]) == 7); assert!(min_sub_array_sum(vec![1, -1]) == -1); } }
Rust/115
/* You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents a single unit of water. Each well has a corresponding bucket that can be used to extract water from it, and all buckets have the same capacity. Your task is to use the buckets to empty the wells. Output the number of times you need to lower the buckets. *\
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 max_fill(grid:Vec<Vec<i32>>, capacity:i32) -> i32{
let mut out: i32 = 0; for i in 0..grid.len() { let mut sum: i32 = 0; for j in 0..grid[i].len() { sum += grid[i][j]; } if sum > 0 { out += (sum - 1) / capacity + 1; } } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_max_fill() { assert!( max_fill( vec![vec![0, 0, 1, 0], vec![0, 1, 0, 0], vec![1, 1, 1, 1]], 1 ) == 6 ); assert!( max_fill( vec![ vec![0, 0, 1, 1], vec![0, 0, 0, 0], vec![1, 1, 1, 1], vec![0, 1, 1, 1] ], 2 ) == 5 ); assert!(max_fill(vec![vec![0, 0, 0], vec![0, 0, 0]], 5) == 0); assert!(max_fill(vec![vec![1, 1, 1, 1], vec![1, 1, 1, 1]], 2) == 4); assert!(max_fill(vec![vec![1, 1, 1, 1], vec![1, 1, 1, 1]], 9) == 2); } }
Rust/116
/* 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_1(arr:Vec<i32>) -> Vec<i32>{
let mut arr_cp = arr.clone(); let mut bin = vec![]; let mut m; for i in 0..arr_cp.len() { let mut b = 0; let mut n = arr_cp[i].abs(); while n > 0 { b += n % 2; n = n / 2; } bin.push(b); } for i in 0..arr_cp.len() { for j in 1..arr_cp.len() { if bin[j] < bin[j - 1] || (bin[j] == bin[j - 1] && arr_cp[j] < arr_cp[j - 1]) { m = arr_cp[j]; arr_cp[j] = arr_cp[j - 1]; arr_cp[j - 1] = m; m = bin[j]; bin[j] = bin[j - 1]; bin[j - 1] = m; } } } return arr_cp; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_sort_array_1() { assert!(sort_array_1(vec![1, 5, 2, 3, 4]) == vec![1, 2, 4, 3, 5]); assert!(sort_array_1(vec![-2, -3, -4, -5, -6]) == vec![-4, -2, -6, -5, -3]); assert!(sort_array_1(vec![1, 0, 2, 3, 4]) == vec![0, 1, 2, 4, 3]); assert!(sort_array_1(vec![]) == vec![]); assert!( sort_array_1(vec![2, 5, 77, 4, 5, 3, 5, 7, 2, 3, 4]) == vec![2, 2, 4, 4, 3, 3, 5, 5, 5, 7, 77] ); assert!(sort_array_1(vec![3, 6, 44, 12, 32, 5]) == vec![32, 3, 5, 6, 12, 44]); assert!(sort_array_1(vec![2, 4, 8, 16, 32]) == vec![2, 4, 8, 16, 32]); assert!(sort_array_1(vec![2, 4, 8, 16, 32]) == vec![2, 4, 8, 16, 32]); } }
Rust/117
/* Given a string s and a natural number n, you have been tasked to implement a function that returns a list of all words from string s that contain exactly n consonants, in order these words appear in the string s. If the string s is empty then the function should return an empty list. Note: you may assume the input string contains only letters and spaces. *\
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 select_words(s:&str, n:i32) -> Vec<String>{
let vowels = "aeiouAEIOU"; let mut current = String::new(); let mut out = Vec::new(); let mut numc = 0; let mut s = s.to_string(); s.push(' '); for i in 0..s.len() { if s.chars().nth(i).unwrap() == ' ' { if numc == n { out.push(current); } current = String::new(); numc = 0; } else { current.push(s.chars().nth(i).unwrap()); if (s.chars().nth(i).unwrap() >= 'A' && s.chars().nth(i).unwrap() <= 'Z') || (s.chars().nth(i).unwrap() >= 'a' && s.chars().nth(i).unwrap() <= 'z') { if !vowels.contains(s.chars().nth(i).unwrap()) { numc += 1; } } } } out }
#[cfg(test)] mod tests { use super::*; #[test] fn test_select_words() { assert_eq!(select_words("Mary had a little lamb", 4), vec!["little"]); assert_eq!( select_words("Mary had a little lamb", 3), vec!["Mary", "lamb"] ); let v_empty: Vec<&str> = vec![]; assert_eq!(select_words("simple white space", 2), v_empty); assert_eq!(select_words("Hello world", 4), vec!["world"]); assert_eq!(select_words("Uncle sam", 3), vec!["Uncle"]); assert_eq!(select_words("", 4), v_empty); assert_eq!(select_words("a b c d e f", 1), vec!["b", "c", "d", "f"]); } }
Rust/118
/* You are given a word. Your task is to find the closest vowel that stands between two consonants from the right side of the word (case sensitive). Vowels in the beginning and ending doesn't count. Return empty string if you didn't find any vowel met the above condition. You may assume that the given string contains English letter only. *\
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_closest_vowel(word: &str) -> String {
fn get_closest_vowel(word: &str) -> String { let vowels = "AEIOUaeiou"; let mut out = "".to_string(); for i in (1..word.len() - 1).rev() { if vowels.contains(word.chars().nth(i).unwrap()) { if !vowels.contains(word.chars().nth(i + 1).unwrap()) { if !vowels.contains(word.chars().nth(i - 1).unwrap()) { out.push(word.chars().nth(i).unwrap()); return out; } } } } out }
#[cfg(test)] mod tests { use super::*; #[test] fn test_get_closest_vowel() { assert_eq!(get_closest_vowel("yogurt"), "u"); assert_eq!(get_closest_vowel("full"), "u"); assert_eq!(get_closest_vowel("easy"), ""); assert_eq!(get_closest_vowel("eAsy"), ""); assert_eq!(get_closest_vowel("ali"), ""); assert_eq!(get_closest_vowel("bad"), "a"); assert_eq!(get_closest_vowel("most"), "o"); assert_eq!(get_closest_vowel("ab"), ""); assert_eq!(get_closest_vowel("ba"), ""); assert_eq!(get_closest_vowel("quick"), ""); assert_eq!(get_closest_vowel("anime"), "i"); assert_eq!(get_closest_vowel("Asia"), ""); assert_eq!(get_closest_vowel("Above"), "o"); } }
Rust/119
/* You are given a list of two strings, both strings consist of open parentheses '(' or close parentheses ')' only. Your job is to check if it is possible to concatenate the two strings in some order, that the resulting string will be good. A string S is considered to be good if and only if all parentheses in S are balanced. For example: the string '(())()' is good, while the string '())' is not. Return 'Yes' if there's a way to make a good string, and return 'No' 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 match_parens(lst: Vec<&str>) -> &str {
fn match_parens(lst: Vec<&str>) -> &str { let l1 = lst[0].to_string() + lst[1]; let mut count = 0; let mut can = true; for i in 0..l1.len() { if l1.chars().nth(i).unwrap() == '(' { count += 1; } if l1.chars().nth(i).unwrap() == ')' { count -= 1; } if count < 0 { can = false; } } if count != 0 { return "No"; } if can == true { return "Yes"; } let l1 = lst[1].to_string() + lst[0]; let mut can = true; for i in 0..l1.len() { if l1.chars().nth(i).unwrap() == '(' { count += 1; } if l1.chars().nth(i).unwrap() == ')' { count -= 1; } if count < 0 { can = false; } } if can == true { return "Yes"; } return "No"; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_match_parens() { assert_eq!(match_parens(vec!["()(", ")"]), "Yes"); assert_eq!(match_parens(vec![")", ")"]), "No"); assert_eq!(match_parens(vec!["(()(())", "())())"],), "No"); assert_eq!(match_parens(vec![")())", "(()()("]), "Yes"); assert_eq!(match_parens(vec!["(())))", "(()())(("]), "Yes"); assert_eq!(match_parens(vec!["()", "())"],), "No"); assert_eq!(match_parens(vec!["(()(", "()))()"]), "Yes"); assert_eq!(match_parens(vec!["((((", "((())"],), "No"); assert_eq!(match_parens(vec![")(()", "(()("]), "No"); assert_eq!(match_parens(vec![")(", ")("]), "No"); assert_eq!(match_parens(vec!["(", ")"]), "Yes"); assert_eq!(match_parens(vec![")", "("]), "Yes"); } }
Rust/120
/* Given an array arr of integers and a positive integer k, return a sorted list of length k with the maximum k numbers in arr. Note: 1. The length of the array will be in the range of [1, 1000]. 2. The elements in the array will be in the range of [-1000, 1000]. 3. 0 <= k <= len(arr) *\
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_120(arr: Vec<i32>, k: i32) -> Vec<i32> {
let mut arr = arr; arr.sort(); let mut arr_res: Vec<i32> = arr.iter().rev().take(k as usize).cloned().collect(); arr_res.sort(); return arr_res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_maximum_120() { assert_eq!(maximum_120(vec![-3, -4, 5], 3), vec![-4, -3, 5]); assert_eq!(maximum_120(vec![4, -4, 4], 2), vec![4, 4]); assert_eq!(maximum_120(vec![-3, 2, 1, 2, -1, -2, 1], 1), vec![2]); assert_eq!( maximum_120(vec![123, -123, 20, 0, 1, 2, -3], 3), vec![2, 20, 123] ); assert_eq!( maximum_120(vec![-123, 20, 0, 1, 2, -3], 4), vec![0, 1, 2, 20] ); assert_eq!( maximum_120(vec![5, 15, 0, 3, -13, -8, 0], 7), vec![-13, -8, 0, 0, 3, 5, 15] ); assert_eq!(maximum_120(vec![-1, 0, 2, 5, 3, -10], 2), vec![3, 5]); assert_eq!(maximum_120(vec![1, 0, 5, -7], 1), vec![5]); assert_eq!(maximum_120(vec![4, -4], 2), vec![-4, 4]); assert_eq!(maximum_120(vec![-10, 10], 2), vec![-10, 10]); assert_eq!(maximum_120(vec![1, 2, 3, -23, 243, -400, 0], 0), vec![]); } }
Rust/121
/* Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions. *\
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 solutions(lst: Vec<i32>) -> i32 {
let mut sum = 0; for (indx, elem) in lst.iter().enumerate() { if indx % 2 == 0 { if elem % 2 == 1 { sum += elem; } } } return sum; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_solutions() { assert_eq!(solutions(vec![5, 8, 7, 1]), 12); assert_eq!(solutions(vec![3, 3, 3, 3, 3]), 9); assert_eq!(solutions(vec![30, 13, 24, 321]), 0); assert_eq!(solutions(vec![5, 9]), 5); assert_eq!(solutions(vec![2, 4, 8]), 0); assert_eq!(solutions(vec![30, 13, 23, 32]), 23); assert_eq!(solutions(vec![3, 13, 2, 9]), 3); } }
Rust/122
/* Given a non-empty array of integers arr and an integer k, return the sum of the elements with at most two digits from the first k elements of arr. Constraints: 1. 1 <= len(arr) <= 100 2. 1 <= k <= len(arr) *\
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_elements(arr: Vec<i32>, k: i32) -> i32 {
let mut sum = 0; for i in 0..k { if arr[i as usize] >= -99 && arr[i as usize] <= 99 { sum += arr[i as usize]; } } sum }
#[cfg(test)] mod tests { use super::*; #[test] fn test_add_elements() { assert_eq!(add_elements(vec![1, -2, -3, 41, 57, 76, 87, 88, 99], 3), -4); assert_eq!(add_elements(vec![111, 121, 3, 4000, 5, 6], 2), 0); assert_eq!(add_elements(vec![11, 21, 3, 90, 5, 6, 7, 8, 9], 4), 125); assert_eq!(add_elements(vec![111, 21, 3, 4000, 5, 6, 7, 8, 9], 4), 24); assert_eq!(add_elements(vec![1], 1), 1); } }
Rust/123
/* Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence. The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half of the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. Note: 1. Collatz(1) is [1]. 2. returned list sorted in increasing 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_odd_collatz(n: i32) -> Vec<i32> {
let mut out = vec![1]; let mut n = n; while n != 1 { if n % 2 == 1 { out.push(n); n = n * 3 + 1; } else { n = n / 2; } } out.sort(); out }
#[cfg(test)] mod tests { use super::*; #[test] fn test_get_odd_collatz() { assert_eq!(get_odd_collatz(14), vec![1, 5, 7, 11, 13, 17]); assert_eq!(get_odd_collatz(5), vec![1, 5]); assert_eq!(get_odd_collatz(12), vec![1, 3, 5]); assert_eq!(get_odd_collatz(1), vec![1]); } }
Rust/124
/* You have to write a function which validates a given date string and returns True if the date is valid otherwise False. The date is valid if all of the following rules are satisfied: 1. The date string is not empty. 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. 3. The months should not be less than 1 or higher than 12. 4. The date should be in the format: mm-dd-yyyy *\
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 valid_date(date: &str) -> bool {
let mut mm = 0; let mut dd = 0; let mut yy = 0; let mut i = 0; if date.len() != 10 { return false; } for i in 0..10 { if i == 2 || i == 5 { if date.chars().nth(i).unwrap() != '-' { return false; } } else if date.chars().nth(i).unwrap() < '0' || date.chars().nth(i).unwrap() > '9' { return false; } } mm = date[0..2].parse::<i32>().unwrap(); dd = date[3..5].parse::<i32>().unwrap(); yy = date[6..10].parse::<i32>().unwrap(); if mm < 1 || mm > 12 { return false; } if dd < 1 || dd > 31 { return false; } if dd == 31 && (mm == 4 || mm == 6 || mm == 9 || mm == 11 || mm == 2) { return false; } if dd == 30 && mm == 2 { return false; } return true; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_valid_date() { assert_eq!(valid_date("03-11-2000"), true); assert_eq!(valid_date("15-01-2012"), false); assert_eq!(valid_date("04-0-2040"), false); assert_eq!(valid_date("06-04-2020"), true); assert_eq!(valid_date("01-01-2007"), true); assert_eq!(valid_date("03-32-2011"), false); assert_eq!(valid_date(""), false); assert_eq!(valid_date("04-31-3000"), false); assert_eq!(valid_date("06-06-2005"), true); assert_eq!(valid_date("21-31-2000"), false); assert_eq!(valid_date("04-12-2003"), true); assert_eq!(valid_date("04122003"), false); assert_eq!(valid_date("20030412"), false); assert_eq!(valid_date("2003-04"), false); assert_eq!(valid_date("2003-04-12"), false); assert_eq!(valid_date("04-2003"), false); } }
Rust/125
/* Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 *\
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 split_words(txt: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new(); let alphabet: HashMap<char, i32> = HashMap::from([ ('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('h', 7), ('i', 8), ('j', 9), ('k', 10), ('l', 11), ('m', 12), ('n', 13), ('o', 14), ('p', 15), ('q', 16), ('r', 17), ('s', 18), ('t', 19), ('u', 20), ('v', 21), ('w', 22), ('x', 23), ('y', 24), ('z', 25), ]); if txt.contains(' ') { out = txt .split_whitespace() .into_iter() .map(|c| c.to_string()) .collect(); } else if txt.contains(',') { out = txt.split(',').into_iter().map(|c| c.to_string()).collect(); } else { let count = txt .chars() .into_iter() .filter(|c| c.is_ascii_lowercase()) .filter(|c| alphabet.get(c).unwrap() % 2 == 1) .count(); out.push(count.to_string()); } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_split_words() { assert_eq!(split_words("Hello world!"), vec!["Hello", "world!"]); assert_eq!(split_words("Hello,world!"), vec!["Hello", "world!"]); assert_eq!(split_words("Hello world,!"), vec!["Hello", "world,!"]); assert_eq!( split_words("Hello,Hello,world !"), vec!["Hello,Hello,world", "!"] ); assert_eq!(split_words("abcdef"), vec!["3"]); assert_eq!(split_words("aaabb"), vec!["2"]); assert_eq!(split_words("aaaBb"), vec!["1"]); assert_eq!(split_words(""), vec!["0"]); } }
Rust/126
/* Given a list of numbers, return whether or not they are sorted in ascending order. If list has more than 1 duplicate of the same number, return False. Assume no negative numbers and only 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 is_sorted(lst: Vec<i32>) -> bool {
for i in 1..lst.len() { if lst[i] < lst[i - 1] { return false; } if i >= 2 && lst[i] == lst[i - 1] && lst[i] == lst[i - 2] { return false; } } true }
#[cfg(test)] mod tests { use super::*; #[test] fn test_is_sorted() { assert_eq!(is_sorted(vec![5]), true); assert_eq!(is_sorted(vec![1, 2, 3, 4, 5]), true); assert_eq!(is_sorted(vec![1, 3, 2, 4, 5]), false); assert_eq!(is_sorted(vec![1, 2, 3, 4, 5, 6]), true); assert_eq!(is_sorted(vec![1, 2, 3, 4, 5, 6, 7]), true); assert_eq!(is_sorted(vec![1, 3, 2, 4, 5, 6, 7]), false); assert_eq!(is_sorted(vec![]), true); assert_eq!(is_sorted(vec![1]), true); assert_eq!(is_sorted(vec![3, 2, 1]), false); assert_eq!(is_sorted(vec![1, 2, 2, 2, 3, 4]), false); assert_eq!(is_sorted(vec![1, 2, 3, 3, 3, 4]), false); assert_eq!(is_sorted(vec![1, 2, 2, 3, 3, 4]), true); assert_eq!(is_sorted(vec![1, 2, 3, 4]), true); } }
Rust/127
/* You are given two intervals, where each interval is a pair of integers. For example, interval = (start, end) = (1, 2). The given intervals are closed which means that the interval (start, end) includes both start and end. For each given interval, it is assumed that its start is less or equal its end. Your task is to determine whether the length of intersection of these two intervals is a prime number. Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3) which its length is 1, which not a prime number. If the length of the intersection is a prime number, return "YES", otherwise, return "NO". If the two intervals don't intersect, return "NO". *\
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 intersection(interval1: Vec<i32>, interval2: Vec<i32>) -> String {
let inter1 = std::cmp::max(interval1[0], interval2[0]); let inter2 = std::cmp::min(interval1[1], interval2[1]); let l = inter2 - inter1; if l < 2 { return "NO".to_string(); } for i in 2..l { if l % i == 0 { return "NO".to_string(); } } return "YES".to_string(); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_intersection() { assert_eq!(intersection(vec![1, 2], vec![2, 3]), "NO"); assert_eq!(intersection(vec![-1, 1], vec![0, 4]), "NO"); assert_eq!(intersection(vec![-3, -1], vec![-5, 5]), "YES"); assert_eq!(intersection(vec![-2, 2], vec![-4, 0]), "YES"); assert_eq!(intersection(vec![-11, 2], vec![-1, -1]), "NO"); assert_eq!(intersection(vec![1, 2], vec![3, 5]), "NO"); assert_eq!(intersection(vec![1, 2], vec![1, 2]), "NO"); assert_eq!(intersection(vec![-2, -2], vec![-3, -2]), "NO"); } }
Rust/128
/* You are given an array arr of integers and you need to return sum of magnitudes of integers multiplied by product of all signs of each number in the array, represented by 1, -1 or 0. Note: return None for empty arr. *\
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 prod_signs(arr: Vec<i32>) -> i32 {
if arr.is_empty() { return -32768; } let mut sum = 0; let mut prods = 1; for i in arr { sum += i.abs(); if i == 0 { prods = 0; } if i < 0 { prods = -prods; } } sum * prods }
#[cfg(test)] mod tests { use super::*; #[test] fn test_prod_signs() { assert_eq!(prod_signs(vec![1, 2, 2, -4]), -9); assert_eq!(prod_signs(vec![0, 1]), 0); assert_eq!(prod_signs(vec![1, 1, 1, 2, 3, -1, 1]), -10); assert_eq!(prod_signs(vec![]), -32768); assert_eq!(prod_signs(vec![2, 4, 1, 2, -1, -1, 9]), 20); assert_eq!(prod_signs(vec![-1, 1, -1, 1]), 4); assert_eq!(prod_signs(vec![-1, 1, 1, 1]), -4); assert_eq!(prod_signs(vec![-1, 1, 1, 0]), 0); } }
Rust/129
/* Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. *\
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 min_path(grid: Vec<Vec<i32>>, k: i32) -> Vec<i32> {
let mut out: Vec<i32> = vec![]; let mut x = 0; let mut y = 0; let mut min: i32 = (grid.len() * grid.len()) as i32; for i in 0..grid.len() { for j in 0..grid[i].len() { if grid[i][j] == 1 { x = i; y = j; } } } if x > 0 && grid[x - 1][y] < min { min = grid[x - 1][y]; } if x < grid.len() - 1 && grid[x + 1][y] < min { min = grid[x + 1][y]; } if y > 0 && grid[x][y - 1] < min { min = grid[x][y - 1]; } if y < grid.len() - 1 && grid[x][y + 1] < min { min = grid[x][y + 1]; } let mut out = vec![]; for i in 0..k { if i % 2 == 0 { out.push(1); } else { out.push(min); } } out }
#[cfg(test)] mod tests { use super::*; #[test] fn test_min_path() { assert_eq!( min_path(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]], 3), vec![1, 2, 1] ); assert_eq!( min_path(vec![vec![5, 9, 3], vec![4, 1, 6], vec![7, 8, 2]], 1), vec![1] ); assert_eq!( min_path( vec![ vec![1, 2, 3, 4], vec![5, 6, 7, 8], vec![9, 10, 11, 12], vec![13, 14, 15, 16] ], 4 ), vec![1, 2, 1, 2] ); assert_eq!( min_path( vec![ vec![6, 4, 13, 10], vec![5, 7, 12, 1], vec![3, 16, 11, 15], vec![8, 14, 9, 2] ], 7 ), vec![1, 10, 1, 10, 1, 10, 1] ); assert_eq!( min_path( vec![ vec![8, 14, 9, 2], vec![6, 4, 13, 15], vec![5, 7, 1, 12], vec![3, 10, 11, 16] ], 5 ), vec![1, 7, 1, 7, 1] ); assert_eq!( min_path( vec![ vec![11, 8, 7, 2], vec![5, 16, 14, 4], vec![9, 3, 15, 6], vec![12, 13, 10, 1] ], 9 ), vec![1, 6, 1, 6, 1, 6, 1, 6, 1] ); assert_eq!( min_path( vec![ vec![12, 13, 10, 1], vec![9, 3, 15, 6], vec![5, 16, 14, 4], vec![11, 8, 7, 2] ], 12 ), vec![1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6] ); assert_eq!( min_path(vec![vec![2, 7, 4], vec![3, 1, 5], vec![6, 8, 9]], 8), vec![1, 3, 1, 3, 1, 3, 1, 3] ); assert_eq!( min_path(vec![vec![6, 1, 5], vec![3, 8, 9], vec![2, 7, 4]], 8), vec![1, 5, 1, 5, 1, 5, 1, 5] ); assert_eq!( min_path(vec![vec![1, 2], vec![3, 4]], 10), vec![1, 2, 1, 2, 1, 2, 1, 2, 1, 2] ); assert_eq!( min_path(vec![vec![1, 3], vec![3, 2]], 10), vec![1, 3, 1, 3, 1, 3, 1, 3, 1, 3] ); } }
Rust/130
/* Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in the last couple centuries. However, what people don't know is Tribonacci sequence. Tribonacci sequence is defined by the recurrence: tri(1) = 3 tri(n) = 1 + n / 2, if n is even. tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd. For example: tri(2) = 1 + (2 / 2) = 2 tri(4) = 3 tri(3) = tri(2) + tri(1) + tri(4) = 2 + 3 + 3 = 8 You are given a non-negative integer number n, you have to a return a list of the first n + 1 numbers of the Tribonacci 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 tri(n: i32) -> Vec<i32> {
let mut out = vec![1, 3]; if n == 0 { return vec![1]; } for i in 2..=n { if i % 2 == 0 { out.push(1 + i / 2); } else { out.push(out[(i - 1) as usize] + out[(i - 2) as usize] + 1 + (i + 1) / 2); } } out }
#[cfg(test)] mod tests { use super::*; #[test] fn test_tri() { assert!(tri(3) == vec![1, 3, 2, 8]); assert!(tri(4) == vec![1, 3, 2, 8, 3]); assert!(tri(5) == vec![1, 3, 2, 8, 3, 15]); assert!(tri(6) == vec![1, 3, 2, 8, 3, 15, 4]); assert!(tri(7) == vec![1, 3, 2, 8, 3, 15, 4, 24]); assert!(tri(8) == vec![1, 3, 2, 8, 3, 15, 4, 24, 5]); assert!(tri(9) == vec![1, 3, 2, 8, 3, 15, 4, 24, 5, 35]); assert!( tri(20) == vec![1, 3, 2, 8, 3, 15, 4, 24, 5, 35, 6, 48, 7, 63, 8, 80, 9, 99, 10, 120, 11] ); assert!(tri(0) == vec![1]); assert!(tri(1) == vec![1, 3]); } }
Rust/131
/* Given a positive integer n, return the product of the odd digits. Return 0 if all digits are even. *\
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 digits(n: i32) -> i32 {
let mut prod: i32 = 1; let mut has = 0; let s = n.to_string(); for i in 0..s.len() { if s.chars().nth(i).unwrap().to_digit(10).unwrap() % 2 == 1 { has = 1; prod = prod * (s.chars().nth(i).unwrap().to_digit(10).unwrap()) as i32; } } if has == 0 { return 0; } prod }
#[cfg(test)] mod tests { use super::*; #[test] fn test_digits() { assert_eq!(digits(5), 5); assert_eq!(digits(54), 5); assert_eq!(digits(120), 1); assert_eq!(digits(5014), 5); assert_eq!(digits(98765), 315); assert_eq!(digits(5576543), 2625); assert_eq!(digits(2468), 0); } }
Rust/132
/* Create a function that takes a string as input which contains only square brackets. The function should return True if and only if there is a valid subsequence of brackets where at least one bracket in the subsequence is nested. *\
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_nested(str: &str) -> bool {
let mut count = 0; let mut maxcount = 0; for i in 0..str.len() { if str.chars().nth(i).unwrap() == '[' { count += 1; } if str.chars().nth(i).unwrap() == ']' { count -= 1; } if count < 0 { count = 0; } if count > maxcount { maxcount = count; } if count <= maxcount - 2 { return true; } } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_is_nested() { assert_eq!(is_nested("[[]]"), true); assert_eq!(is_nested("[]]]]]]][[[[[]"), false); assert_eq!(is_nested("[][]"), false); assert_eq!(is_nested("[]"), false); assert_eq!(is_nested("[[[[]]]]"), true); assert_eq!(is_nested("[]]]]]]]]]]"), false); assert_eq!(is_nested("[][][[]]"), true); assert_eq!(is_nested("[[]"), false); assert_eq!(is_nested("[]]"), false); assert_eq!(is_nested("[[]][["), true); assert_eq!(is_nested("[[][]]"), true); assert_eq!(is_nested(""), false); assert_eq!(is_nested("[[[[[[[["), false); assert_eq!(is_nested("]]]]]]]]"), false); } }
Rust/133
/* " This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. *\
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_squares(lst: Vec<f32>) -> i32 {
let mut sum: f32 = 0.0; for i in 0..lst.len() { sum = sum + (lst[i].ceil() * lst[i].ceil()); } sum as i32 }
#[cfg(test)] mod tests { use super::*; #[test] fn test_sum_squares() { assert_eq!(sum_squares(vec![1.0, 2.0, 3.0]), 14); assert_eq!(sum_squares(vec![1.0, 2.0, 3.0]), 14); assert_eq!(sum_squares(vec![1.0, 3.0, 5.0, 7.0]), 84); assert_eq!(sum_squares(vec![1.4, 4.2, 0.0]), 29); assert_eq!(sum_squares(vec![-2.4, 1.0, 1.0]), 6); assert_eq!(sum_squares(vec![100.0, 1.0, 15.0, 2.0]), 10230); assert_eq!(sum_squares(vec![10000.0, 10000.0]), 200000000); assert_eq!(sum_squares(vec![-1.4, 4.6, 6.3]), 75); assert_eq!(sum_squares(vec![-1.4, 17.9, 18.9, 19.9]), 1086); assert_eq!(sum_squares(vec![0.0]), 0); assert_eq!(sum_squares(vec![-1.0]), 1); assert_eq!(sum_squares(vec![-1.0, 1.0, 0.0]), 2); } }
Rust/134
/* Create a function that returns True if the last character of a given string is an alphabetical character and is not a part of a word, and False otherwise. Note: "word" is a group of characters separated by space. *\
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_if_last_char_is_a_letter(txt: &str) -> bool {
if txt.len() == 0 { return false; } let chr = txt.chars().last().unwrap(); if chr < 'A' || (chr > 'Z' && chr < 'a') || chr > 'z' { return false; } if txt.len() == 1 { return true; } let chr = txt.chars().nth(txt.len() - 2).unwrap(); if (chr >= 'A' && chr <= 'Z') || (chr >= 'a' && chr <= 'z') { return false; } true }
#[cfg(test)] mod tests { use super::*; #[test] fn test_check_if_last_char_is_a_letter() { assert_eq!(check_if_last_char_is_a_letter("apple"), false); assert_eq!(check_if_last_char_is_a_letter("apple pi e"), true); assert_eq!(check_if_last_char_is_a_letter("eeeee"), false); assert_eq!(check_if_last_char_is_a_letter("A"), true); assert_eq!(check_if_last_char_is_a_letter("Pumpkin pie "), false); assert_eq!(check_if_last_char_is_a_letter("Pumpkin pie 1"), false); assert_eq!(check_if_last_char_is_a_letter(""), false); assert_eq!(check_if_last_char_is_a_letter("eeeee e "), false); assert_eq!(check_if_last_char_is_a_letter("apple pie"), false); } }
Rust/135
/* Create a function which returns the largest index of an element which is not greater than or equal to the element immediately preceding it. If no such element exists then return -1. The given array will not contain duplicate values. *\
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 can_arrange(arr: Vec<i32>) -> i32 {
let mut max: i32 = -1; for i in 0..arr.len() { if arr[i] <= i as i32 { max = i as i32; } } max }
#[cfg(test)] mod tests { use super::*; #[test] fn test_can_arrange() { assert_eq!(can_arrange(vec![1, 2, 4, 3, 5]), 3); assert_eq!(can_arrange(vec![1, 2, 4, 5]), -1); assert_eq!(can_arrange(vec![1, 4, 2, 5, 6, 7, 8, 9, 10]), 2); assert_eq!(can_arrange(vec![4, 8, 5, 7, 3]), 4); assert_eq!(can_arrange(vec![]), -1); } }
Rust/136
/* Create a function that returns a tuple (a, b), where 'a' is the largest of negative integers, and 'b' is the smallest of positive integers in a list. If there is no negative or positive integers, return them as None. *\
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_smallest_integers(lst: Vec<i32>) -> Vec<i32> {
let mut maxneg = 0; let mut minpos = 0; for i in 0..lst.len() { if lst[i] < 0 && (maxneg == 0 || lst[i] > maxneg) { maxneg = lst[i]; } if lst[i] > 0 && (minpos == 0 || lst[i] < minpos) { minpos = lst[i]; } } vec![maxneg, minpos] }
#[cfg(test)] mod tests { use super::*; #[test] fn test_largest_smallest_integers() { assert_eq!( largest_smallest_integers(vec![2, 4, 1, 3, 5, 7]), vec![0, 1] ); assert_eq!( largest_smallest_integers(vec![2, 4, 1, 3, 5, 7, 0]), vec![0, 1] ); assert_eq!( largest_smallest_integers(vec![1, 3, 2, 4, 5, 6, -2]), vec![-2, 1] ); assert_eq!( largest_smallest_integers(vec![4, 5, 3, 6, 2, 7, -7]), vec![-7, 2] ); assert_eq!( largest_smallest_integers(vec![7, 3, 8, 4, 9, 2, 5, -9]), vec![-9, 2] ); assert_eq!(largest_smallest_integers(vec![]), vec![0, 0]); assert_eq!(largest_smallest_integers(vec![0]), vec![0, 0]); assert_eq!(largest_smallest_integers(vec![-1, -3, -5, -6]), vec![-1, 0]); assert_eq!( largest_smallest_integers(vec![-1, -3, -5, -6, 0]), vec![-1, 0] ); assert_eq!( largest_smallest_integers(vec![-6, -4, -4, -3, 1]), vec![-3, 1] ); assert_eq!( largest_smallest_integers(vec![-6, -4, -4, -3, -100, 1]), vec![-3, 1] ); } }
Rust/137
/* Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . 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 compare_one<'a>(a:&'a dyn Any, b:&'a dyn Any) -> RtnType<String,f64,i32>{
let a_f64 = Any_to_f64(a); let b_f64 = Any_to_f64(b); if a_f64 > b_f64 { return original_type(a); } if a_f64 < b_f64 { return original_type(b); } else { return RtnType::String("None".to_string()); } } #[derive(Debug, PartialEq)] pub enum RtnType<S, F, I> { Empty(), String(S), Float(F), Int(I), } fn Any_to_f64(a: &dyn Any) -> f64 { let mut a_f64 = 0.0; if a.downcast_ref::<f64>() == None { match a.downcast_ref::<&str>() { Some(as_string) => { a_f64 = as_string.parse::<f64>().unwrap(); } None => {} } match a.downcast_ref::<i32>() { Some(as_i32) => { a_f64 = *as_i32 as f64; } None => {} } } else { a_f64 = *a.downcast_ref::<f64>().unwrap(); } return a_f64; } fn original_type(a: &dyn Any) -> RtnType<String, f64, i32> { let mut res = RtnType::Empty(); match a.downcast_ref::<&str>() { Some(as_string) => { res = RtnType::String(as_string.parse::<String>().unwrap()); } None => {} } match a.downcast_ref::<i32>() { Some(as_i32) => { res = RtnType::Int(*as_i32); } None => {} } match a.downcast_ref::<f64>() { Some(as_f64) => res = RtnType::Float(*as_f64), None => {} } return res; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_compare_one() { assert_eq!(compare_one(&1, &2), RtnType::Int(2)); assert_eq!(compare_one(&1, &2.5), RtnType::Float(2.5)); assert_eq!(compare_one(&2, &3), RtnType::Int(3)); assert_eq!(compare_one(&5, &6), RtnType::Int(6)); assert_eq!(compare_one(&1, &"2.3"), RtnType::String("2.3".to_string())); assert_eq!(compare_one(&"5.1", &"6"), RtnType::String("6".to_string())); assert_eq!(compare_one(&"1", &"2"), RtnType::String("2".to_string())); assert_eq!(compare_one(&"1", &1), RtnType::String("None".to_string())); } }
Rust/138
/* Evaluate whether the given number n can be written as the sum of exactly 4 positive even 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 is_equal_to_sum_even(n: i32) -> bool {
if n % 2 == 0 && n >= 8 { return true; } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_is_equal_to_sum_even() { assert_eq!(is_equal_to_sum_even(4), false); assert_eq!(is_equal_to_sum_even(6), false); assert_eq!(is_equal_to_sum_even(8), true); assert_eq!(is_equal_to_sum_even(10), true); assert_eq!(is_equal_to_sum_even(11), false); assert_eq!(is_equal_to_sum_even(12), true); assert_eq!(is_equal_to_sum_even(13), false); assert_eq!(is_equal_to_sum_even(16), true); } }
Rust/139
/* The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 The function will receive an integer as input and should return the special factorial of this integer. *\
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 special_factorial(n: i32) -> i64 {
let mut fact = 1; let mut bfact: i64 = 1; for i in 1..=n { fact = fact * i; bfact = bfact * fact as i64; } bfact }
#[cfg(test)] mod tests { use super::*; #[test] fn test_special_factorial() { assert_eq!(special_factorial(4), 288); assert_eq!(special_factorial(5), 34560); assert_eq!(special_factorial(7), 125411328000); assert_eq!(special_factorial(1), 1); } }
Rust/140
/* Given a string text, replace all spaces in it with underscores, and if a string has more than 2 consecutive spaces, then replace all consecutive spaces with - *\
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 fix_spaces(text: &str) -> String {
let mut out = String::new(); let mut spacelen = 0; for c in text.chars() { if c == ' ' { spacelen += 1; } else { if spacelen == 1 { out.push('_'); } if spacelen == 2 { out.push_str("__"); } if spacelen > 2 { out.push('-'); } spacelen = 0; out.push(c); } } if spacelen == 1 { out.push('_'); } if spacelen == 2 { out.push_str("__"); } if spacelen > 2 { out.push('-'); } out }
#[cfg(test)] mod tests { use super::*; #[test] fn test_fix_spaces() { assert_eq!(fix_spaces("Example"), "Example"); assert_eq!(fix_spaces("Mudasir Hanif "), "Mudasir_Hanif_"); assert_eq!( fix_spaces("Yellow Yellow Dirty Fellow"), "Yellow_Yellow__Dirty__Fellow" ); assert_eq!(fix_spaces("Exa mple"), "Exa-mple"); assert_eq!(fix_spaces(" Exa 1 2 2 mple"), "-Exa_1_2_2_mple"); } }
Rust/141
/* Create a function which takes a string representing a file's name, and returns 'Yes' if the the file's name is valid, and returns 'No' otherwise. A file's name is considered to be valid if and only if all the following conditions are met: - There should not be more than three digits ('0'-'9') in the file's name. - The file's name contains exactly one dot '.' - The substring before the dot should not be empty, and it starts with a letter from the latin alphapet ('a'-'z' and 'A'-'Z'). - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] *\
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 file_name_check(file_name: &str) -> &str {
let mut numdigit = 0; let mut numdot = 0; if file_name.len() < 5 { return "No"; } let w = file_name.chars().nth(0).unwrap(); if w < 'A' || (w > 'Z' && w < 'a') || w > 'z' { return "No"; } let last = &file_name[file_name.len() - 4..]; if last != ".txt" && last != ".exe" && last != ".dll" { return "No"; } for c in file_name.chars() { if c >= '0' && c <= '9' { numdigit += 1; } if c == '.' { numdot += 1; } } if numdigit > 3 || numdot != 1 { return "No"; } return "Yes"; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_file_name_check() { assert_eq!(file_name_check("example.txt"), "Yes"); assert_eq!(file_name_check("1example.dll"), "No"); assert_eq!(file_name_check("s1sdf3.asd"), "No"); assert_eq!(file_name_check("K.dll"), "Yes"); assert_eq!(file_name_check("MY16FILE3.exe"), "Yes"); assert_eq!(file_name_check("His12FILE94.exe"), "No"); assert_eq!(file_name_check("_Y.txt"), "No"); assert_eq!(file_name_check("?aREYA.exe"), "No"); assert_eq!(file_name_check("/this_is_valid.dll"), "No"); assert_eq!(file_name_check("this_is_valid.wow"), "No"); assert_eq!(file_name_check("this_is_valid.txt"), "Yes"); assert_eq!(file_name_check("this_is_valid.txtexe"), "No"); assert_eq!(file_name_check("#this2_i4s_5valid.ten"), "No"); assert_eq!(file_name_check("@this1_is6_valid.exe"), "No"); assert_eq!(file_name_check("this_is_12valid.6exe4.txt"), "No"); assert_eq!(file_name_check("all.exe.txt"), "No"); assert_eq!(file_name_check("I563_No.exe"), "Yes"); assert_eq!(file_name_check("Is3youfault.txt"), "Yes"); assert_eq!(file_name_check("no_one#knows.dll"), "Yes"); assert_eq!(file_name_check("1I563_Yes3.exe"), "No"); assert_eq!(file_name_check("I563_Yes3.txtt"), "No"); assert_eq!(file_name_check("final..txt"), "No"); assert_eq!(file_name_check("final132"), "No"); assert_eq!(file_name_check("_f4indsartal132."), "No"); assert_eq!(file_name_check(".txt"), "No"); assert_eq!(file_name_check("s."), "No"); } }
Rust/142
/* " This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. *\
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_squares_142(lst: Vec<i32>) -> i32 {
let mut sum = 0; for i in 0..lst.len() { if i % 3 == 0 { sum += lst[i] * lst[i]; } else if i % 4 == 0 { sum += lst[i] * lst[i] * lst[i]; } else { sum += lst[i]; } } return sum; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_sum_squares_142() { assert_eq!(sum_squares_142(vec![1, 2, 3]), 6); assert_eq!(sum_squares_142(vec![1, 4, 9]), 14); assert_eq!(sum_squares_142(vec![]), 0); assert_eq!(sum_squares_142(vec![1, 1, 1, 1, 1, 1, 1, 1, 1]), 9); assert_eq!( sum_squares_142(vec![-1, -1, -1, -1, -1, -1, -1, -1, -1]), -3 ); assert_eq!(sum_squares_142(vec![0]), 0); assert_eq!(sum_squares_142(vec![-1, -5, 2, -1, -5]), -126); assert_eq!(sum_squares_142(vec![-56, -99, 1, 0, -2]), 3030); assert_eq!(sum_squares_142(vec![-1, 0, 0, 0, 0, 0, 0, 0, -1]), 0); assert_eq!( sum_squares_142(vec![ -16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37 ]), -14196 ); assert_eq!( sum_squares_142(vec![ -1, -3, 17, -1, -15, 13, -1, 14, -14, -12, -5, 14, -14, 6, 13, 11, 16, 16, 4, 10 ]), -1448 ); } }
Rust/143
/* You are given a string representing a sentence, the sentence contains some words separated by a space, and you have to return a string that contains the words from the original sentence, whose lengths are prime numbers, the order of the words in the new string should be the same as the original one. Constraints: * 1 <= len(sentence) <= 100 * sentence contains 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 words_in_sentence(sentence: &str) -> String {
let mut out = String::new(); let mut current = String::new(); let mut sentence = sentence.to_string(); sentence.push(' '); for i in 0..sentence.len() { if sentence.chars().nth(i).unwrap() != ' ' { current.push(sentence.chars().nth(i).unwrap()); } else { let mut isp = true; let l = current.len(); if l < 2 { isp = false; } for j in 2..(l as f64).sqrt() as usize + 1 { if l % j == 0 { isp = false; } } if isp { out.push_str(&current); out.push(' '); } current = String::new(); } } if out.len() > 0 { out.pop(); } out }
#[cfg(test)] mod tests { use super::*; #[test] fn test_words_in_sentence() { assert_eq!(words_in_sentence("This is a test"), "is"); assert_eq!(words_in_sentence("lets go for swimming"), "go for"); assert_eq!( words_in_sentence("there is no place available here"), "there is no place" ); assert_eq!(words_in_sentence("Hi I am Hussein"), "Hi am Hussein"); assert_eq!(words_in_sentence("go for it"), "go for it"); assert_eq!(words_in_sentence("here"), ""); assert_eq!(words_in_sentence("here is"), "is"); } }
Rust/144
/* Your task is to implement a function that will simplify the expression x * n. The function returns True if x * n evaluates to a whole number and False otherwise. Both x and n, are string representation of a fraction, and have the following format, <numerator>/<denominator> where both numerator and denominator are positive whole numbers. You can assume that x, and n are valid fractions, and do not have zero as denominator. *\
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 simplify(x: &str, n: &str) -> bool {
let mut a = 0; let mut b = 0; let mut c = 0; let mut d = 0; let mut i = 0; for i in 0..x.len() { if x.chars().nth(i).unwrap() == '/' { a = x .chars() .take(i) .collect::<String>() .parse::<i32>() .unwrap(); b = x .chars() .skip(i + 1) .collect::<String>() .parse::<i32>() .unwrap(); } } for i in 0..n.len() { if n.chars().nth(i).unwrap() == '/' { c = n .chars() .take(i) .collect::<String>() .parse::<i32>() .unwrap(); d = n .chars() .skip(i + 1) .collect::<String>() .parse::<i32>() .unwrap(); } } if (a * c) % (b * d) == 0 { return true; } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_simplify() { assert_eq!(simplify("1/5", "5/1"), true); assert_eq!(simplify("1/6", "2/1"), false); assert_eq!(simplify("5/1", "3/1"), true); assert_eq!(simplify("7/10", "10/2"), false); assert_eq!(simplify("2/10", "50/10"), true); assert_eq!(simplify("7/2", "4/2"), true); assert_eq!(simplify("11/6", "6/1"), true); assert_eq!(simplify("2/3", "5/2"), false); assert_eq!(simplify("5/2", "3/5"), false); assert_eq!(simplify("2/4", "8/4"), true); assert_eq!(simplify("2/4", "4/2"), true); assert_eq!(simplify("1/5", "5/1"), true); assert_eq!(simplify("1/5", "1/5"), false); } }
Rust/145
/* Write a function which sorts the given list of integers in ascending order according to the sum of their digits. Note: if there are several items with similar sum of their digits, order them based on their index in original 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 order_by_points(arr: Vec<i32>) -> Vec<i32> {
let mut result = arr.clone(); result.sort_by_key(|&x| (sum_of_digits(x))); result } pub fn sum_of_digits(n: i32) -> i32 { let mut sum = 0; let mut n = n; if n < 0 { let right = n / 10; let mut left; if right != 0 { left = n % 10; left = -1 * left; } else { left = n % 10; } sum = right + left; return sum; } while n > 0 { sum += n % 10; n /= 10; } sum }
#[cfg(test)] mod tests { use super::*; #[test] fn test_order_by_points() { assert_eq!( order_by_points(vec![1, 11, -1, -11, -12]), vec![-1, -11, 1, -12, 11] ); assert_eq!( order_by_points(vec![ 1234, 423, 463, 145, 2, 423, 423, 53, 6, 37, 3457, 3, 56, 0, 46 ]), vec![0, 2, 3, 6, 53, 423, 423, 423, 1234, 145, 37, 46, 56, 463, 3457] ); assert_eq!(order_by_points(vec![]), vec![]); assert_eq!( order_by_points(vec![1, -11, -32, 43, 54, -98, 2, -3]), vec![-3, -32, -98, -11, 1, 2, 43, 54] ); assert_eq!( order_by_points(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), vec![1, 10, 2, 11, 3, 4, 5, 6, 7, 8, 9] ); assert_eq!( order_by_points(vec![0, 6, 6, -76, -21, 23, 4]), vec![-76, -21, 0, 4, 23, 6, 6] ); } }
Rust/146
/* Write a function that takes an array of numbers as input and returns the number of elements in the array that are greater than 10 and both first and last digits of a number are odd (1, 3, 5, 7, 9). *\
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 special_filter(nums: Vec<i32>) -> i32 {
let mut num = 0; for i in 0..nums.len() { if nums[i] > 10 { let w = nums[i].to_string(); if w.chars().nth(0).unwrap().to_digit(10).unwrap() % 2 == 1 && w.chars().last().unwrap().to_digit(10).unwrap() % 2 == 1 { num += 1; } } } num }
#[cfg(test)] mod tests { use super::*; #[test] fn test_special_filter() { assert_eq!(special_filter(vec![5, -2, 1, -5]), 0); assert_eq!(special_filter(vec![15, -73, 14, -15]), 1); assert_eq!(special_filter(vec![33, -2, -3, 45, 21, 109]), 2); assert_eq!(special_filter(vec![43, -12, 93, 125, 121, 109]), 4); assert_eq!(special_filter(vec![71, -2, -33, 75, 21, 19]), 3); assert_eq!(special_filter(vec![1]), 0); assert_eq!(special_filter(vec![]), 0); } }
Rust/147
/* You are given a positive integer n. You have to create an integer array a of length n. For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. *\
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_matrix_triples(n: i32) -> i32 {
let mut a = vec![]; let mut sum = vec![vec![0, 0, 0]]; let mut sum2 = vec![vec![0, 0, 0]]; for i in 1..=n { a.push((i * i - i + 1) % 3); sum.push(sum[sum.len() - 1].clone()); sum[i as usize][a[i as usize - 1] as usize] += 1; } for times in 1..3 { for i in 1..=n { sum2.push(sum2[sum2.len() - 1].clone()); if i >= 1 { for j in 0..=2 { sum2[i as usize][(a[i as usize - 1] + j) as usize % 3] += sum[i as usize - 1][j as usize]; } } } sum = sum2.clone(); sum2 = vec![vec![0, 0, 0]]; } return sum[n as usize][0]; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_get_matrix_triples() { assert_eq!(get_matrix_triples(5), 1); assert_eq!(get_matrix_triples(6), 4); assert_eq!(get_matrix_triples(10), 36); assert_eq!(get_matrix_triples(100), 53361); } }
Rust/148
/* There are eight planets in our solar system: the closerst to the Sun is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, Uranus, Neptune. Write a function that takes two planet names as strings planet1 and planet2. The function should return a tuple containing all planets whose orbits are located between the orbit of planet1 and the orbit of planet2, sorted by the proximity to the sun. The function should return an empty tuple if planet1 or planet2 are not correct planet names. *\
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 bf(planet1: &str, planet2: &str) -> Vec<String> {
let planets = vec![ "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", ]; let mut pos1: i32 = -1; let mut pos2: i32 = -1; let mut m; for m in 0..planets.len() { if planets[m] == planet1 { pos1 = m as i32; } if planets[m] == planet2 { pos2 = m as i32; } } if pos1 == -1 || pos2 == -1 { return vec![]; } if pos1 > pos2 { m = pos1; pos1 = pos2; pos2 = m; } let mut out = vec![]; for m in pos1 + 1..pos2 { out.push(planets[m as usize].to_string()); } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_bf() { assert_eq!(bf("Jupiter", "Neptune"), vec!["Saturn", "Uranus"]); assert_eq!(bf("Earth", "Mercury"), vec!["Venus"]); assert_eq!( bf("Mercury", "Uranus"), vec!["Venus", "Earth", "Mars", "Jupiter", "Saturn"] ); assert_eq!( bf("Neptune", "Venus"), vec!["Earth", "Mars", "Jupiter", "Saturn", "Uranus"] ); let v_empty: Vec<&str> = vec![]; assert_eq!(bf("Earth", "Earth"), v_empty); assert_eq!(bf("Mars", "Earth"), v_empty); assert_eq!(bf("Jupiter", "Makemake"), v_empty); } }
Rust/149
/* Write a function that accepts a list of strings as a parameter, deletes the strings that have odd lengths from it, and returns the resulted list with a sorted order, The list is always a list of strings and never an array of numbers, and it may contain duplicates. The order of the list should be ascending by length of each word, and you should return the list sorted by that rule. If two words have the same length, sort the list alphabetically. The function should return a list of strings in sorted order. You may assume that all words will have the same length. *\
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 sorted_list_sum(lst: Vec<&str>) -> Vec<&str> {
let mut out: Vec<&str> = Vec::new(); for i in 0..lst.len() { if lst[i].len() % 2 == 0 { out.push(lst[i]); } } out.sort(); for i in 0..out.len() { for j in 1..out.len() { if out[j].len() < out[j - 1].len() { let mid = out[j]; out[j] = out[j - 1]; out[j - 1] = mid; } } } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_sorted_list_sum() { assert_eq!(sorted_list_sum(vec!["aa", "a", "aaa"]), vec!["aa"]); assert_eq!( sorted_list_sum(vec!["school", "AI", "asdf", "b"]), vec!["AI", "asdf", "school"] ); let v_empty: Vec<&str> = vec![]; assert_eq!(sorted_list_sum(vec!["d", "b", "c", "a"]), v_empty); assert_eq!( sorted_list_sum(vec!["d", "dcba", "abcd", "a"]), vec!["abcd", "dcba"] ); assert_eq!( sorted_list_sum(vec!["AI", "ai", "au"]), vec!["AI", "ai", "au"] ); assert_eq!(sorted_list_sum(vec!["a", "b", "b", "c", "c", "a"]), v_empty); assert_eq!( sorted_list_sum(vec!["aaaa", "bbbb", "dd", "cc"]), vec!["cc", "dd", "aaaa", "bbbb"] ); } }
Rust/150
/* A simple program which should return the value of x if n is a prime number and should return the value of y 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 x_or_y(n: i32, x: i32, y: i32) -> i32 {
let mut isp = true; if n < 2 { isp = false; } for i in 2..=n / 2 { if n % i == 0 { isp = false; } } if isp { return x; } return y; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_x_or_y() { assert_eq!(x_or_y(7, 34, 12), 34); assert_eq!(x_or_y(15, 8, 5), 5); assert_eq!(x_or_y(3, 33, 5212), 33); assert_eq!(x_or_y(1259, 3, 52), 3); assert_eq!(x_or_y(7919, -1, 12), -1); assert_eq!(x_or_y(3609, 1245, 583), 583); assert_eq!(x_or_y(91, 56, 129), 129); assert_eq!(x_or_y(6, 34, 1234), 1234); assert_eq!(x_or_y(1, 2, 0), 0); assert_eq!(x_or_y(2, 2, 0), 2); } }
Rust/151
/* Given a list of numbers, return the sum of squares of the numbers in the list that are odd. Ignore numbers that are negative or not integers. If the input list is empty, return 0. *\
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 double_the_difference(lst: Vec<f32>) -> i64 {
let mut sum: i64 = 0; for i in 0..lst.len() { if (lst[i] - lst[i].round()).abs() < 1e-4 { if lst[i] > 0.0 && (lst[i].round() as i64) % 2 == 1 { sum += (lst[i].round() as i64) * (lst[i].round() as i64); } } } return sum; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_double_the_difference() { assert_eq!(double_the_difference(vec![]), 0); assert_eq!(double_the_difference(vec![5.0, 4.0]), 25); assert_eq!(double_the_difference(vec![0.1, 0.2, 0.3]), 0); assert_eq!(double_the_difference(vec![-10.0, -20.0, -30.0]), 0); assert_eq!(double_the_difference(vec![-1.0, -2.0, 8.0]), 0); assert_eq!(double_the_difference(vec![0.2, 3.0, 5.0]), 34); let mut lst = vec![]; let mut odd_sum = 0; for i in -99..100 { lst.push(i as f32); if i > 0 && i % 2 == 1 { odd_sum += i * i; } } assert_eq!(double_the_difference(lst), odd_sum); } }
Rust/152
/* I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to determine if a person correctly guessed the results of a number of matches. You are given two arrays of scores and guesses of equal length, where each index shows a match. Return an array of the same length denoting how far off each guess was. If they have guessed correctly, the value is 0, and if not, the value is the absolute difference between the guess and the score. *\
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 compare(game: Vec<i32>, guess: Vec<i32>) -> Vec<i32> {
let mut out: Vec<i32> = Vec::new(); for i in 0..game.len() { out.push(i32::abs(game[i] - guess[i])); } return out; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_compare() { assert_eq!( compare(vec![1, 2, 3, 4, 5, 1], vec![1, 2, 3, 4, 2, -2]), vec![0, 0, 0, 0, 3, 3] ); assert_eq!( compare(vec![0, 5, 0, 0, 0, 4], vec![4, 1, 1, 0, 0, -2]), vec![4, 4, 1, 0, 0, 6] ); assert_eq!( compare(vec![1, 2, 3, 4, 5, 1], vec![1, 2, 3, 4, 2, -2]), vec![0, 0, 0, 0, 3, 3] ); assert_eq!( compare(vec![0, 0, 0, 0, 0, 0], vec![0, 0, 0, 0, 0, 0]), vec![0, 0, 0, 0, 0, 0] ); assert_eq!(compare(vec![1, 2, 3], vec![-1, -2, -3]), vec![2, 4, 6]); assert_eq!( compare(vec![1, 2, 3, 5], vec![-1, 2, 3, 4]), vec![2, 0, 0, 1] ); } }
Rust/153
/* You will be given the name of a class (a string) and a list of extensions. The extensions are to be used to load additional classes to the class. The strength of the extension is as follows: Let CAP be the number of the uppercase letters in the extension's name, and let SM be the number of lowercase letters in the extension's name, the strength is given by the fraction CAP - SM. You should find the strongest extension and return a string in this format: ClassName.StrongestExtensionName. If there are two or more extensions with the same strength, you should choose the one that comes first in the list. For example, if you are given "Slices" as the class and a list of the extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension (its strength is -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 strongest_extension(class_name: &str, extensions: Vec<&str>) -> String {
let mut strongest = ""; let mut max = -1000; for i in 0..extensions.len() { let mut strength = 0; for j in 0..extensions[i].len() { let chr = extensions[i].chars().nth(j).unwrap(); if chr >= 'A' && chr <= 'Z' { strength += 1; } if chr >= 'a' && chr <= 'z' { strength -= 1; } } if strength > max { max = strength; strongest = extensions[i]; } } format!("{}.{}", class_name, strongest) }
#[cfg(test)] mod tests { use super::*; #[test] fn test_strongest_extension() { assert_eq!( strongest_extension("Watashi", vec!["tEN", "niNE", "eIGHt8OKe"]), "Watashi.eIGHt8OKe" ); assert_eq!( strongest_extension("Boku123", vec!["nani", "NazeDa", "YEs.WeCaNe", "32145tggg"]), "Boku123.YEs.WeCaNe" ); assert_eq!( strongest_extension( "__YESIMHERE", vec!["t", "eMptY", "(nothing", "zeR00", "NuLl__", "123NoooneB321"] ), "__YESIMHERE.NuLl__" ); assert_eq!( strongest_extension("K", vec!["Ta", "TAR", "t234An", "cosSo"]), "K.TAR" ); assert_eq!( strongest_extension("__HAHA", vec!["Tab", "123", "781345", "-_-"]), "__HAHA.123" ); assert_eq!( strongest_extension( "YameRore", vec!["HhAas", "okIWILL123", "WorkOut", "Fails", "-_-"] ), "YameRore.okIWILL123" ); assert_eq!( strongest_extension("finNNalLLly", vec!["Die", "NowW", "Wow", "WoW"]), "finNNalLLly.WoW" ); assert_eq!(strongest_extension("_", vec!["Bb", "91245"]), "_.Bb"); assert_eq!(strongest_extension("Sp", vec!["671235", "Bb"]), "Sp.671235"); } }
Rust/154
/* You are given 2 words. You need to return True if the second word or any of its rotations is a substring in the first 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 cycpattern_check(a: &str, b: &str) -> bool {
for i in 0..b.len() { let rotate = format!("{}{}", &b[i..], &b[..i]); if a.contains(&rotate) { return true; } } false }
#[cfg(test)] mod tests { use super::*; #[test] fn test_cycpattern_check() { assert_eq!(cycpattern_check("xyzw", "xyw"), false); assert_eq!(cycpattern_check("yello", "ell"), true); assert_eq!(cycpattern_check("whattup", "ptut"), false); assert_eq!(cycpattern_check("efef", "fee"), true); assert_eq!(cycpattern_check("abab", "aabb"), false); assert_eq!(cycpattern_check("winemtt", "tinem"), true); } }
Rust/155
/* Given an integer. return a tuple that has the number of even and odd digits respectively. *\
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 even_odd_count(num: i32) -> Vec<i32> {
let w = num.abs().to_string(); let mut n1 = 0; let mut n2 = 0; for i in 0..w.len() { if w.chars().nth(i).unwrap().to_digit(10).unwrap() % 2 == 1 { n1 += 1; } else { n2 += 1; } } vec![n2, n1] }
#[cfg(test)] mod tests { use super::*; #[test] fn test_even_odd() { assert_eq!(even_odd_count(7), vec![0, 1]); assert_eq!(even_odd_count(-78), vec![1, 1]); assert_eq!(even_odd_count(3452), vec![2, 2]); assert_eq!(even_odd_count(346211), vec![3, 3]); assert_eq!(even_odd_count(-345821), vec![3, 3]); assert_eq!(even_odd_count(-2), vec![1, 0]); assert_eq!(even_odd_count(-45347), vec![2, 3]); assert_eq!(even_odd_count(0), vec![1, 0]); } }
Rust/156
/* Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. Restrictions: 1 <= num <= 1000 *\
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 int_to_mini_romank(number: i32) -> String {
let mut current = String::new(); let mut number = number; let rep = vec![ "m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i", ]; let num = vec![1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; let mut pos = 0; while number > 0 { while number >= num[pos] { current.push_str(rep[pos]); number -= num[pos]; } if number > 0 { pos += 1; } } current }
#[cfg(test)] mod tests { use super::*; #[test] fn test_int_to_mini_romank() { assert_eq!(int_to_mini_romank(19), "xix"); assert_eq!(int_to_mini_romank(152), "clii"); assert_eq!(int_to_mini_romank(251), "ccli"); assert_eq!(int_to_mini_romank(426), "cdxxvi"); assert_eq!(int_to_mini_romank(500), "d"); assert_eq!(int_to_mini_romank(1), "i"); assert_eq!(int_to_mini_romank(4), "iv"); assert_eq!(int_to_mini_romank(43), "xliii"); assert_eq!(int_to_mini_romank(90), "xc"); assert_eq!(int_to_mini_romank(94), "xciv"); assert_eq!(int_to_mini_romank(532), "dxxxii"); assert_eq!(int_to_mini_romank(900), "cm"); assert_eq!(int_to_mini_romank(994), "cmxciv"); assert_eq!(int_to_mini_romank(1000), "m"); } }
Rust/157
/* Given the lengths of the three sides of a triangle. Return True if the three sides form a right-angled triangle, False otherwise. A right-angled triangle is a triangle in which one angle is right angle or 90 degree. *\
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 right_angle_triangle(a: f32, b: f32, c: f32) -> bool {
if (a * a + b * b - c * c).abs() < 1e-4 || (a * a + c * c - b * b).abs() < 1e-4 || (b * b + c * c - a * a).abs() < 1e-4 { return true; } return false; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_right_angle_triangle() { assert_eq!(right_angle_triangle(3.0, 4.0, 5.0), true); assert_eq!(right_angle_triangle(1.0, 2.0, 3.0), false); assert_eq!(right_angle_triangle(10.0, 6.0, 8.0), true); assert_eq!(right_angle_triangle(2.0, 2.0, 2.0), false); assert_eq!(right_angle_triangle(7.0, 24.0, 25.0), true); assert_eq!(right_angle_triangle(10.0, 5.0, 7.0), false); assert_eq!(right_angle_triangle(5.0, 12.0, 13.0), true); assert_eq!(right_angle_triangle(15.0, 8.0, 17.0), true); assert_eq!(right_angle_triangle(48.0, 55.0, 73.0), true); assert_eq!(right_angle_triangle(1.0, 1.0, 1.0), false); assert_eq!(right_angle_triangle(2.0, 2.0, 10.0), false); } }
Rust/158
/* Write a function that accepts a list of strings. The list contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical 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 find_max(words: Vec<&str>) -> &str {
let mut max = ""; let mut maxu = 0; for i in 0..words.len() { let mut unique = String::from(""); for j in 0..words[i].len() { if !unique.contains(words[i].chars().nth(j).unwrap()) { unique.push(words[i].chars().nth(j).unwrap()); } } if unique.len() > maxu || (unique.len() == maxu && words[i] < max) { max = words[i]; maxu = unique.len(); } } max }
#[cfg(test)] mod tests { use super::*; #[test] fn test_find_max() { assert_eq!(find_max(vec!["name", "of", "string"]), "string"); assert_eq!(find_max(vec!["name", "enam", "game"]), "enam"); assert_eq!(find_max(vec!["aaaaaaa", "bb", "cc"]), "aaaaaaa"); assert_eq!(find_max(vec!["abc", "cba"]), "abc"); assert_eq!( find_max(vec!["play", "this", "game", "of", "footbott"]), "footbott" ); assert_eq!(find_max(vec!["we", "are", "gonna", "rock"]), "gonna"); assert_eq!(find_max(vec!["we", "are", "a", "mad", "nation"]), "nation"); assert_eq!(find_max(vec!["this", "is", "a", "prrk"]), "this"); assert_eq!(find_max(vec!["b"]), "b"); assert_eq!(find_max(vec!["play", "play", "play"]), "play"); } }
Rust/159
/* You're a hungry rabbit, and you already have eaten a certain number of carrots, but now you need to eat more carrots to complete the day's meals. you should return an array of [ total number of eaten carrots after your meals, the number of carrots left after your meals ] if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry. Variables: @number : integer the number of carrots that you have eaten. @need : integer the number of carrots that you need to eat. @remaining : integer the number of remaining carrots thet exist in stock Constrain: * 0 <= number <= 1000 * 0 <= need <= 1000 * 0 <= remaining <= 1000 Have fun :) *\
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 eat(number: i32, need: i32, remaining: i32) -> Vec<i32> {
if need > remaining { return vec![number + remaining, 0]; } return vec![number + need, remaining - need]; }
#[cfg(test)] mod tests { use super::*; #[test] fn test_eat() { assert_eq!(eat(5, 6, 10), vec![11, 4]); assert_eq!(eat(4, 8, 9), vec![12, 1]); assert_eq!(eat(1, 10, 10), vec![11, 0]); assert_eq!(eat(2, 11, 5), vec![7, 0]); assert_eq!(eat(4, 5, 7), vec![9, 2]); assert_eq!(eat(4, 5, 1), vec![5, 0]); } }
Rust/160
/* Given two lists operator, and operand. The first list has basic algebra operations, and the second list is a list of integers. Use the two given lists to build the algebric expression and return the evaluation of this expression. The basic algebra operations: Addition ( + ) Subtraction ( - ) Multiplication ( * ) Floor division ( // ) Exponentiation ( ** ) Note: The length of operator list is equal to the length of operand list minus one. Operand is a list of of non-negative integers. Operator list has at least one operator, and operand list has at least two operands. *\
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 do_algebra(operato: Vec<&str>, operand: Vec<i32>) -> i32 {
let mut operand: Vec<i32> = operand; let mut num: Vec<i32> = vec![]; let mut posto: Vec<i32> = vec![]; for i in 0..operand.len() { posto.push(i as i32); } for i in 0..operato.len() { if operato[i] == "**" { while posto[posto[i] as usize] != posto[i] { posto[i] = posto[posto[i] as usize]; } while posto[posto[i + 1] as usize] != posto[i + 1] { posto[i + 1] = posto[posto[i + 1] as usize]; } operand[posto[i] as usize] = operand[posto[i] as usize].pow(operand[posto[i + 1] as usize] as u32); posto[i + 1] = posto[i]; } } for i in 0..operato.len() { if operato[i] == "*" || operato[i] == "//" { while posto[posto[i] as usize] != posto[i] { posto[i] = posto[posto[i] as usize]; } while posto[posto[i + 1] as usize] != posto[i + 1] { posto[i + 1] = posto[posto[i + 1] as usize]; } if operato[i] == "*" { operand[posto[i] as usize] = operand[posto[i] as usize] * operand[posto[i + 1] as usize]; } else { operand[posto[i] as usize] = operand[posto[i] as usize] / operand[posto[i + 1] as usize]; } posto[i + 1] = posto[i]; } } for i in 0..operato.len() { if operato[i] == "+" || operato[i] == "-" { while posto[posto[i] as usize] != posto[i] { posto[i] = posto[posto[i] as usize]; } while posto[posto[i + 1] as usize] != posto[i + 1] { posto[i + 1] = posto[posto[i + 1] as usize]; } if operato[i] == "+" { operand[posto[i] as usize] = operand[posto[i] as usize] + operand[posto[i + 1] as usize]; } else { operand[posto[i] as usize] = operand[posto[i] as usize] - operand[posto[i + 1] as usize]; } posto[i + 1] = posto[i]; } } operand[0] }
#[cfg(test)] mod tests { use super::*; #[test] fn test_do_algebra() { assert_eq!(do_algebra(vec!["**", "*", "+"], vec![2, 3, 4, 5]), 37); assert_eq!(do_algebra(vec!["+", "*", "-"], vec![2, 3, 4, 5]), 9); assert_eq!(do_algebra(vec!["//", "*"], vec![7, 3, 4]), 8); } }
Rust/161
/* You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string contains no letters, reverse the string. The function should return the resulted 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 solve_161(s: &str) -> String {
let mut nletter = 0; let mut out = String::new(); for c in s.chars() { let mut w = c; if w >= 'A' && w <= 'Z' { w = w.to_ascii_lowercase(); } else if w >= 'a' && w <= 'z' { w = w.to_ascii_uppercase(); } else { nletter += 1; } out.push(w); } if nletter == s.len() { out.chars().rev().collect() } else { out } }
#[cfg(test)] mod tests { use super::*; #[test] fn test_solve_161() { assert_eq!(solve_161("AsDf"), "aSdF"); assert_eq!(solve_161("1234"), "4321"); assert_eq!(solve_161("ab"), "AB"); assert_eq!(solve_161("#a@C"), "#A@c"); assert_eq!(solve_161("#AsdfW^45"), "#aSDFw^45"); assert_eq!(solve_161("#6@2"), "2@6#"); assert_eq!(solve_161("#$a^D"), "#$A^d"); assert_eq!(solve_161("#ccc"), "#CCC"); } }
Rust/162
/* Given a string 'text', return its md5 hash equivalent string. If 'text' is an empty string, return None. *\
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_to_md5(text: &str) -> String {
if text.is_empty() { return "None".to_string(); } let digest = md5::compute(text.as_bytes()); return format!("{:x}", digest); }
#[cfg(test)] mod tests { use super::*; #[test] fn test_string_to_md5() { assert_eq!( string_to_md5("Hello world"), "3e25960a79dbc69b674cd4ec67a72c62" ); assert_eq!(string_to_md5(""), "None"); assert_eq!(string_to_md5("A B C"), "0ef78513b0cb8cef12743f5aeb35f888"); assert_eq!( string_to_md5("password"), "5f4dcc3b5aa765d61d8327deb882cf99" ); } }
Rust/163
/* Given two positive integers a and b, return the even digits between a and b, in ascending 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 generate_integers(a: i32, b: i32) -> Vec<i32> {
let mut a = a; let mut b = b; let mut m; if b < a { m = a; a = b; b = m; } let mut out = vec![]; for i in a..=b { if i < 10 && i % 2 == 0 { out.push(i); } } out }
#[cfg(test)] mod tests { use super::*; #[test] fn test_generate_integers() { assert_eq!(generate_integers(2, 10), vec![2, 4, 6, 8]); assert_eq!(generate_integers(10, 2), vec![2, 4, 6, 8]); assert_eq!(generate_integers(132, 2), vec![2, 4, 6, 8]); assert_eq!(generate_integers(17, 89), vec![]); } }