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