diff --git a/solutions/blood_types_s/Cargo.toml b/solutions/blood_types_s/Cargo.toml index afb88bfc..5691734e 100644 --- a/solutions/blood_types_s/Cargo.toml +++ b/solutions/blood_types_s/Cargo.toml @@ -2,7 +2,7 @@ name = "blood_types_s" version = "0.1.0" authors = ["Augusto "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/blood_types_s/src/lib.rs b/solutions/blood_types_s/src/lib.rs index 60cd4ed7..0247c62e 100644 --- a/solutions/blood_types_s/src/lib.rs +++ b/solutions/blood_types_s/src/lib.rs @@ -1,12 +1,4 @@ -// Write three methods for BloodType: -// - can_receive_from(&self, other: BloodType) -> bool {}: which -// returns true if self can receive blood from `other` blood type -// - donors(&self) -> Vec: which returns -// all the blood types that can give blood to self -// - recipients(&self) -> Vec: which returns all the blood -// types that can receive blood from self - -#[derive(Debug, PartialEq, Eq, Clone, PartialOrd, Ord)] +#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] pub enum Antigen { A, AB, @@ -14,337 +6,59 @@ pub enum Antigen { O, } -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] +impl Antigen { + pub const EVERY: &[Self] = &[Self::A, Self::AB, Self::B, Self::O]; +} + +#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] pub enum RhFactor { Positive, Negative, } -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] +impl RhFactor { + pub const EVERY: &[Self] = &[Self::Positive, Self::Negative]; +} + +#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] pub struct BloodType { - pub antigen: Antigen, pub rh_factor: RhFactor, + pub antigen: Antigen, } impl BloodType { - pub fn can_receive_from(&self, other: &Self) -> bool { - // Positive can only receive from positive - // A can only give from A - // And B can only give to B - if self.rh_factor != other.rh_factor && self.rh_factor == RhFactor::Negative { - return false; - } - - if other.antigen == Antigen::O { - return true; - } - - // if self.rh_factor contains one of the antigens of other - // then it can receive from it - self.antigen == Antigen::AB || other.antigen == self.antigen + #[inline] + pub fn every() -> impl Iterator { + Antigen::EVERY.iter().copied().flat_map(|a| { + RhFactor::EVERY.iter().copied().map(move |r| Self { + antigen: a, + rh_factor: r, + }) + }) } - // who are the donors of self - pub fn donors(&self) -> Vec { - // all blood types A, B, AB, O - let mut blood_types = Vec::new(); - let mut antigens = if self.antigen == Antigen::O { - vec![Antigen::O] - } else { - vec![Antigen::O, self.antigen.clone()] - }; - - let rh_factors = if self.rh_factor == RhFactor::Negative { - vec![RhFactor::Negative] - } else { - vec![RhFactor::Positive, RhFactor::Negative] - }; - - if self.antigen == Antigen::AB { - antigens.extend(vec![Antigen::A, Antigen::B]); - } - - for factor in rh_factors.iter() { - for ant in antigens.iter() { - blood_types.push(BloodType { - rh_factor: (*factor).clone(), - antigen: (*ant).clone(), - }) - } - } - - blood_types + #[inline] + fn can_donate_to(self, other: Self) -> bool { + other.can_receive_from(self) } - // who are the recipients of self - pub fn recipients(&self) -> Vec { - let mut blood_types = Vec::new(); - let mut antigens = if self.antigen != Antigen::AB { - vec![Antigen::AB, self.antigen.clone()] - } else { - vec![Antigen::AB] - }; - - let rh_factors = if self.rh_factor == RhFactor::Negative { - vec![RhFactor::Positive, RhFactor::Negative] - } else { - vec![RhFactor::Positive] - }; - - if self.antigen == Antigen::O { - antigens.extend(vec![Antigen::A, Antigen::B]); - } - - for factor in rh_factors.iter() { - for ant in antigens.iter() { - blood_types.push(BloodType { - rh_factor: (*factor).clone(), - antigen: (*ant).clone(), - }) - } + pub fn can_receive_from(self, other: Self) -> bool { + if !(self.rh_factor == other.rh_factor || self.rh_factor == RhFactor::Positive) { + return false; } - blood_types + other.antigen == Antigen::O || self.antigen == Antigen::AB || other.antigen == self.antigen } -} - -// fn main() { -// let blood_type: BloodType = "O+".parse().unwrap(); -// println!("recipients of O+ {:?}", blood_type.recipients()); -// println!("donors of O+ {:?}", blood_type.donors()); -// let another_blood_type: BloodType = "A-".parse().unwrap(); -// println!( -// "donors of O+ can receive from {:?} {:?}", -// &another_blood_type, -// blood_type.can_receive_from(&another_blood_type) -// ); -// } - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn compatible_ab_neg_with_a_pos() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }; - let other_bt = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Positive, - }; - assert!(!blood_type.can_receive_from(&other_bt)); + #[inline] + pub fn donors(self) -> Vec { + Self::every() + .filter(|&b| self.can_receive_from(b)) + .collect() } - #[test] - fn compatible_a_neg_with_a_pos() { - let blood_type = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }; - let other_bt = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Positive, - }; - assert!(!blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn compatible_a_neg_with_ab_neg() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }; - let other_bt = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }; - assert!(blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn compatible_ab_neg_with_o_pos() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }; - let other_bt = BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Positive, - }; - assert!(!blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn compatible_ab_pos_with_o_pos() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }; - let other_bt = BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Positive, - }; - assert!(blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn test_compatible_ab_neg_with_o_neg() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }; - let other_bt = BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Negative, - }; - assert!(blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn test_antigen_ab_from_str() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }; - assert_eq!(blood_type.antigen, Antigen::AB); - assert_eq!(blood_type.rh_factor, RhFactor::Positive); - } - - #[test] - fn test_antigen_a_from_str() { - let blood_type = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }; - assert_eq!(blood_type.antigen, Antigen::A); - assert_eq!(blood_type.rh_factor, RhFactor::Negative); - } - - #[test] - fn test_donors() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }; - let mut givers = blood_type.donors(); - // println!("Before sorting {:?}", &givers); - givers.sort(); - // println!("{:?}", &givers); - let mut expected = vec![ - BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }, - BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }, - BloodType { - antigen: Antigen::B, - rh_factor: RhFactor::Negative, - }, - BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Negative, - }, - BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }, - BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Positive, - }, - BloodType { - antigen: Antigen::B, - rh_factor: RhFactor::Positive, - }, - BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Positive, - }, - ]; - expected.sort(); - assert_eq!(givers, expected); - } - - #[test] - fn test_a_neg_donors() { - let blood = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }; - let mut givers = blood.donors(); - givers.sort(); - let mut expected = vec![ - BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }, - BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Negative, - }, - ]; - - expected.sort(); - assert_eq!(givers, expected); - } - - #[test] - fn test_o_neg_donors() { - let blood = BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Negative, - }; - - let mut givers = blood.donors(); - givers.sort(); - let mut expected = vec![blood.clone()]; - expected.sort(); - assert_eq!(givers, expected); - } - - #[test] - fn test_ab_pos_recipients() { - let blood = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }; - let mut recipients = blood.recipients(); - recipients.sort(); - let mut expected = vec![blood.clone()]; - expected.sort(); - assert_eq!(recipients, expected); - } - - #[test] - fn test_a_neg_recipients() { - let blood = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }; - - let mut recipients = blood.recipients(); - recipients.sort(); - let mut expected = vec![ - blood.clone(), - BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }, - BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Positive, - }, - BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }, - ]; - expected.sort(); - assert_eq!(recipients, expected); + #[inline] + pub fn recipients(self) -> Vec { + Self::every().filter(|&b| self.can_donate_to(b)).collect() } } diff --git a/solutions/brackets_matching/Cargo.toml b/solutions/brackets_matching/Cargo.toml index 024d517a..0593d298 100644 --- a/solutions/brackets_matching/Cargo.toml +++ b/solutions/brackets_matching/Cargo.toml @@ -2,7 +2,7 @@ name = "brackets_matching" version = "0.1.0" authors = ["lee "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/brackets_matching/src/main.rs b/solutions/brackets_matching/src/main.rs index 7a787720..118ba939 100644 --- a/solutions/brackets_matching/src/main.rs +++ b/solutions/brackets_matching/src/main.rs @@ -1,29 +1,29 @@ use std::env; -fn match_brackets(s: &str) -> bool { - let runes: Vec<&str> = s.split("").collect(); - let mut opened: Vec<&str> = vec![]; - let mut ptr: i32 = -1; - for c in runes.into_iter() { - if c == "(" || c == "[" || c == "{" { +fn match_brackets(s: String) -> bool { + let mut opened = vec![]; + + let mut ptr = -1; + for c in s.chars() { + if c == '(' || c == '[' || c == '{' { opened.push(c); ptr += 1; - } else if c == ")" { - if ptr < 0 || opened[ptr as usize] != "(" { + } else if c == ')' { + if ptr < 0 || opened[ptr as usize] != '(' { return false; } let (o, _) = opened.split_at(opened.len() - 1); opened = o.to_vec(); ptr -= 1; - } else if c == "]" { - if ptr < 0 || opened[ptr as usize] != "[" { + } else if c == ']' { + if ptr < 0 || opened[ptr as usize] != '[' { return false; } let (o, _) = opened.split_at(opened.len() - 1); opened = o.to_vec(); ptr -= 1; - } else if c == "}" { - if ptr < 0 || opened[ptr as usize] != "{" { + } else if c == '}' { + if ptr < 0 || opened[ptr as usize] != '{' { return false; } let (o, _) = opened.split_at(opened.len() - 1); @@ -31,21 +31,19 @@ fn match_brackets(s: &str) -> bool { ptr -= 1; } } - return opened.len() == 0; + + opened.is_empty() } fn main() { - let arg1: Vec = env::args().collect(); - if arg1.len() == 0 { - println!(""); - } else { - for (i, v) in arg1.iter().enumerate() { - if i != 0 { - if match_brackets(v) { - println!("OK"); - } else { - println!("Error"); - } + let args = env::args().collect::>(); + + for (i, v) in args.into_iter().enumerate() { + if i != 0 { + if match_brackets(v) { + println!("OK"); + } else { + println!("Error"); } } } diff --git a/solutions/car_rental/Cargo.toml b/solutions/car_rental/Cargo.toml index 36a515cb..c41c4b1b 100644 --- a/solutions/car_rental/Cargo.toml +++ b/solutions/car_rental/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "car_rental" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/car_rental/src/lib.rs b/solutions/car_rental/src/lib.rs index 856e3868..b84ea3ff 100644 --- a/solutions/car_rental/src/lib.rs +++ b/solutions/car_rental/src/lib.rs @@ -1,6 +1,4 @@ -use std::cell::Ref; -use std::cell::RefCell; -use std::cell::RefMut; +use std::cell::{Ref, RefCell, RefMut}; #[derive(Debug, Default, PartialEq, Eq)] pub struct Car { @@ -14,18 +12,22 @@ pub struct RentalBusiness { } impl RentalBusiness { - pub fn rent_car(&self) -> Ref { + #[inline] + pub fn rent_car(&self) -> Ref<'_, Car> { self.car.borrow() } + #[inline] pub fn sell_car(&self) -> Car { self.car.take() } - pub fn repair_car(&self) -> RefMut { + #[inline] + pub fn repair_car(&self) -> RefMut<'_, Car> { self.car.borrow_mut() } + #[inline] pub fn change_car(&self, new_car: Car) { self.car.replace(new_car); } diff --git a/solutions/count_factorial_steps/Cargo.toml b/solutions/count_factorial_steps/Cargo.toml index 2b4ed611..ad4e40a3 100644 --- a/solutions/count_factorial_steps/Cargo.toml +++ b/solutions/count_factorial_steps/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "count_factorial_steps" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/count_factorial_steps/src/lib.rs b/solutions/count_factorial_steps/src/lib.rs index 8a4ae296..b5292db0 100644 --- a/solutions/count_factorial_steps/src/lib.rs +++ b/solutions/count_factorial_steps/src/lib.rs @@ -6,7 +6,7 @@ pub fn count_factorial_steps(factorial: u64) -> u64 { loop { if curr_val < 2 { return step; - } else if (curr_val % multiplier) > 0 { + } else if !curr_val.is_multiple_of(multiplier) { return 0; } curr_val /= multiplier; diff --git a/solutions/counting_words/Cargo.toml b/solutions/counting_words/Cargo.toml index c47aeeb2..ea4714c7 100644 --- a/solutions/counting_words/Cargo.toml +++ b/solutions/counting_words/Cargo.toml @@ -2,7 +2,7 @@ name = "counting_words" version = "0.1.0" authors = ["MSilva95 "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/counting_words/src/lib.rs b/solutions/counting_words/src/lib.rs index 7d7f2afe..82c78901 100644 --- a/solutions/counting_words/src/lib.rs +++ b/solutions/counting_words/src/lib.rs @@ -1,159 +1,17 @@ -/*## counting_words - -### Instructions - -In this program you will have to create a function `counting_words` that -receives a `&str` and returns each word and the number of times it appears on the string. - -The program will count as a word the following: - -- A number like ("0" or "1234") will count as 1. -- A simple word or letter like ("a" or "they") will count as 1. -- Two simple words joined by a single apostrophe ("it's" or "they're") will count as 1. - -The program must respect the following rules: - -- The count is case insensitive ("HELLO", "Hello", and "hello") are 3 uses of the same word. -- All forms of punctuation have to be ignored except for the apostrophe if used like the example above. -- The words can be separated by any form of whitespace (ie "\t", "\n", " "). - -### Expected Function - -```rust -fn counting_words(words: &str) -> HashMap {} -``` - -### Usage - -Here is a possible program to test your function : - -```rust -use counting_words::counting_words; -use std::collections::HashMap; - -fn main() { - println!("{:?}", counting_words("Hello, world!")); - println!("{:?}", counting_words("“Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.” - ― Albert Einstein ")); - println!("{:?}", counting_words("Batman, BATMAN, batman, Stop stop")); -} -``` - -And its output: - -```console -student@ubuntu:~/[[ROOT]]/test$ cargo run -{"hello": 1, "world": 1} -{"and": 2, "human": 1, "universe": 2, "the": 2, "i\'m": 1, "about": 1, "einstein": 1, "are": 1, "infinite": 1, "sure": 1, "albert": 1, "two": 1, "things": 1, "not": 1, "stupidity": 1} -{"batman": 3, "stop": 2} -student@ubuntu:~/[[ROOT]]/test$ -``` -*/ - use std::collections::HashMap; +#[inline] pub fn counting_words(words: &str) -> HashMap { words .to_lowercase() .split(|c: char| !c.is_alphanumeric() && c != '\'') .map(|w| w.trim_matches('\'')) - .filter(|w| !w.is_empty()) + .filter(|&w| !w.is_empty()) .fold(HashMap::new(), |mut map, w| { - *map.entry(String::from(w)).or_default() += 1; + map.entry(String::from(w)) + .and_modify(|e| *e += 1) + .or_insert(1); + map }) } - -#[cfg(test)] -mod tests { - use super::*; - use test; - - fn test_counting(input: &str, expected: &[(&str, u32)]) { - let mut m: HashMap = counting_words(input); - for &(k, v) in expected.iter() { - assert_eq!( - (k, m.remove(&k.to_string().to_lowercase()).unwrap_or(0)), - (k, v) - ); - } - // may fail with a message that clearly shows all extra pairs in the map - assert_eq!(m.iter().collect::>(), vec![]); - } - #[test] - fn test_simple() { - test_counting("word", &[("word", 1)]); - test_counting("hello", &[("hello", 1)]); - test_counting("hello big world", &[("hello", 1), ("big", 1), ("world", 1)]); - test_counting("one of each", &[("one", 1), ("of", 1), ("each", 1)]); - test_counting("Hello, 1, 2 HELLO", &[("Hello", 2), ("1", 1), ("2", 1)]); - test_counting( - "Batman, BATMAN, batman, Stop stop", - &[("batman", 3), ("stop", 2)], - ); - test_counting( - " multiple whitespace", - &[("multiple", 1), ("whitespace", 1)], - ); - } - - #[test] - fn test_count_multiple_occurrences() { - test_counting( - "one fish two fish red fish blue fish", - &[("one", 1), ("fish", 4), ("two", 1), ("red", 1), ("blue", 1)], - ); - } - - #[test] - fn test_multi_lines() { - test_counting( - "Game\nNight\nTomorrow", - &[("Game", 1), ("Night", 1), ("Tomorrow", 1)], - ); - } - - #[test] - fn test_punctuation() { - test_counting( - "keyboard : mouse on the desk : Computer!!&@$%^&", - &[ - ("keyboard", 1), - ("mouse", 1), - ("on", 1), - ("the", 1), - ("desk", 1), - ("Computer", 1), - ], - ); - } - - #[test] - fn with_apostrophes() { - test_counting( - "First: don't laugh. Then: don't cry.", - &[ - ("first", 1), - ("don't", 2), - ("laugh", 1), - ("then", 1), - ("cry", 1), - ], - ); - } - - #[test] - fn test_apostrophe() { - test_counting( - "Joe can't tell between 'large' and large.", - &[ - ("joe", 1), - ("can't", 1), - ("tell", 1), - ("between", 1), - ("large", 2), - ("and", 1), - ], - ); - } -} diff --git a/solutions/display_table/Cargo.toml b/solutions/display_table/Cargo.toml index 26add114..9879738b 100644 --- a/solutions/display_table/Cargo.toml +++ b/solutions/display_table/Cargo.toml @@ -2,7 +2,7 @@ name = "display_table" version = "0.1.0" authors = ["Augusto "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/display_table/src/lib.rs b/solutions/display_table/src/lib.rs index 8ef2faf2..e2bb847d 100644 --- a/solutions/display_table/src/lib.rs +++ b/solutions/display_table/src/lib.rs @@ -1,99 +1,69 @@ use std::fmt; -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Default)] pub struct Table { pub headers: Vec, pub body: Vec>, } -// I want to print a table well formatted: -// Each column must adjust automatically depending on the maximum -// length of the string inside -// Ex: -// | Name | Last Name | -// |---------+-----------| -// | augusto | ornelas | -// here augusto is the longest string in the name column and therefore -// the col is adjusted in response -// in the column last name "last name" is the longest string so the -// length of the column is adjusted and "ornelas" stays in the center impl fmt::Display for Table { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.headers.len() == 0 { + if self.headers.is_empty() { return Ok(()); } - // get the maximum length of each column + let cols_len = self.columns_len(); - // print just one row without the newline let print_row = |row: &Vec, f: &mut fmt::Formatter| -> fmt::Result { write!(f, "|")?; for (i, col) in row.iter().enumerate() { write!(f, " {:^1$} |", col, cols_len[i])?; } + writeln!(f)?; Ok(()) }; print_row(&self.headers, f)?; - write!(f, "\n")?; - // write the separator between the headers and the rest of the list write!(f, "|")?; for v in &cols_len[..(cols_len.len() - 1)] { write!(f, "{:->1$}", "+", v + 3)?; } write!(f, "{:->1$}", "|", cols_len[cols_len.len() - 1] + 3)?; - write!(f, "\n")?; + writeln!(f)?; - // write the rest of the list - for row in self.body.iter() { - print_row(&row, f)?; - write!(f, "\n")?; + for row in &self.body { + print_row(row, f)?; } + Ok(()) } } impl Table { - #[allow(dead_code)] + #[inline] pub fn new() -> Self { - Self { - body: Vec::new(), - headers: Vec::new(), - } + Default::default() } - #[allow(dead_code)] + + #[inline] fn max_col(&self, col: usize) -> usize { - let col_header_length = self.headers[col].len(); - let mut max: usize = 0; - for row in &self.body { - for (i, v) in row.iter().enumerate() { - if i == col && v.len() > max { - max = v.len() - } - } - } - if max > col_header_length { - max - } else { - col_header_length - } + let header_len = self.headers[col].len(); + + self.body + .iter() + .map(|r| r[col].len()) + .max() + .unwrap_or_default() + .max(header_len) } - #[allow(dead_code)] + #[inline] fn columns_len(&self) -> Vec { - let mut cols_len = Vec::with_capacity(self.headers.len()); - for i in 0..self.headers.len() { - cols_len.push(self.max_col(i)); - } - cols_len - } - #[allow(dead_code)] - pub fn add_header(&mut self, new_header: &str) { - self.headers.push(new_header.to_owned()); + (0..self.headers.len()).map(|i| self.max_col(i)).collect() } - #[allow(dead_code)] + #[inline] pub fn add_row(&mut self, row: &[String]) { assert_eq!(self.headers.len(), row.len()); self.body.push(row.to_vec()); diff --git a/solutions/dress_code/Cargo.toml b/solutions/dress_code/Cargo.toml index 3d2cac58..ae231a97 100644 --- a/solutions/dress_code/Cargo.toml +++ b/solutions/dress_code/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "dress_code" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/dress_code/src/lib.rs b/solutions/dress_code/src/lib.rs index d18b8f88..6848f47d 100644 --- a/solutions/dress_code/src/lib.rs +++ b/solutions/dress_code/src/lib.rs @@ -18,34 +18,23 @@ pub struct Outfit { pub hat: Hat, } +#[inline] pub fn choose_outfit( formality_level: Option, invitation_message: Result<&str, &str>, ) -> Outfit { - let mut outfit = Outfit { - jacket: Jacket::Black, - hat: Hat::Snapback, + let jacket = match formality_level { + Some(level) if level > 0 => Jacket::White, + Some(_) => Jacket::Black, + _ => Jacket::Flowers, }; - match formality_level { - Some(level) => { - if level > 0 { - outfit.jacket = Jacket::White; - } - } - _ => { - outfit.jacket = Jacket::Flowers; - } + Outfit { + hat: match invitation_message { + Ok(_) => Hat::Fedora, + Err(_) if jacket == Jacket::Flowers => Hat::Baseball, + _ => Hat::Snapback, + }, + jacket, } - match invitation_message { - Ok(_) => { - outfit.hat = Hat::Fedora; - } - Err(_) => { - if let Jacket::Flowers = outfit.jacket { - outfit.hat = Hat::Baseball; - } - } - } - outfit } diff --git a/solutions/filter_table/Cargo.toml b/solutions/filter_table/Cargo.toml index 39ecff30..4b2a86e5 100644 --- a/solutions/filter_table/Cargo.toml +++ b/solutions/filter_table/Cargo.toml @@ -2,7 +2,7 @@ name = "filter_table" version = "0.1.0" authors = ["Augusto "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/filter_table/src/lib.rs b/solutions/filter_table/src/lib.rs index f2c3e9e4..679e63ab 100644 --- a/solutions/filter_table/src/lib.rs +++ b/solutions/filter_table/src/lib.rs @@ -1,25 +1,20 @@ -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Default)] pub struct Table { pub headers: Vec, pub body: Vec>, } impl Table { - #[allow(dead_code)] + #[inline] pub fn new() -> Self { - Self { - body: Vec::new(), - headers: Vec::new(), - } + Default::default() } - #[allow(dead_code)] pub fn add_row(&mut self, row: &[String]) { assert_eq!(self.headers.len(), row.len()); self.body.push(row.to_vec()); } - #[allow(dead_code)] pub fn add_col(&mut self, col: &[String]) { let mut col_it = col.iter(); @@ -32,7 +27,6 @@ impl Table { } } - #[allow(dead_code)] fn get_col(&self, index: usize) -> Option> { let header = self.headers.get(index)?; let mut col = vec![header.to_owned()]; @@ -43,11 +37,10 @@ impl Table { Some(col) } - #[allow(dead_code)] - pub fn filter_col bool>(&self, filter: T) -> Option { + pub fn filter_col(&self, filter: impl Fn(&str) -> bool) -> Option { let mut n_table = Table::new(); for (i, col) in self.headers.iter().enumerate() { - if filter(&col) { + if filter(col) { let column = self.get_col(i)?; n_table.add_col(&column); } @@ -55,15 +48,10 @@ impl Table { Some(n_table) } - // the filter is only to choose which elements of the column must - // be returned - #[allow(dead_code)] - pub fn filter_row bool>(&self, col_name: &str, filter: T) -> Option { + pub fn filter_row(&self, col_name: &str, filter: impl Fn(&str) -> bool) -> Option { let mut table = Table::new(); - // the first argument of the closure is the header and the - // second is the value of the column - // to select the column of a table with table.headers = self.headers.clone(); + let mut col = 0; for (i, header) in self.headers.iter().enumerate() { if header == col_name { @@ -81,99 +69,3 @@ impl Table { Some(table) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn filtering_columns() { - let mut table = Table::new(); - table.headers = vec![ - "name".to_string(), - "lastname".to_string(), - "id number".to_string(), - ]; - table.add_row(&[ - "Ackerley".to_string(), - "Philips".to_string(), - "123456789".to_string(), - ]); - table.add_row(&[ - "Adamaris".to_string(), - "Philips".to_string(), - "1111123456789".to_string(), - ]); - table.add_row(&[ - "Ackerley".to_string(), - "Philips".to_string(), - "123456789".to_string(), - ]); - - let filter = |col: &str| col == "name"; - - let new_table = Table { - headers: vec!["name".to_string()], - body: vec![ - vec!["Ackerley".to_string()], - vec!["Adamaris".to_string()], - vec!["Ackerley".to_string()], - ], - }; - assert_eq!(new_table, table.filter_col(filter).unwrap()); - } - - #[test] - fn filtering_rows() { - let tab = Table { - headers: vec![ - "Name".to_string(), - "Last Name".to_string(), - "ID Number".to_string(), - ], - body: vec![ - vec![ - "Adamaris".to_string(), - "Philips".to_string(), - "1111123456789".to_string(), - ], - vec![ - "Thomas".to_string(), - "Shelby".to_string(), - "123456789".to_string(), - ], - vec![ - "Ackerley".to_string(), - "Philips".to_string(), - "123456789".to_string(), - ], - ], - }; - - let get_fillips = |s: &str| s == "Philips"; - // filter the elements with last name Philips - let expected_table = Table { - headers: vec![ - "Name".to_string(), - "Last Name".to_string(), - "ID Number".to_string(), - ], - body: vec![ - vec![ - "Adamaris".to_string(), - "Philips".to_string(), - "1111123456789".to_string(), - ], - vec![ - "Ackerley".to_string(), - "Philips".to_string(), - "123456789".to_string(), - ], - ], - }; - assert_eq!( - tab.filter_row("Last Name", get_fillips).unwrap(), - expected_table - ); - } -} diff --git a/solutions/format_me/Cargo.toml b/solutions/format_me/Cargo.toml index 75d1f240..97915a23 100644 --- a/solutions/format_me/Cargo.toml +++ b/solutions/format_me/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "format_me" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/format_me/src/lib.rs b/solutions/format_me/src/lib.rs index 27696d03..5f03b7eb 100644 --- a/solutions/format_me/src/lib.rs +++ b/solutions/format_me/src/lib.rs @@ -1,11 +1,11 @@ use std::fmt; pub struct Park { - pub name: String, + pub name: Option, pub park_type: ParkType, - pub address: String, - pub cap: String, - pub state: String, + pub address: Option, + pub cap: Option, + pub state: Option, } pub enum ParkType { @@ -15,43 +15,31 @@ pub enum ParkType { } impl fmt::Display for Park { + #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{} - ", self.park_type)?; - - if self.name.is_empty() { - write!(f, "No name, ")?; - } else { - write!(f, "{}, ", self.name)?; - } - - if self.address.is_empty() { - write!(f, "No address, ")?; - } else { - write!(f, "{}, ", self.address)?; - } - - if self.cap.is_empty() { - write!(f, "No cap - ")?; - } else { - write!(f, "{} - ", self.cap)?; - } - - if self.state.is_empty() { - write!(f, "No state")?; - } else { - write!(f, "{}", self.state)?; - } - Ok(()) + write!( + f, + "{} - {}, {}, {} - {}", + self.park_type, + self.name.as_deref().unwrap_or("No name"), + self.address.as_deref().unwrap_or("No address"), + self.cap.as_deref().unwrap_or("No cap"), + self.state.as_deref().unwrap_or("No state") + ) } } impl fmt::Display for ParkType { + #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ParkType::Garden => write!(f, "garden")?, - ParkType::Forest => write!(f, "forest")?, - ParkType::Playground => write!(f, "playground")?, - } - Ok(()) + write!( + f, + "{}", + match self { + ParkType::Garden => "garden", + ParkType::Forest => "forest", + ParkType::Playground => "playground", + } + ) } } diff --git a/solutions/get_document_id/Cargo.toml b/solutions/get_document_id/Cargo.toml index 7b5ae7b8..4e78767e 100644 --- a/solutions/get_document_id/Cargo.toml +++ b/solutions/get_document_id/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "get_document_id" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/get_document_id/src/lib.rs b/solutions/get_document_id/src/lib.rs index f7e7e46b..169192e4 100644 --- a/solutions/get_document_id/src/lib.rs +++ b/solutions/get_document_id/src/lib.rs @@ -26,6 +26,7 @@ pub struct OfficeFour { } impl OfficeOne { + #[inline] pub fn get_document_id(&self) -> Result { self.next_office?.next_office?.next_office?.document_id } diff --git a/solutions/lucas_number/Cargo.toml b/solutions/lucas_number/Cargo.toml index 327cd0d6..c9e90cb2 100644 --- a/solutions/lucas_number/Cargo.toml +++ b/solutions/lucas_number/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lucas_number" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/lucas_number/src/lib.rs b/solutions/lucas_number/src/lib.rs index 1447d409..a0bcd93e 100644 --- a/solutions/lucas_number/src/lib.rs +++ b/solutions/lucas_number/src/lib.rs @@ -1,3 +1,4 @@ +#[inline] pub fn lucas_number(n: u32) -> u32 { match n { 0 => 2, diff --git a/solutions/lunch_queue/src/lib.rs b/solutions/lunch_queue/src/lib.rs index 6fa234b6..f48b5fa2 100644 --- a/solutions/lunch_queue/src/lib.rs +++ b/solutions/lunch_queue/src/lib.rs @@ -1,4 +1,4 @@ -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] pub struct Queue { pub node: Link, } @@ -13,10 +13,12 @@ pub struct Person { } impl Queue { + #[inline] pub fn new() -> Queue { - Queue { node: None } + Default::default() } + #[inline] pub fn add(&mut self, name: String, discount: u32) { let new_node = Box::new(Person { name, @@ -33,46 +35,47 @@ impl Queue { } pub fn rm(&mut self) -> Option<(String, u32)> { - if self.clone().node.as_ref().is_none() { - return None; - } let mut q = Queue::new(); - let result = recursion_rm(&self.clone().node, &mut q); + let result = recursion_rm(&self.node, &mut q); *self = q; self.invert_queue(); return Some(result); } - pub fn search(&self, s: &str) -> Option<(String, u32)> { - recursion(&self.clone().node, s.to_string()) + pub fn search(&self, s: &str) -> Option<(&String, &u32)> { + recursion(&self.node, s.to_string()) } } -fn recursion(node: &Link, s: String) -> Option<(String, u32)> { - if node.as_ref().is_none() { +fn recursion(node: &Link, s: String) -> Option<(&String, &u32)> { + let Some(node) = node.as_ref() else { return None; + }; + + if node.name == s { + return Some((&node.name, &node.discount)); } - let a = node.as_ref().unwrap(); - if a.name == s { - return Some((a.name.clone(), a.discount.clone())); - } - return recursion(&node.as_ref().unwrap().next_person, s); + return recursion(&node.next_person, s); } fn recursion_rm(node: &Link, q: &mut Queue) -> (String, u32) { - let a = node.as_ref().unwrap(); - if !a.next_person.is_none() { - q.add(a.name.clone(), a.discount.clone()); - return recursion_rm(&node.as_ref().unwrap().next_person, q); + let Some(node) = node.as_ref() else { + unreachable!(); + }; + + if node.next_person.is_some() { + q.add(node.name.clone(), node.discount); + return recursion_rm(&node.next_person, q); } else { - return (a.as_ref().name.clone(), a.as_ref().discount.clone()); + return (node.name.clone(), node.discount); } } fn recursion_inv(node: &Link, q: &mut Queue) { - let a = node.as_ref(); - if !a.is_none() { - q.add(a.unwrap().name.clone(), a.unwrap().discount.clone()); - return recursion_inv(&node.as_ref().unwrap().next_person, q); - } + let Some(node) = node.as_ref() else { + return; + }; + + q.add(node.name.clone(), node.discount.clone()); + return recursion_inv(&node.next_person, q); } diff --git a/solutions/matrix_determinant/Cargo.toml b/solutions/matrix_determinant/Cargo.toml index 5b3d51c7..03a18c67 100644 --- a/solutions/matrix_determinant/Cargo.toml +++ b/solutions/matrix_determinant/Cargo.toml @@ -2,7 +2,7 @@ name = "matrix_determinant" version = "0.1.0" authors = ["OGordoo "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/matrix_determinant/src/lib.rs b/solutions/matrix_determinant/src/lib.rs index b20f3457..24c4920a 100644 --- a/solutions/matrix_determinant/src/lib.rs +++ b/solutions/matrix_determinant/src/lib.rs @@ -6,10 +6,3 @@ pub fn matrix_determinant(matrix: [[isize; 3]; 3]) -> isize { - matrix[0][1] * matrix[1][0] * matrix[2][2] - matrix[0][2] * matrix[1][1] * matrix[2][0] } - -//other solution -pub fn matrix_determinant_2(matrix: [[isize; 3]; 3]) -> isize { - matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1]) - - matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[0][2] * matrix[2][1]) - + matrix[0][2] * (matrix[1][0] * matrix[1][2] - matrix[1][1] * matrix[1][2]) -} diff --git a/solutions/matrix_display/Cargo.toml b/solutions/matrix_display/Cargo.toml index 4df1ab98..70a5ef9c 100644 --- a/solutions/matrix_display/Cargo.toml +++ b/solutions/matrix_display/Cargo.toml @@ -2,7 +2,7 @@ name = "matrix_display" version = "0.1.0" authors = ["Augusto "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/matrix_display/src/lib.rs b/solutions/matrix_display/src/lib.rs index e337a0d2..d545273c 100644 --- a/solutions/matrix_display/src/lib.rs +++ b/solutions/matrix_display/src/lib.rs @@ -1,30 +1,14 @@ -// Implement the std::fmt::Display trait for a matrix of i32 -// using the struct Matrix define the associated function new that -// creates a new Matrix from &[&[i32]] -// After implement the std::fmt::Display trait to print the matrix -// like this - -// ``` -// (1 2 3) -// (4 5 6) -// (7 8 9) -// ``` +use std::fmt; #[derive(Debug, Clone)] pub struct Matrix(pub Vec>); impl Matrix { pub fn new(slice: &[&[i32]]) -> Self { - let mut inner = Vec::new(); - for row in slice { - inner.push(row.to_vec()); - } - Self(inner) + Self(slice.iter().map(|row| row.to_vec()).collect()) } } -use std::fmt; - impl fmt::Display for Matrix { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, row) in self.0.iter().enumerate() { @@ -37,28 +21,9 @@ impl fmt::Display for Matrix { } write!(f, ")")?; if i != self.0.len() - 1 { - write!(f, "\n")?; + writeln!(f)?; } } Ok(()) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - let matrix = Matrix::new(&[&[1, 2, 3], &[4, 5, 6], &[7, 8, 9]]); - let display = String::from("(1 2 3)\n(4 5 6)\n(7 8 9)"); - assert_eq!(display, matrix.to_string()); - } - - #[test] - fn test_matrix_col() { - let matrix = Matrix::new(&[&[1], &[2], &[3]]); - let display = String::from("(1)\n(2)\n(3)"); - assert_eq!(matrix.to_string(), display); - } -} diff --git a/solutions/matrix_multiplication/Cargo.toml b/solutions/matrix_multiplication/Cargo.toml index ef734668..eccfd01b 100644 --- a/solutions/matrix_multiplication/Cargo.toml +++ b/solutions/matrix_multiplication/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "matrix_multiplication" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/modify_letter/Cargo.toml b/solutions/modify_letter/Cargo.toml index 087a7850..e454e81b 100644 --- a/solutions/modify_letter/Cargo.toml +++ b/solutions/modify_letter/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "modify_letter" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/modify_letter/src/lib.rs b/solutions/modify_letter/src/lib.rs index 556d514c..0348929f 100644 --- a/solutions/modify_letter/src/lib.rs +++ b/solutions/modify_letter/src/lib.rs @@ -1,30 +1,26 @@ +#[inline] pub fn remove_letter_sensitive(s: &str, letter: char) -> String { s.replace(letter, "") } +#[inline] pub fn remove_letter_insensitive(s: &str, letter: char) -> String { - let lower_letter = letter.to_lowercase().to_string(); - let upper_letter = letter.to_uppercase().to_string(); - s.replace(&upper_letter, &lower_letter) - .replace(&lower_letter, "") + s.replace(|c: char| c.eq_ignore_ascii_case(&letter), "") } +#[inline] pub fn swap_letter_case(s: &str, letter: char) -> String { - s.split("") - .into_iter() - .map(|s| { - s.chars() - .filter_map(|c| { - if c.to_string() == letter.to_lowercase().to_string() { - c.to_uppercase().next() - } else if c.to_string() == letter.to_uppercase().to_string() { - c.to_lowercase().next() - } else { - Some(c) - } - }) - .collect() + s.chars() + .map(|c| { + if c.eq_ignore_ascii_case(&letter) { + if c.is_lowercase() { + c.to_ascii_uppercase() + } else { + c.to_ascii_lowercase() + } + } else { + c + } }) - .collect::>() - .join("") + .collect() } diff --git a/solutions/moving_targets/src/lib.rs b/solutions/moving_targets/src/lib.rs index 20d45e71..156a24ae 100644 --- a/solutions/moving_targets/src/lib.rs +++ b/solutions/moving_targets/src/lib.rs @@ -4,6 +4,7 @@ pub struct Target { pub xp: u32, } +#[derive(Default)] pub struct Field { head: Link, } @@ -16,10 +17,12 @@ struct Node { } impl Field { + #[inline] pub fn new() -> Self { - Field { head: None } + Default::default() } + #[inline] pub fn push(&mut self, target: Target) { let new_node = Box::new(Node { elem: target, @@ -28,6 +31,7 @@ impl Field { self.head = Some(new_node); } + #[inline] pub fn pop(&mut self) -> Option { self.head.take().map(|node| { self.head = node.next; @@ -35,10 +39,12 @@ impl Field { }) } + #[inline] pub fn peek(&self) -> Option<&Target> { self.head.as_ref().map(|node| &node.elem) } + #[inline] pub fn peek_mut(&mut self) -> Option<&mut Target> { self.head.as_mut().map(|node| &mut node.elem) } diff --git a/solutions/negative_spelling/Cargo.toml b/solutions/negative_spelling/Cargo.toml index e164ad0b..e4efb26e 100644 --- a/solutions/negative_spelling/Cargo.toml +++ b/solutions/negative_spelling/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "negative_spelling" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/negative_spelling/src/lib.rs b/solutions/negative_spelling/src/lib.rs index a399cff7..296f06b0 100644 --- a/solutions/negative_spelling/src/lib.rs +++ b/solutions/negative_spelling/src/lib.rs @@ -1,11 +1,13 @@ +#[inline] pub fn negative_spell(n: i64) -> String { match n { - 1.. => "error: positive number".to_string(), - 0 => "zero".to_string(), + 1.. => "error: positive number".to_owned(), + 0 => "zero".to_owned(), _ => format!("minus {}", spell(-n as u64)), } } +#[inline] pub fn spell(n: u64) -> String { match n { 0..=99 => spells_below_100(n), @@ -14,41 +16,43 @@ pub fn spell(n: u64) -> String { } } +#[inline] pub fn spells_below_100(n: u64) -> String { match n { - 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(), - 10 => "ten".to_string(), - 11 => "eleven".to_string(), - 12 => "twelve".to_string(), - 13 => "thirteen".to_string(), - 14 => "fourteen".to_string(), - 15 => "fifteen".to_string(), - 16 => "fifteen".to_string(), - 17 => "seventeen".to_string(), - 18 => "eighteen".to_string(), - 19 => "nineteen".to_string(), - 20 => "twenty".to_string(), - 30 => "thirty".to_string(), - 40 => "forty".to_string(), - 50 => "fifty".to_string(), - 60 => "sixty".to_string(), - 70 => "seventy".to_string(), - 80 => "eighty".to_string(), - 90 => "ninety".to_string(), + 0 => "zero", + 1 => "one", + 2 => "two", + 3 => "three", + 4 => "four", + 5 => "five", + 6 => "six", + 7 => "seven", + 8 => "eight", + 9 => "nine", + 10 => "ten", + 11 => "eleven", + 12 => "twelve", + 13 => "thirteen", + 14 => "fourteen", + 15 => "fifteen", + 16 => "sixteen", + 17 => "seventeen", + 18 => "eighteen", + 19 => "nineteen", + 20 => "twenty", + 30 => "thirty", + 40 => "forty", + 50 => "fifty", + 60 => "sixty", + 70 => "seventy", + 80 => "eighty", + 90 => "ninety", _ => { let rem = n % 10; - format!("{}-{}", spells_below_100(n - rem), spells_below_100(rem)) + return format!("{}-{}", spells_below_100(n - rem), spells_below_100(rem)); } } + .to_owned() } pub fn spells_hundreds(n: u64) -> String { @@ -62,28 +66,35 @@ pub fn spells_hundreds(n: u64) -> String { } pub fn spells_bignum(n: u64) -> String { - let mut enc_chunks: Vec = vec![]; - let mut chunks: Vec = vec![0; 7]; - let mut m = n; - for e in chunks.iter_mut() { - let rem = m % 1_000; - m /= 1_000; - *e += rem; - } - for (idx, chunk) in chunks.into_iter().enumerate() { - let substr = match idx { - 0 => "", - 1 => "thousand", - 2 => "million", - 3 => "billion", - 4 => "trillion", - 5 => "quadrillion", - _ => "quintillion", - }; - if chunk != 0 { - enc_chunks.push(format!("{} {}", spell(chunk), substr).trim().to_string()); - } - } - enc_chunks.reverse(); - enc_chunks.join(" ") + let chunks = [0; 7].into_iter().scan(n, |acc, _| { + let rem = *acc % 1_000; + *acc /= 1_000; + Some(rem) + }); + + let mut s = chunks + .into_iter() + .enumerate() + .map(|(i, chunk)| { + let substr = match i { + 0 => "", + 1 => "thousand", + 2 => "million", + 3 => "billion", + 4 => "trillion", + 5 => "quadrillion", + _ => "quintillion", + }; + if chunk != 0 { + Some(format!("{} {}", spell(chunk), substr)) + } else { + None + } + }) + .flat_map(|v| v) + .collect::>(); + + s.reverse(); + + s.join(" ").trim().to_owned() } diff --git a/solutions/office_worker/Cargo.toml b/solutions/office_worker/Cargo.toml index aa5f7734..e5aa99ef 100644 --- a/solutions/office_worker/Cargo.toml +++ b/solutions/office_worker/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "office_worker" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/office_worker/src/lib.rs b/solutions/office_worker/src/lib.rs index a040e8e8..409f0fea 100644 --- a/solutions/office_worker/src/lib.rs +++ b/solutions/office_worker/src/lib.rs @@ -14,21 +14,28 @@ pub enum WorkerRole { impl From<&str> for OfficeWorker { fn from(s: &str) -> Self { - let entries = s.split(',').collect::>(); - OfficeWorker { - name: entries.get(0).unwrap().to_string(), - age: entries.get(1).unwrap().parse().unwrap(), - role: WorkerRole::from(*entries.get(2).unwrap()), - } + let mut entries = s.split(','); + + let v = Self { + name: entries.next().unwrap().to_owned(), + age: entries.next().unwrap().parse().unwrap(), + role: WorkerRole::from(entries.next().unwrap()), + }; + + assert!(entries.next().is_none()); + + v } } impl From<&str> for WorkerRole { + #[inline] fn from(s: &str) -> Self { match s { "admin" => WorkerRole::Admin, "user" => WorkerRole::User, - _ => WorkerRole::Guest, + "guest" => WorkerRole::Guest, + _ => unreachable!(), } } } diff --git a/solutions/partial_sums/Cargo.toml b/solutions/partial_sums/Cargo.toml index f71b8cf8..e37e3528 100644 --- a/solutions/partial_sums/Cargo.toml +++ b/solutions/partial_sums/Cargo.toml @@ -2,7 +2,7 @@ name = "partial_sums" version = "0.1.0" authors = ["OGordoo "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/partial_sums/src/lib.rs b/solutions/partial_sums/src/lib.rs index f47183b8..a71b82a7 100644 --- a/solutions/partial_sums/src/lib.rs +++ b/solutions/partial_sums/src/lib.rs @@ -1,10 +1,14 @@ -pub fn parts_sums(ls: &[u64]) -> Vec { - let mut res = vec![]; - let mut sum: u64 = ls.iter().sum(); - res.push(sum); - for nbr in ls.iter().rev() { - sum -= nbr; - res.push(sum); - } - res +use std::iter; + +#[inline] +pub fn parts_sums(arr: &[u64]) -> Vec { + iter::successors(Some(arr), |&v| { + if v.is_empty() { + None + } else { + Some(&v[0..v.len() - 1]) + } + }) + .map(|v| v.iter().sum()) + .collect() } diff --git a/solutions/previousprime/src/lib.rs b/solutions/previousprime/src/lib.rs index fdfa8f94..a067970a 100644 --- a/solutions/previousprime/src/lib.rs +++ b/solutions/previousprime/src/lib.rs @@ -1,15 +1,19 @@ -use std::iter; - -#[inline] pub fn prev_prime(nbr: usize) -> usize { - if nbr > 2 { - iter::once(2) - .chain((3..nbr).step_by(2)) - .rfind(|&n| is_prime(n)) - .unwrap_or_default() - } else { - Default::default() + if nbr <= 2 { + return 0; } + + let start = if nbr.is_multiple_of(2) { + nbr - 1 + } else { + nbr - 2 + }; + + (1..=start) + .rev() + .step_by(2) + .find(|&n| is_prime(n)) + .unwrap_or(2) } fn is_prime(n: usize) -> bool { @@ -22,12 +26,21 @@ fn is_prime(n: usize) -> bool { if n.is_multiple_of(2) || n.is_multiple_of(3) { return false; } - let mut d = 5; - while d * d <= n { - if n.is_multiple_of(d) || n.is_multiple_of(d + 2) { + + if n.is_multiple_of(5) || n.is_multiple_of(7) || n.is_multiple_of(11) || n.is_multiple_of(13) { + return n <= 13; + } + + let sqrt_n = (n as f64).sqrt() as usize; + let mut d = 17; + let mut step = 2; + + while d <= sqrt_n { + if n % d == 0 { return false; } - d += 6; + d += step; + step = 6 - step; } true } diff --git a/solutions/profanity_filter/Cargo.toml b/solutions/profanity_filter/Cargo.toml index 7a337016..828d721f 100644 --- a/solutions/profanity_filter/Cargo.toml +++ b/solutions/profanity_filter/Cargo.toml @@ -2,7 +2,7 @@ name = "profanity_filter" version = "0.1.0" authors = ["lee "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/profanity_filter/src/lib.rs b/solutions/profanity_filter/src/lib.rs index d1d124d7..c44776e0 100644 --- a/solutions/profanity_filter/src/lib.rs +++ b/solutions/profanity_filter/src/lib.rs @@ -1,5 +1,6 @@ const WORD: &str = "stupid"; +#[inline] pub fn check_ms(message: &str) -> Result<&str, &str> { if message.is_empty() || message.contains(WORD) { Err("ERROR: illegal") diff --git a/solutions/reverse_it/Cargo.toml b/solutions/reverse_it/Cargo.toml index 949ed318..53d77354 100644 --- a/solutions/reverse_it/Cargo.toml +++ b/solutions/reverse_it/Cargo.toml @@ -2,7 +2,7 @@ name = "reverse_it" version = "0.1.0" authors = ["lee "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/reverse_it/src/lib.rs b/solutions/reverse_it/src/lib.rs index e4d9c4df..a8faa105 100644 --- a/solutions/reverse_it/src/lib.rs +++ b/solutions/reverse_it/src/lib.rs @@ -4,16 +4,3 @@ pub fn reverse_it(nbr: i32) -> String { let rev = abs_s.chars().rev().collect::(); format!("{}{}{}", if nbr < 0 { "-" } else { "" }, rev, abs_s) } - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn reverse_it_test() { - assert_eq!("321123", &reverse_it(123)); - assert_eq!("987654321123456789", &reverse_it(123456789)); - assert_eq!("00", &reverse_it(0)); - assert_eq!("-321123", &reverse_it(-123)); - assert_eq!("11", &reverse_it(1)); - } -} diff --git a/solutions/rot21/Cargo.toml b/solutions/rot21/Cargo.toml index 71a68bdb..10c9a19f 100644 --- a/solutions/rot21/Cargo.toml +++ b/solutions/rot21/Cargo.toml @@ -2,7 +2,7 @@ name = "rot21" version = "0.1.0" authors = ["MSilva95 "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/rot21/src/lib.rs b/solutions/rot21/src/lib.rs index dfff27a3..d314280e 100644 --- a/solutions/rot21/src/lib.rs +++ b/solutions/rot21/src/lib.rs @@ -1,78 +1,17 @@ -/* -## rot21 - -### Instructions - -Your purpose in this exercise is to create a `rot21` function that works like the ROT13 cipher. - -Your function will receive a string and it will rotate each letter of that string 21 times to the right. - -Your function should only change letters. If the string includes punctuation, symbols and numbers -they will remain the same. - -### Expected functions - -```rust -pub fn rot21(input: &str) -> String {} -``` - -### Usage - -Here is a program to test your function. - -```rust -use rot21::rot21; - -fn main() { - println!("The letter \"a\" becomes: {}", rot21("a")); - println!("The letter \"m\" becomes: {}", rot21("m")); - println!("The word \"MISS\" becomes: {}", rot21("MISS")); - println!("Your cypher wil be: {}", rot21("Testing numbers 1 2 3")); - println!("Your cypher wil be: {}", rot21("rot21 works!")); -} - -``` - -And its output - -```console -The letter "a" becomes: v -The letter "m" becomes: h -The word "MISS" becomes: HDNN -Your cypher wil be: Oznodib iphwzmn 1 2 3 -Your cypher wil be: mjo21 rjmfn! -student@ubuntu:~/[[ROOT]]/test$ -``` -*/ +const ROT: u8 = 21; +const ALPHABET_SIZE: u8 = 26; +#[inline] pub fn rot21(input: &str) -> String { input .chars() - .map(|character| match character { - 'a'..='z' => { - ((((character as u8) - b'a') as i8 + 21).rem_euclid(26) as u8 + b'a') as char + .map(|c| { + if !c.is_ascii_alphabetic() { + c + } else { + let init = if c.is_ascii_lowercase() { b'a' } else { b'A' }; + ((c as u8 - init + ROT) % ALPHABET_SIZE + init) as char } - 'A'..='Z' => { - ((((character as u8) - b'A') as i8 + 21).rem_euclid(26) as u8 + b'A') as char - } - _ => character, }) - .collect::() -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_rot21_multiple_cases() { - assert_eq!("ocdn dn v ozno", rot21("this is a test")); - assert_eq!("mviyjh ndhkgz rjmyn", rot21("random simple words")); - assert_eq!( - "ojj hpxc nkvxzn rjmfn", - rot21("too much spaces works") - ); - assert_eq!("mv😋w", rot21("ra😋b")); - assert_eq!("12Â nãj ábpv", rot21("12Â são água")); - } + .collect() } diff --git a/solutions/smallest/Cargo.toml b/solutions/smallest/Cargo.toml index d2ac1401..e10a48a5 100644 --- a/solutions/smallest/Cargo.toml +++ b/solutions/smallest/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "smallest" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/solutions/smallest/src/lib.rs b/solutions/smallest/src/lib.rs index 9b0221b5..a3dba5b7 100644 --- a/solutions/smallest/src/lib.rs +++ b/solutions/smallest/src/lib.rs @@ -1,12 +1,6 @@ use std::collections::HashMap; +#[inline] pub fn smallest(h: HashMap<&str, i32>) -> i32 { - let mut smallest_value = i32::MAX; - - for (_, v) in h.iter() { - if *v < smallest_value { - smallest_value = *v; - } - } - return smallest_value; + h.values().min().copied().unwrap_or(i32::MAX) } diff --git a/tests/blood_types_s_test/Cargo.toml b/tests/blood_types_s_test/Cargo.toml index 97a5f953..290bae9d 100644 --- a/tests/blood_types_s_test/Cargo.toml +++ b/tests/blood_types_s_test/Cargo.toml @@ -2,9 +2,9 @@ name = "blood_types_s_test" version = "0.1.0" authors = ["Augusto "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -blood_types_s = { path = "../../solutions/blood_types_s" } \ No newline at end of file +blood_types_s = { path = "../../solutions/blood_types_s" } diff --git a/tests/blood_types_s_test/src/lib.rs b/tests/blood_types_s_test/src/lib.rs new file mode 100644 index 00000000..50285d9a --- /dev/null +++ b/tests/blood_types_s_test/src/lib.rs @@ -0,0 +1,210 @@ +use blood_types_s::*; +use std::{collections::HashMap, hash::Hash}; + +fn slices_eq_unordered(a: &[T], b: &[T]) -> bool { + let count_elems = |arr| { + let mut map = HashMap::new(); + for item in arr { + *map.entry(item).or_insert(0) += 1; + } + map + }; + + count_elems(a) == count_elems(b) +} + +#[test] +fn check_blood_type_relationships() { + let relationships = [ + ( + BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Positive, + }, + false, + ), + ( + BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Positive, + }, + false, + ), + ( + BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Negative, + }, + true, + ), + ( + BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::O, + rh_factor: RhFactor::Positive, + }, + false, + ), + ( + BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Positive, + }, + BloodType { + antigen: Antigen::O, + rh_factor: RhFactor::Positive, + }, + true, + ), + ( + BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::O, + rh_factor: RhFactor::Negative, + }, + true, + ), + ]; + + relationships + .into_iter() + .for_each(|(t1, t2, e)| assert_eq!(t1.can_receive_from(t2), e)); +} + +#[test] +fn test_ab_pos_donors() { + let donors = BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Positive, + } + .donors(); + let expected = [ + BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::B, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::O, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Positive, + }, + BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Positive, + }, + BloodType { + antigen: Antigen::B, + rh_factor: RhFactor::Positive, + }, + BloodType { + antigen: Antigen::O, + rh_factor: RhFactor::Positive, + }, + ]; + assert!(slices_eq_unordered(&donors, &expected)); +} + +#[test] +fn test_a_neg_donors() { + let donors = BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Negative, + } + .donors(); + let expected = [ + BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::O, + rh_factor: RhFactor::Negative, + }, + ]; + assert!(slices_eq_unordered(&donors, &expected)); +} + +#[test] +fn test_o_neg_donors() { + let donors = BloodType { + antigen: Antigen::O, + rh_factor: RhFactor::Negative, + } + .donors(); + let expected = [BloodType { + antigen: Antigen::O, + rh_factor: RhFactor::Negative, + }]; + assert!(slices_eq_unordered(&donors, &expected)); +} + +#[test] +fn test_ab_pos_recipients() { + let recipients = BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Positive, + } + .recipients(); + let expected = [BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Positive, + }]; + assert!(slices_eq_unordered(&recipients, &expected)); +} + +#[test] +fn test_a_neg_recipients() { + let recipients = BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Negative, + } + .recipients(); + let expected = [ + BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::A, + rh_factor: RhFactor::Positive, + }, + BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Negative, + }, + BloodType { + antigen: Antigen::AB, + rh_factor: RhFactor::Positive, + }, + ]; + assert!(slices_eq_unordered(&recipients, &expected)); +} diff --git a/tests/blood_types_s_test/src/main.rs b/tests/blood_types_s_test/src/main.rs deleted file mode 100644 index bcc6c0d7..00000000 --- a/tests/blood_types_s_test/src/main.rs +++ /dev/null @@ -1,256 +0,0 @@ -// Write three methods for BloodType: -// - can_receive_from(&self, other: BloodType) -> bool {}: which -// returns true if self can receive blood from `other` blood type -// - donors(&self) -> Vec: which returns -// all the blood types that can give blood to self -// - recipients(&self) -> Vec: which returns all the blood -// types that can receive blood from self - -use blood_types_s::{Antigen, BloodType, RhFactor}; - -fn main() { - let blood_type = BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Positive, - }; - println!("recipients of O+ {:?}", blood_type.recipients()); - println!("donors of O+ {:?}", blood_type.donors()); - let another_blood_type = BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Positive, - }; - println!( - "donors of O+ can receive from {:?} {:?}", - &another_blood_type, - blood_type.can_receive_from(&another_blood_type) - ); -} - -#[cfg(test)] -mod tests { - use blood_types_s::*; - - #[test] - fn compatible_ab_neg_with_a_pos() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }; - let other_bt = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Positive, - }; - assert!(!blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn compatible_a_neg_with_a_pos() { - let blood_type = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }; - let other_bt = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Positive, - }; - assert!(!blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn compatible_a_neg_with_ab_neg() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }; - let other_bt = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }; - assert!(blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn compatible_ab_neg_with_o_pos() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }; - let other_bt = BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Positive, - }; - assert!(!blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn compatible_ab_pos_with_o_pos() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }; - let other_bt = BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Positive, - }; - assert!(blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn test_compatible_ab_neg_with_o_neg() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }; - let other_bt = BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Negative, - }; - assert!(blood_type.can_receive_from(&other_bt)); - } - - #[test] - fn test_antigen_ab_from_str() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }; - assert_eq!(blood_type.antigen, Antigen::AB); - assert_eq!(blood_type.rh_factor, RhFactor::Positive); - } - - #[test] - fn test_antigen_a_from_str() { - let blood_type = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }; - assert_eq!(blood_type.antigen, Antigen::A); - assert_eq!(blood_type.rh_factor, RhFactor::Negative); - } - - #[test] - fn test_donors() { - let blood_type = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }; - let mut givers = blood_type.donors(); - // println!("Before sorting {:?}", &givers); - givers.sort(); - // println!("{:?}", &givers); - let mut expected = vec![ - BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }, - BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }, - BloodType { - antigen: Antigen::B, - rh_factor: RhFactor::Negative, - }, - BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Negative, - }, - BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }, - BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Positive, - }, - BloodType { - antigen: Antigen::B, - rh_factor: RhFactor::Positive, - }, - BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Positive, - }, - ]; - expected.sort(); - assert_eq!(givers, expected); - } - - #[test] - fn test_a_neg_donors() { - let blood = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }; - let mut givers = blood.donors(); - givers.sort(); - let mut expected = vec![ - BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }, - BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Negative, - }, - ]; - - expected.sort(); - assert_eq!(givers, expected); - } - - #[test] - fn test_o_neg_donors() { - let blood = BloodType { - antigen: Antigen::O, - rh_factor: RhFactor::Negative, - }; - - let mut givers = blood.donors(); - givers.sort(); - let mut expected = vec![blood.clone()]; - expected.sort(); - assert_eq!(givers, expected); - } - - #[test] - fn test_ab_pos_recipients() { - let blood = BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }; - let mut recipients = blood.recipients(); - recipients.sort(); - let mut expected = vec![blood.clone()]; - expected.sort(); - assert_eq!(recipients, expected); - } - - #[test] - fn test_a_neg_recipients() { - let blood = BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Negative, - }; - - let mut recipients = blood.recipients(); - recipients.sort(); - let mut expected = vec![ - blood.clone(), - BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Positive, - }, - BloodType { - antigen: Antigen::A, - rh_factor: RhFactor::Positive, - }, - BloodType { - antigen: Antigen::AB, - rh_factor: RhFactor::Negative, - }, - ]; - expected.sort(); - assert_eq!(recipients, expected); - } -} diff --git a/tests/brackets_matching_test/Cargo.toml b/tests/brackets_matching_test/Cargo.toml index af0b38f1..95332b48 100644 --- a/tests/brackets_matching_test/Cargo.toml +++ b/tests/brackets_matching_test/Cargo.toml @@ -2,9 +2,9 @@ name = "brackets_matching_test" version = "0.1.0" authors = ["lee "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -rand = "0.8.2" \ No newline at end of file +rand = "0.9.2" diff --git a/tests/brackets_matching_test/src/lib.rs b/tests/brackets_matching_test/src/lib.rs index dfce134f..6a99447c 100644 --- a/tests/brackets_matching_test/src/lib.rs +++ b/tests/brackets_matching_test/src/lib.rs @@ -1,78 +1,64 @@ -#[cfg(test)] -mod tests { +use rand::{Rng, distr::Alphanumeric}; +use std::process::{Command, Output}; - use rand::distributions::Alphanumeric; - use rand::{thread_rng, Rng}; +const MANIFEST_PATH: &str = "../../solutions/brackets_matching/Cargo.toml"; - use std::process::{Command, Output}; - - const MANIFEST_PATH: &str = "../../solutions/brackets_matching/Cargo.toml"; +#[inline] +fn run(s: Vec<&str>) -> Output { + Command::new("cargo") + .arg("run") + .arg("--manifest-path") + .arg(MANIFEST_PATH) + .args(s.iter()) + .output() + .expect("Failed to execute command") +} - fn run(s: Vec<&str>) -> Output { - Command::new("cargo") - .arg("run") - .arg("--manifest-path") - .arg(MANIFEST_PATH) - .args(s.iter()) - .output() - .expect("Failed to execute command") +#[test] +fn random_tests() { + fn random_alnum() -> String { + rand::rng() + .sample_iter(&Alphanumeric) + .take(30) + .map(char::from) + .collect() } - #[test] - fn random_tests() { - fn random_alnum() -> String { - thread_rng() - .sample_iter(&Alphanumeric) - .take(30) - .map(char::from) - .collect() - } - let mut args = vec![ - String::from("(johndoe)"), - String::from("()"), - String::from("([])"), - String::from("{2*[d - 3]/(12)}"), - ]; + let mut args = vec![ + String::from("(johndoe)"), + String::from("()"), + String::from("([])"), + String::from("{2*[d - 3]/(12)}"), + ]; - for _ in 0..3 { - args.push(format!("({:?})", &random_alnum())); - args.push(format!("[{:?}]", &random_alnum())); - args.push(format!("{}{:?}{}", "{", &random_alnum(), "}")); - } - - for v in args.iter() { - let output = run(vec![v]); - assert_eq!(String::from_utf8(output.stdout).unwrap(), "OK\n"); - } + for _ in 0..3 { + args.push(format!("({:?})", &random_alnum())); + args.push(format!("[{:?}]", &random_alnum())); + args.push(format!("{}{:?}{}", "{", &random_alnum(), "}")); } - #[test] - fn tests_both() { - struct Test<'a> { - arguments: ([&'a str; 2], &'a str), - } + for v in args.iter() { + let output = run(vec![v]); + assert_eq!(String::from_utf8(output.stdout).unwrap(), "OK\n"); + } +} - let arr: [Test; 3] = [ - Test { - arguments: (["", "{[(0 + 0)(1 + 1)](3*(-1)){()}}"], "OK\nOK\n"), - }, - Test { - arguments: (["{][]}", "{3*[21/(12+ 23)]}"], "Error\nOK\n"), - }, - Test { - arguments: (["{([)])}", "{{{something }- [something]}}"], "Error\nOK\n"), - }, - ]; +#[test] +fn tests_both() { + let arr = [ + (["", "{[(0 + 0)(1 + 1)](3*(-1)){()}}"], "OK\nOK\n"), + (["{][]}", "{3*[21/(12+ 23)]}"], "Error\nOK\n"), + (["{([)])}", "{{{something }- [something]}}"], "Error\nOK\n"), + ]; - for t in arr.iter() { - let output = run(t.arguments.0.to_vec()); - assert_eq!(String::from_utf8_lossy(&output.stdout), t.arguments.1); - } + for t in arr.iter() { + let output = run(t.0.to_vec()); + assert_eq!(String::from_utf8_lossy(&output.stdout), t.1); } +} - #[test] - fn tests_with_nothing() { - let output = run(vec![]); - assert_eq!(String::from_utf8_lossy(&output.stdout), ""); - } +#[test] +fn tests_with_nothing() { + let output = run(vec![]); + assert_eq!(String::from_utf8_lossy(&output.stdout), ""); } diff --git a/tests/car_rental_test/Cargo.toml b/tests/car_rental_test/Cargo.toml index 8c5043f3..15a5130c 100644 --- a/tests/car_rental_test/Cargo.toml +++ b/tests/car_rental_test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "car_rental_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/car_rental_test/src/lib.rs b/tests/car_rental_test/src/lib.rs new file mode 100644 index 00000000..e8ef98df --- /dev/null +++ b/tests/car_rental_test/src/lib.rs @@ -0,0 +1,125 @@ +use car_rental::*; +use std::cell::RefCell; + +#[test] +fn test_rent_car() { + let car_rental = RentalBusiness { + car: RefCell::new(Car { + color: "violet".to_string(), + plate: "ABCDEF".to_string(), + }), + }; + let car_result1 = Car { + color: "violet".to_string(), + plate: "ABCDEF".to_string(), + }; + + assert_eq!(*car_rental.rent_car(), car_result1); + assert_eq!(*car_rental.rent_car(), car_result1); + assert_eq!(*car_rental.rent_car(), car_result1); +} + +#[test] +fn test_repair_car() { + let car_rental = RentalBusiness { + car: RefCell::new(Car { + color: "violet".to_string(), + plate: "ABCDEF".to_string(), + }), + }; + + assert_eq!( + *car_rental.rent_car(), + Car { + color: "violet".to_string(), + plate: "ABCDEF".to_string(), + } + ); + + { + let mut car = car_rental.repair_car(); + car.color = "yellow".to_string(); + } + + assert_eq!( + *car_rental.rent_car(), + Car { + color: "yellow".to_string(), + plate: "ABCDEF".to_string(), + } + ); +} + +#[test] +#[should_panic] +fn test_repair_car_panic() { + let car_rental = RentalBusiness { + car: RefCell::new(Car { + color: "violet".to_string(), + plate: "ABCDEF".to_string(), + }), + }; + let _car = car_rental.repair_car(); + let _car2 = car_rental.repair_car(); +} + +#[test] +#[should_panic] +fn test_repair_and_rent() { + let car_rental = RentalBusiness { + car: RefCell::new(Car { + color: "violet".to_string(), + plate: "ABCDEF".to_string(), + }), + }; + let _car = car_rental.repair_car(); + car_rental.rent_car(); +} + +#[test] +fn test_change_car() { + let car_rental = RentalBusiness { + car: RefCell::new(Car { + color: "violet".to_string(), + plate: "ABCDEF".to_string(), + }), + }; + + car_rental.change_car(Car { + color: "yellow".to_string(), + plate: "ABCDEF".to_string(), + }); + + assert_eq!( + *car_rental.rent_car(), + Car { + color: "yellow".to_string(), + plate: "ABCDEF".to_string(), + } + ); +} + +#[test] +fn test_sell_car() { + let car_rental = RentalBusiness { + car: RefCell::new(Car { + color: "violet".to_string(), + plate: "ABCDEF".to_string(), + }), + }; + + assert_eq!( + car_rental.sell_car(), + Car { + color: "violet".to_string(), + plate: "ABCDEF".to_string(), + } + ); + assert_eq!( + car_rental.sell_car(), + Car { + color: "".to_string(), + plate: "".to_string(), + } + ); +} diff --git a/tests/car_rental_test/src/main.rs b/tests/car_rental_test/src/main.rs deleted file mode 100644 index adcabfa2..00000000 --- a/tests/car_rental_test/src/main.rs +++ /dev/null @@ -1,159 +0,0 @@ -use car_rental::*; -use std::cell::RefCell; - -fn main() { - let car_rental = RentalBusiness { - car: RefCell::new(Car { - color: "red".to_string(), - plate: "AAA".to_string(), - }), - }; - - println!("{:?}", car_rental.rent_car()); - println!("{:?}", car_rental.repair_car()); - - { - let mut car = car_rental.repair_car(); - car.color = "blue".to_string(); - } - - println!("{:?}", car_rental.rent_car()); - - car_rental.change_car(Car { - color: "pink".to_string(), - plate: "WWW".to_string(), - }); - - println!("{:?}", car_rental.rent_car()); - - println!("{:?}", car_rental.sell_car()); - println!("{:?}", car_rental.sell_car()); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_rent_car() { - let car_rental = RentalBusiness { - car: RefCell::new(Car { - color: "violet".to_string(), - plate: "ABCDEF".to_string(), - }), - }; - let car_result1 = Car { - color: "violet".to_string(), - plate: "ABCDEF".to_string(), - }; - - assert_eq!(*car_rental.rent_car(), car_result1); - assert_eq!(*car_rental.rent_car(), car_result1); - assert_eq!(*car_rental.rent_car(), car_result1); - } - - #[test] - fn test_repair_car() { - let car_rental = RentalBusiness { - car: RefCell::new(Car { - color: "violet".to_string(), - plate: "ABCDEF".to_string(), - }), - }; - - assert_eq!( - *car_rental.rent_car(), - Car { - color: "violet".to_string(), - plate: "ABCDEF".to_string(), - } - ); - - { - let mut car = car_rental.repair_car(); - car.color = "yellow".to_string(); - } - - assert_eq!( - *car_rental.rent_car(), - Car { - color: "yellow".to_string(), - plate: "ABCDEF".to_string(), - } - ); - } - - #[test] - #[should_panic] - fn test_repair_car_panic() { - let car_rental = RentalBusiness { - car: RefCell::new(Car { - color: "violet".to_string(), - plate: "ABCDEF".to_string(), - }), - }; - let _car = car_rental.repair_car(); - let _car2 = car_rental.repair_car(); - } - - #[test] - #[should_panic] - fn test_repair_and_rent() { - let car_rental = RentalBusiness { - car: RefCell::new(Car { - color: "violet".to_string(), - plate: "ABCDEF".to_string(), - }), - }; - let _car = car_rental.repair_car(); - car_rental.rent_car(); - } - - #[test] - fn test_change_car() { - let car_rental = RentalBusiness { - car: RefCell::new(Car { - color: "violet".to_string(), - plate: "ABCDEF".to_string(), - }), - }; - - car_rental.change_car(Car { - color: "yellow".to_string(), - plate: "ABCDEF".to_string(), - }); - - assert_eq!( - *car_rental.rent_car(), - Car { - color: "yellow".to_string(), - plate: "ABCDEF".to_string(), - } - ); - } - - #[test] - fn test_sell_car() { - let car_rental = RentalBusiness { - car: RefCell::new(Car { - color: "violet".to_string(), - plate: "ABCDEF".to_string(), - }), - }; - - assert_eq!( - car_rental.sell_car(), - Car { - color: "violet".to_string(), - plate: "ABCDEF".to_string(), - } - ); - assert_eq!( - car_rental.sell_car(), - Car { - color: "".to_string(), - plate: "".to_string(), - } - ); - } -} diff --git a/tests/count_factorial_steps_test/Cargo.toml b/tests/count_factorial_steps_test/Cargo.toml index f2db95fe..29a8f683 100644 --- a/tests/count_factorial_steps_test/Cargo.toml +++ b/tests/count_factorial_steps_test/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "count_factorial_steps_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -count_factorial_steps = { path = "../../solutions/count_factorial_steps" } +count_factorial_steps = { path = "../../solutions/count_factorial_steps" } diff --git a/tests/count_factorial_steps_test/src/lib.rs b/tests/count_factorial_steps_test/src/lib.rs new file mode 100644 index 00000000..71cf3872 --- /dev/null +++ b/tests/count_factorial_steps_test/src/lib.rs @@ -0,0 +1,14 @@ +use count_factorial_steps::*; + +#[test] +fn count_factorial_steps_edge_cases() { + assert_eq!(0, count_factorial_steps(0)); + assert_eq!(0, count_factorial_steps(1)); + assert_eq!(0, count_factorial_steps(123)); +} + +#[test] +fn count_factorial_steps_normal_cases() { + assert_eq!(6, count_factorial_steps(720)); + assert_eq!(10, count_factorial_steps(3628800)); +} diff --git a/tests/count_factorial_steps_test/src/main.rs b/tests/count_factorial_steps_test/src/main.rs deleted file mode 100644 index 33a29fd4..00000000 --- a/tests/count_factorial_steps_test/src/main.rs +++ /dev/null @@ -1,24 +0,0 @@ -use count_factorial_steps::count_factorial_steps; - -fn main() { - println!("The factorial steps of 720 = {}", count_factorial_steps(720)); - println!("The factorial steps of 13 = {}", count_factorial_steps(13)); - println!("The factorial steps of 6 = {}", count_factorial_steps(6)); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn count_factorial_steps_edge_cases() { - assert_eq!(0, count_factorial_steps(0)); - assert_eq!(0, count_factorial_steps(1)); - assert_eq!(0, count_factorial_steps(123)); - } - #[test] - fn count_factorial_steps_normal_cases() { - assert_eq!(6, count_factorial_steps(720)); - assert_eq!(10, count_factorial_steps(3628800)); - } -} diff --git a/tests/counting_words_test/Cargo.toml b/tests/counting_words_test/Cargo.toml index 0adfb035..074ca92b 100644 --- a/tests/counting_words_test/Cargo.toml +++ b/tests/counting_words_test/Cargo.toml @@ -2,7 +2,7 @@ name = "counting_words_test" version = "0.1.0" authors = ["MSilva95 "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/counting_words_test/src/lib.rs b/tests/counting_words_test/src/lib.rs new file mode 100644 index 00000000..a3bd2046 --- /dev/null +++ b/tests/counting_words_test/src/lib.rs @@ -0,0 +1,87 @@ +use counting_words::*; + +fn cmp_hashmap_unordered(input: &str, expected: &[(&str, u32)]) { + let m = counting_words(input); + + assert_eq!(expected.len(), m.len()); + expected + .iter() + .for_each(|&(k, v)| assert_eq!(m.get(k), Some(&v))); +} + +#[test] +fn test_simple() { + cmp_hashmap_unordered("word", &[("word", 1)]); + cmp_hashmap_unordered("hello", &[("hello", 1)]); + cmp_hashmap_unordered("hello big world", &[("hello", 1), ("big", 1), ("world", 1)]); + cmp_hashmap_unordered("one of each", &[("one", 1), ("of", 1), ("each", 1)]); + cmp_hashmap_unordered("Hello, 1, 2 HELLO", &[("hello", 2), ("1", 1), ("2", 1)]); + cmp_hashmap_unordered( + "Batman, BATMAN, batman, Stop stop", + &[("batman", 3), ("stop", 2)], + ); + cmp_hashmap_unordered( + " multiple whitespace", + &[("multiple", 1), ("whitespace", 1)], + ); +} + +#[test] +fn test_count_multiple_occurrences() { + cmp_hashmap_unordered( + "one fish two fish red fish blue fish", + &[("one", 1), ("fish", 4), ("two", 1), ("red", 1), ("blue", 1)], + ); +} + +#[test] +fn test_multi_lines() { + cmp_hashmap_unordered( + "Game\nNight\nTomorrow", + &[("game", 1), ("night", 1), ("tomorrow", 1)], + ); +} + +#[test] +fn test_punctuation() { + cmp_hashmap_unordered( + "keyboard : mouse on the desk : Computer!!&@$%^&", + &[ + ("keyboard", 1), + ("mouse", 1), + ("on", 1), + ("the", 1), + ("desk", 1), + ("computer", 1), + ], + ); +} + +#[test] +fn with_apostrophes() { + cmp_hashmap_unordered( + "First: don't laugh. Then: don't cry.", + &[ + ("first", 1), + ("don't", 2), + ("laugh", 1), + ("then", 1), + ("cry", 1), + ], + ); +} + +#[test] +fn test_apostrophe() { + cmp_hashmap_unordered( + "Joe can't tell between 'large' and large.", + &[ + ("joe", 1), + ("can't", 1), + ("tell", 1), + ("between", 1), + ("large", 2), + ("and", 1), + ], + ); +} diff --git a/tests/counting_words_test/src/main.rs b/tests/counting_words_test/src/main.rs deleted file mode 100644 index 41a9d67a..00000000 --- a/tests/counting_words_test/src/main.rs +++ /dev/null @@ -1,156 +0,0 @@ -/* -## counting_words - -### Instructions - -In this program you will have to create a function `counting_words` that -receives a `&str` and returns each word and the number of times it appears on the string. - -The program will count as a word the following: - -- A number like ("0" or "1234") will count as 1. -- A simple word or letter like ("a" or "they") will count as 1. -- Two simple words joined by a single apostrophe ("it's" or "they're") will count as 1. - -The program must respect the following rules: - -- The count is case insensitive ("HELLO", "Hello", and "hello") are 3 uses of the same word. -- All forms of punctuation have to be ignored except for the apostrophe if used like the example above. -- The words can be separated by any form of whitespace (ie "\t", "\n", " "). - -### Expected Function - -```rust -fn counting_words(words: &str) -> HashMap {} -``` - -### Usage - -Here is a possible program to test your function : - -```rust -use counting_words::counting_words; -use std::collections::HashMap; - -fn main() { - println!("{:?}", counting_words("Hello, world!")); - println!("{:?}", counting_words("“Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.” - ― Albert Einstein ")); - println!("{:?}", counting_words("Batman, BATMAN, batman, Stop stop")); -} -``` - -And its output: - -```console -student@ubuntu:~/[[ROOT]]/test$ cargo run -{"hello": 1, "world": 1} -{"and": 2, "human": 1, "universe": 2, "the": 2, "i\'m": 1, "about": 1, "einstein": 1, "are": 1, "infinite": 1, "sure": 1, "albert": 1, "two": 1, "things": 1, "not": 1, "stupidity": 1} -{"batman": 3, "stop": 2} -student@ubuntu:~/[[ROOT]]/test$ -``` -*/ - -use counting_words::*; -use std::collections::HashMap; - -fn main() { - println!("{:?}", counting_words("Hello, world!")); - println!("{:?}", counting_words("“Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.” - ― Albert Einstein ")); - println!("{:?}", counting_words("Batman, BATMAN, batman, Stop stop")); -} - -#[cfg(test)] -mod tests { - use super::*; - use test; - - fn test_counting(input: &str, expected: &[(&str, u32)]) { - let mut m: HashMap = counting_words(input); - for &(k, v) in expected.iter() { - assert_eq!( - (k, m.remove(&k.to_string().to_lowercase()).unwrap_or(0)), - (k, v) - ); - } - // may fail with a message that clearly shows all extra pairs in the map - assert_eq!(m.iter().collect::>(), vec![]); - } - #[test] - fn test_simple() { - test_counting("word", &[("word", 1)]); - test_counting("hello", &[("hello", 1)]); - test_counting("hello big world", &[("hello", 1), ("big", 1), ("world", 1)]); - test_counting("one of each", &[("one", 1), ("of", 1), ("each", 1)]); - test_counting("Hello, 1, 2 HELLO", &[("Hello", 2), ("1", 1), ("2", 1)]); - test_counting( - "Batman, BATMAN, batman, Stop stop", - &[("batman", 3), ("stop", 2)], - ); - test_counting( - " multiple whitespace", - &[("multiple", 1), ("whitespace", 1)], - ); - } - - #[test] - fn test_count_multiple_occurrences() { - test_counting( - "one fish two fish red fish blue fish", - &[("one", 1), ("fish", 4), ("two", 1), ("red", 1), ("blue", 1)], - ); - } - - #[test] - fn test_multi_lines() { - test_counting( - "Game\nNight\nTomorrow", - &[("Game", 1), ("Night", 1), ("Tomorrow", 1)], - ); - } - - #[test] - fn test_punctuation() { - test_counting( - "keyboard : mouse on the desk : Computer!!&@$%^&", - &[ - ("keyboard", 1), - ("mouse", 1), - ("on", 1), - ("the", 1), - ("desk", 1), - ("Computer", 1), - ], - ); - } - - #[test] - fn with_apostrophes() { - test_counting( - "First: don't laugh. Then: don't cry.", - &[ - ("first", 1), - ("don't", 2), - ("laugh", 1), - ("then", 1), - ("cry", 1), - ], - ); - } - - #[test] - fn test_apostrophe() { - test_counting( - "Joe can't tell between 'large' and large.", - &[ - ("joe", 1), - ("can't", 1), - ("tell", 1), - ("between", 1), - ("large", 2), - ("and", 1), - ], - ); - } -} diff --git a/tests/display_table_test/Cargo.toml b/tests/display_table_test/Cargo.toml index 2d4f3856..69ddd3ab 100644 --- a/tests/display_table_test/Cargo.toml +++ b/tests/display_table_test/Cargo.toml @@ -2,9 +2,9 @@ name = "display_table_test" version = "0.1.0" authors = ["Augusto "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -display_table = { path = "../../solutions/display_table" } \ No newline at end of file +display_table = { path = "../../solutions/display_table" } diff --git a/tests/display_table_test/src/lib.rs b/tests/display_table_test/src/lib.rs new file mode 100644 index 00000000..d8b910a5 --- /dev/null +++ b/tests/display_table_test/src/lib.rs @@ -0,0 +1,77 @@ +use display_table::*; + +#[test] +fn it_displays() { + let mut table = Table::new(); + table.headers = vec![ + "Name".to_string(), + "Last Name".to_string(), + "ID Number".to_string(), + ]; + table.add_row(&[ + "Ackerley".to_string(), + "Fillips".to_string(), + "123456789".to_string(), + ]); + table.add_row(&[ + "Adamaris".to_string(), + "Fillips".to_string(), + "1111123456789".to_string(), + ]); + table.add_row(&[ + "Ackerley".to_string(), + "Fillips".to_string(), + "123456789".to_string(), + ]); + assert_eq!( + table.to_string(), + "| Name | Last Name | ID Number |\n|----------+-----------+---------------|\n| Ackerley | Fillips | 123456789 |\n| Adamaris | Fillips | 1111123456789 |\n| Ackerley | Fillips | 123456789 |\n" + ); +} + +#[test] +fn display_table_with_no_headers() { + let table = Table::new(); + assert!(table.to_string().is_empty()); +} + +#[test] +fn display_table_with_headers_only() { + let mut table = Table::new(); + table.headers = vec![ + "Name".to_string(), + "Last Name".to_string(), + "ID Number".to_string(), + ]; + assert_eq!( + table.to_string(), + "| Name | Last Name | ID Number |\n|------+-----------+-----------|\n" + ); +} + +#[test] +fn display_second() { + let mut table = Table::new(); + table.headers = vec![ + "ID".to_string(), + "Car Brand".to_string(), + "Model".to_string(), + "Is Electric".to_string(), + ]; + table.add_row(&[ + "1".to_string(), + "Tesla".to_string(), + "Model 3".to_string(), + "True".to_string(), + ]); + table.add_row(&[ + "2".to_string(), + "Ford".to_string(), + "Focus".to_string(), + "False".to_string(), + ]); + assert_eq!( + table.to_string(), + "| ID | Car Brand | Model | Is Electric |\n|----+-----------+---------+-------------|\n| 1 | Tesla | Model 3 | True |\n| 2 | Ford | Focus | False |\n" + ); +} diff --git a/tests/display_table_test/src/main.rs b/tests/display_table_test/src/main.rs deleted file mode 100644 index 526f44d6..00000000 --- a/tests/display_table_test/src/main.rs +++ /dev/null @@ -1,106 +0,0 @@ -use display_table::Table; - -fn main() { - let mut table = Table::new(); - table.headers = vec![ - "ID".to_string(), - "Car Brand".to_string(), - "Model".to_string(), - "Is Electric".to_string(), - ]; - table.add_row(&[ - "1".to_string(), - "Tesla".to_string(), - "Model 3".to_string(), - "True".to_string(), - ]); - table.add_row(&[ - "2".to_string(), - "Ford".to_string(), - "Focus".to_string(), - "False".to_string(), - ]); - println!("{}", table); -} - -#[cfg(test)] -mod tests { - use display_table::*; - - #[test] - fn it_displays() { - let mut table = Table::new(); - table.headers = vec![ - "Name".to_string(), - "Last Name".to_string(), - "ID Number".to_string(), - ]; - table.add_row(&[ - "Ackerley".to_string(), - "Fillips".to_string(), - "123456789".to_string(), - ]); - table.add_row(&[ - "Adamaris".to_string(), - "Fillips".to_string(), - "1111123456789".to_string(), - ]); - table.add_row(&[ - "Ackerley".to_string(), - "Fillips".to_string(), - "123456789".to_string(), - ]); - assert_eq!( - table.to_string(), - "| Name | Last Name | ID Number |\n|----------+-----------+---------------|\n| Ackerley | Fillips | 123456789 |\n| Adamaris | Fillips | 1111123456789 |\n| Ackerley | Fillips | 123456789 |\n" - ); - } - - // An empty table must not display anything - #[test] - fn display_table_with_no_headers() { - let table = Table::new(); - assert_eq!(table.to_string(), ""); - } - - #[test] - fn display_table_with_headers_only() { - let mut table = Table::new(); - table.headers = vec![ - "Name".to_string(), - "Last Name".to_string(), - "ID Number".to_string(), - ]; - assert_eq!( - table.to_string(), - "| Name | Last Name | ID Number |\n|------+-----------+-----------|\n" - ); - } - - #[test] - fn display_second() { - let mut table = Table::new(); - table.headers = vec![ - "ID".to_string(), - "Car Brand".to_string(), - "Model".to_string(), - "Is Electric".to_string(), - ]; - table.add_row(&[ - "1".to_string(), - "Tesla".to_string(), - "Model 3".to_string(), - "True".to_string(), - ]); - table.add_row(&[ - "2".to_string(), - "Ford".to_string(), - "Focus".to_string(), - "False".to_string(), - ]); - assert_eq!( - table.to_string(), - "| ID | Car Brand | Model | Is Electric |\n|----+-----------+---------+-------------|\n| 1 | Tesla | Model 3 | True |\n| 2 | Ford | Focus | False |\n" - ); - } -} diff --git a/tests/dress_code_test/Cargo.toml b/tests/dress_code_test/Cargo.toml index 2b316235..9837003c 100644 --- a/tests/dress_code_test/Cargo.toml +++ b/tests/dress_code_test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "dress_code_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/dress_code_test/src/lib.rs b/tests/dress_code_test/src/lib.rs new file mode 100644 index 00000000..e9d33f52 --- /dev/null +++ b/tests/dress_code_test/src/lib.rs @@ -0,0 +1,55 @@ +use dress_code::*; + +#[test] +fn test_choose_outfit_case_1() { + let exp_outfit = Outfit { + jacket: Jacket::Black, + hat: Hat::Fedora, + }; + assert_eq!(exp_outfit, choose_outfit(Some(0), Ok("someting"))); +} + +#[test] +fn test_choose_outfit_case_2() { + let exp_outfit = Outfit { + jacket: Jacket::White, + hat: Hat::Fedora, + }; + assert_eq!(exp_outfit, choose_outfit(Some(1), Ok("someting"))); +} + +#[test] +fn test_choose_outfit_case_3() { + let exp_outfit = Outfit { + jacket: Jacket::Black, + hat: Hat::Snapback, + }; + assert_eq!(exp_outfit, choose_outfit(Some(0), Err("someting"))); +} + +#[test] +fn test_choose_outfit_case_4() { + let exp_outfit = Outfit { + jacket: Jacket::White, + hat: Hat::Snapback, + }; + assert_eq!(exp_outfit, choose_outfit(Some(10), Err("someting"))); +} + +#[test] +fn test_choose_outfit_case_5() { + let exp_outfit = Outfit { + jacket: Jacket::Flowers, + hat: Hat::Baseball, + }; + assert_eq!(exp_outfit, choose_outfit(None, Err("someting"))); +} + +#[test] +fn test_choose_outfit_case_6() { + let exp_outfit = Outfit { + jacket: Jacket::Flowers, + hat: Hat::Fedora, + }; + assert_eq!(exp_outfit, choose_outfit(None, Ok("someting"))); +} diff --git a/tests/dress_code_test/src/main.rs b/tests/dress_code_test/src/main.rs deleted file mode 100644 index cb814f61..00000000 --- a/tests/dress_code_test/src/main.rs +++ /dev/null @@ -1,61 +0,0 @@ -use dress_code::*; - -fn main() { - println!( - "My outfit will be: {:?}", - choose_outfit(Some(0), Ok("Dear friend, ...")) - ); -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn test_choose_outfit_case_1() { - let exp_outfit = Outfit { - jacket: Jacket::Black, - hat: Hat::Fedora, - }; - assert_eq!(exp_outfit, choose_outfit(Some(0), Ok("someting"))); - } - #[test] - fn test_choose_outfit_case_2() { - let exp_outfit = Outfit { - jacket: Jacket::White, - hat: Hat::Fedora, - }; - assert_eq!(exp_outfit, choose_outfit(Some(1), Ok("someting"))); - } - #[test] - fn test_choose_outfit_case_3() { - let exp_outfit = Outfit { - jacket: Jacket::Black, - hat: Hat::Snapback, - }; - assert_eq!(exp_outfit, choose_outfit(Some(0), Err("someting"))); - } - #[test] - fn test_choose_outfit_case_4() { - let exp_outfit = Outfit { - jacket: Jacket::White, - hat: Hat::Snapback, - }; - assert_eq!(exp_outfit, choose_outfit(Some(10), Err("someting"))); - } - #[test] - fn test_choose_outfit_case_5() { - let exp_outfit = Outfit { - jacket: Jacket::Flowers, - hat: Hat::Baseball, - }; - assert_eq!(exp_outfit, choose_outfit(None, Err("someting"))); - } - #[test] - fn test_choose_outfit_case_6() { - let exp_outfit = Outfit { - jacket: Jacket::Flowers, - hat: Hat::Fedora, - }; - assert_eq!(exp_outfit, choose_outfit(None, Ok("someting"))); - } -} diff --git a/tests/filter_table_test/Cargo.toml b/tests/filter_table_test/Cargo.toml index c7597059..af9ac7fa 100644 --- a/tests/filter_table_test/Cargo.toml +++ b/tests/filter_table_test/Cargo.toml @@ -2,9 +2,9 @@ name = "filter_table_test" version = "0.1.0" authors = ["Augusto "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -filter_table = { path = "../../solutions/filter_table" } \ No newline at end of file +filter_table = { path = "../../solutions/filter_table" } diff --git a/tests/filter_table_test/src/lib.rs b/tests/filter_table_test/src/lib.rs new file mode 100644 index 00000000..e3b2f3cb --- /dev/null +++ b/tests/filter_table_test/src/lib.rs @@ -0,0 +1,88 @@ +use filter_table::*; + +#[test] +fn filtering_columns() { + let mut table = Table::new(); + table.headers = vec![ + "name".to_owned(), + "lastname".to_owned(), + "id number".to_owned(), + ]; + table.add_row(&[ + "Ackerley".to_owned(), + "Philips".to_owned(), + "123456789".to_owned(), + ]); + table.add_row(&[ + "Adamaris".to_owned(), + "Philips".to_owned(), + "1111123456789".to_owned(), + ]); + table.add_row(&[ + "Ackerley".to_owned(), + "Philips".to_owned(), + "123456789".to_owned(), + ]); + + let new_table = Table { + headers: vec!["name".to_owned()], + body: vec![ + vec!["Ackerley".to_owned()], + vec!["Adamaris".to_owned()], + vec!["Ackerley".to_owned()], + ], + }; + assert_eq!(new_table, table.filter_col(|c| c == "name").unwrap()); +} + +#[test] +fn filtering_rows() { + let tab = Table { + headers: vec![ + "Name".to_owned(), + "Last Name".to_owned(), + "ID Number".to_owned(), + ], + body: vec![ + vec![ + "Adamaris".to_owned(), + "Philips".to_owned(), + "1111123456789".to_owned(), + ], + vec![ + "Thomas".to_owned(), + "Shelby".to_owned(), + "123456789".to_owned(), + ], + vec![ + "Ackerley".to_owned(), + "Philips".to_owned(), + "123456789".to_owned(), + ], + ], + }; + + let expected_table = Table { + headers: vec![ + "Name".to_string(), + "Last Name".to_string(), + "ID Number".to_string(), + ], + body: vec![ + vec![ + "Adamaris".to_string(), + "Philips".to_string(), + "1111123456789".to_string(), + ], + vec![ + "Ackerley".to_string(), + "Philips".to_string(), + "123456789".to_string(), + ], + ], + }; + assert_eq!( + tab.filter_row("Last Name", |s| s == "Philips").unwrap(), + expected_table + ); +} diff --git a/tests/filter_table_test/src/main.rs b/tests/filter_table_test/src/main.rs deleted file mode 100644 index 8b3731b0..00000000 --- a/tests/filter_table_test/src/main.rs +++ /dev/null @@ -1,126 +0,0 @@ -use filter_table::Table; - -fn main() { - let mut table = Table::new(); - table.headers = vec![ - "Name".to_string(), - "Last Name".to_string(), - "ID Number".to_string(), - ]; - table.add_row(&[ - "Adam".to_string(), - "Philips".to_string(), - "123456789".to_string(), - ]); - table.add_row(&[ - "Adamaris".to_string(), - "Shelby".to_string(), - "1111123456789".to_string(), - ]); - table.add_row(&[ - "Ackerley".to_string(), - "Philips".to_string(), - "123456789".to_string(), - ]); - let filter_names = |col: &str| col == "Name"; - println!("{:?}", table.filter_col(filter_names)); - - let filter_philips = |lastname: &str| lastname == "Philips"; - println!("{:?}", table.filter_row("Last Name", filter_philips)); -} - -#[cfg(test)] -mod tests { - use filter_table::*; - - #[test] - fn filtering_columns() { - let mut table = Table::new(); - table.headers = vec![ - "name".to_string(), - "lastname".to_string(), - "id number".to_string(), - ]; - table.add_row(&[ - "Ackerley".to_string(), - "Philips".to_string(), - "123456789".to_string(), - ]); - table.add_row(&[ - "Adamaris".to_string(), - "Philips".to_string(), - "1111123456789".to_string(), - ]); - table.add_row(&[ - "Ackerley".to_string(), - "Philips".to_string(), - "123456789".to_string(), - ]); - - let filter = |col: &str| col == "name"; - - let new_table = Table { - headers: vec!["name".to_string()], - body: vec![ - vec!["Ackerley".to_string()], - vec!["Adamaris".to_string()], - vec!["Ackerley".to_string()], - ], - }; - assert_eq!(new_table, table.filter_col(filter).unwrap()); - } - - #[test] - fn filtering_rows() { - let tab = Table { - headers: vec![ - "Name".to_string(), - "Last Name".to_string(), - "ID Number".to_string(), - ], - body: vec![ - vec![ - "Adamaris".to_string(), - "Philips".to_string(), - "1111123456789".to_string(), - ], - vec![ - "Thomas".to_string(), - "Shelby".to_string(), - "123456789".to_string(), - ], - vec![ - "Ackerley".to_string(), - "Philips".to_string(), - "123456789".to_string(), - ], - ], - }; - - let get_fillips = |s: &str| s == "Philips"; - // filter the elements with last name Philips - let expected_table = Table { - headers: vec![ - "Name".to_string(), - "Last Name".to_string(), - "ID Number".to_string(), - ], - body: vec![ - vec![ - "Adamaris".to_string(), - "Philips".to_string(), - "1111123456789".to_string(), - ], - vec![ - "Ackerley".to_string(), - "Philips".to_string(), - "123456789".to_string(), - ], - ], - }; - assert_eq!( - tab.filter_row("Last Name", get_fillips).unwrap(), - expected_table - ); - } -} diff --git a/tests/format_me_test/Cargo.toml b/tests/format_me_test/Cargo.toml index 86f175da..70e00421 100644 --- a/tests/format_me_test/Cargo.toml +++ b/tests/format_me_test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "format_me_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/format_me_test/src/lib.rs b/tests/format_me_test/src/lib.rs new file mode 100644 index 00000000..b97fca7d --- /dev/null +++ b/tests/format_me_test/src/lib.rs @@ -0,0 +1,49 @@ +use format_me::*; + +#[test] +fn test_park() { + let park = Park { + name: Some("Central Park".to_owned()), + park_type: ParkType::Garden, + address: Some("Av. Sidónio Pais 4".to_owned()), + cap: Some("1050-214".to_owned()), + state: Some("Portugal".to_owned()), + }; + + assert_eq!( + park.to_string(), + "garden - Central Park, Av. Sidónio Pais 4, 1050-214 - Portugal" + ); +} + +#[test] +fn test_empty_name() { + let park = Park { + name: None, + park_type: ParkType::Forest, + address: Some("Av. Sidónio Pais 4".to_owned()), + cap: Some("1050-214".to_owned()), + state: Some("Portugal".to_owned()), + }; + + assert_eq!( + park.to_string(), + "forest - No name, Av. Sidónio Pais 4, 1050-214 - Portugal" + ); +} + +#[test] +fn test_empty_all() { + let park = Park { + name: None, + park_type: ParkType::Playground, + address: None, + cap: None, + state: None, + }; + + assert_eq!( + park.to_string(), + "playground - No name, No address, No cap - No state" + ); +} diff --git a/tests/format_me_test/src/main.rs b/tests/format_me_test/src/main.rs deleted file mode 100644 index ee1c0040..00000000 --- a/tests/format_me_test/src/main.rs +++ /dev/null @@ -1,77 +0,0 @@ -use format_me::*; - -fn main() { - println!( - "{}", - Park { - name: "Les Tuileries".to_string(), - park_type: ParkType::Garden, - address: "Pl. de la Concorde".to_string(), - cap: "75001".to_string(), - state: "France".to_string() - } - ); - println!( - "{}", - Park { - name: "".to_string(), - park_type: ParkType::Playground, - address: "".to_string(), - cap: "".to_string(), - state: "".to_string() - } - ); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_park() { - let park = Park { - name: "Central Park".to_string(), - park_type: ParkType::Garden, - address: "Av. Sidónio Pais 4".to_string(), - cap: "1050-214".to_string(), - state: "Portugal".to_string(), - }; - - assert_eq!( - park.to_string(), - "garden - Central Park, Av. Sidónio Pais 4, 1050-214 - Portugal" - ); - } - - #[test] - fn test_empty_name() { - let park = Park { - name: "".to_string(), - park_type: ParkType::Forest, - address: "Av. Sidónio Pais 4".to_string(), - cap: "1050-214".to_string(), - state: "Portugal".to_string(), - }; - - assert_eq!( - park.to_string(), - "forest - No name, Av. Sidónio Pais 4, 1050-214 - Portugal" - ); - } - - #[test] - fn test_empty_all() { - let park = Park { - name: "".to_string(), - park_type: ParkType::Playground, - address: "".to_string(), - cap: "".to_string(), - state: "".to_string(), - }; - - assert_eq!( - park.to_string(), - "playground - No name, No address, No cap - No state" - ); - } -} diff --git a/tests/get_document_id_test/Cargo.toml b/tests/get_document_id_test/Cargo.toml index 0199e97e..4d28b6bb 100644 --- a/tests/get_document_id_test/Cargo.toml +++ b/tests/get_document_id_test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "get_document_id_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/get_document_id_test/src/lib.rs b/tests/get_document_id_test/src/lib.rs new file mode 100644 index 00000000..d50f73f4 --- /dev/null +++ b/tests/get_document_id_test/src/lib.rs @@ -0,0 +1,58 @@ +use get_document_id::*; + +#[test] +fn test_get_document_id_ok() { + let office = OfficeOne { + next_office: Ok(OfficeTwo { + next_office: Ok(OfficeThree { + next_office: Ok(OfficeFour { + document_id: Ok(13), + }), + }), + }), + }; + + assert_eq!(Ok(13), office.get_document_id()); +} + +#[test] +fn test_get_document_id_closed() { + let office = { + OfficeOne { + next_office: Ok(OfficeTwo { + next_office: Err(ErrorOffice::OfficeClose(2)), + }), + } + }; + + assert_eq!(Err(ErrorOffice::OfficeClose(2)), office.get_document_id()); +} + +#[test] +fn test_get_document_id_not_found() { + let office = { + OfficeOne { + next_office: Ok(OfficeTwo { + next_office: Err(ErrorOffice::OfficeNotFound(2)), + }), + } + }; + + assert_eq!( + Err(ErrorOffice::OfficeNotFound(2)), + office.get_document_id() + ); +} + +#[test] +fn test_get_document_id_full() { + let office = { + OfficeOne { + next_office: Ok(OfficeTwo { + next_office: Err(ErrorOffice::OfficeFull(2)), + }), + } + }; + + assert_eq!(Err(ErrorOffice::OfficeFull(2)), office.get_document_id()); +} diff --git a/tests/get_document_id_test/src/main.rs b/tests/get_document_id_test/src/main.rs deleted file mode 100644 index 2a66c554..00000000 --- a/tests/get_document_id_test/src/main.rs +++ /dev/null @@ -1,88 +0,0 @@ -use get_document_id::*; - -fn main() { - let office_ok = OfficeOne { - next_office: Ok(OfficeTwo { - next_office: Ok(OfficeThree { - next_office: Ok(OfficeFour { - document_id: Ok(13), - }), - }), - }), - }; - let office_closed = { - OfficeOne { - next_office: Ok(OfficeTwo { - next_office: Err(ErrorOffice::OfficeClose(23)), - }), - } - }; - - match office_ok.get_document_id() { - Ok(id) => println!("Found a document with id {}", id), - Err(err) => println!("Error: {:?}", err), - }; - match office_closed.get_document_id() { - Ok(id) => println!("Found a document with id {}", id), - Err(err) => println!("Error: {:?}", err), - }; -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_get_document_id_ok() { - let office = OfficeOne { - next_office: Ok(OfficeTwo { - next_office: Ok(OfficeThree { - next_office: Ok(OfficeFour { - document_id: Ok(13), - }), - }), - }), - }; - - assert_eq!(Ok(13), office.get_document_id()); - } - #[test] - fn test_get_document_id_closed() { - let office = { - OfficeOne { - next_office: Ok(OfficeTwo { - next_office: Err(ErrorOffice::OfficeClose(2)), - }), - } - }; - - assert_eq!(Err(ErrorOffice::OfficeClose(2)), office.get_document_id()); - } - #[test] - fn test_get_document_id_not_found() { - let office = { - OfficeOne { - next_office: Ok(OfficeTwo { - next_office: Err(ErrorOffice::OfficeNotFound(2)), - }), - } - }; - - assert_eq!( - Err(ErrorOffice::OfficeNotFound(2)), - office.get_document_id() - ); - } - #[test] - fn test_get_document_id_full() { - let office = { - OfficeOne { - next_office: Ok(OfficeTwo { - next_office: Err(ErrorOffice::OfficeFull(2)), - }), - } - }; - - assert_eq!(Err(ErrorOffice::OfficeFull(2)), office.get_document_id()); - } -} diff --git a/tests/lucas_number_test/Cargo.toml b/tests/lucas_number_test/Cargo.toml index 40d892ce..118862f2 100644 --- a/tests/lucas_number_test/Cargo.toml +++ b/tests/lucas_number_test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lucas_number_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/lucas_number_test/src/lib.rs b/tests/lucas_number_test/src/lib.rs new file mode 100644 index 00000000..d494d352 --- /dev/null +++ b/tests/lucas_number_test/src/lib.rs @@ -0,0 +1,10 @@ +use lucas_number::*; + +#[test] +fn lucas_number_test() { + assert_eq!(lucas_number(2), 3); + assert_eq!(lucas_number(5), 11); + assert_eq!(lucas_number(10), 123); + assert_eq!(lucas_number(13), 521); + assert_eq!(lucas_number(25), 167761); +} diff --git a/tests/lucas_number_test/src/main.rs b/tests/lucas_number_test/src/main.rs deleted file mode 100644 index c122811d..00000000 --- a/tests/lucas_number_test/src/main.rs +++ /dev/null @@ -1,38 +0,0 @@ -use lucas_number::lucas_number; - -fn main() { - println!( - "The element in the position {} in Lucas Numbers is {}", - 2, - lucas_number(2) - ); - println!( - "The element in the position {} in Lucas Numbers is {}", - 5, - lucas_number(5) - ); - println!( - "The element in the position {} in Lucas Numbers is {}", - 10, - lucas_number(10) - ); - println!( - "The element in the position {} in Lucas Numbers is {}", - 13, - lucas_number(13) - ); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn lucas_number_test() { - assert_eq!(lucas_number(2), 3); - assert_eq!(lucas_number(5), 11); - assert_eq!(lucas_number(10), 123); - assert_eq!(lucas_number(13), 521); - assert_eq!(lucas_number(25), 167761); - } -} diff --git a/tests/lunch_queue_test/Cargo.toml b/tests/lunch_queue_test/Cargo.toml index 298ea5b7..0ee67da1 100644 --- a/tests/lunch_queue_test/Cargo.toml +++ b/tests/lunch_queue_test/Cargo.toml @@ -2,7 +2,7 @@ name = "lunch_queue_test" version = "0.1.0" authors = ["lee "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/lunch_queue_test/src/lib.rs b/tests/lunch_queue_test/src/lib.rs new file mode 100644 index 00000000..cbdb4bbe --- /dev/null +++ b/tests/lunch_queue_test/src/lib.rs @@ -0,0 +1,79 @@ +use lunch_queue::*; + +#[test] +fn test_new() { + let list = Queue::new(); + assert!(list.node.is_none()); +} + +#[test] +fn test_one_person() { + let mut list = Queue::new(); + list.add(String::from("Marie"), 14); + list.rm(); + assert!(list.node.is_none()); +} + +#[test] +fn test_two_person() { + let mut list = Queue::new(); + list.add(String::from("Marie"), 13); + list.add(String::from("Monica"), 54); + list.rm(); + + assert_eq!(list.node.as_ref().unwrap().name, "Monica"); + assert_eq!(list.node.as_ref().unwrap().discount, 54); +} + +#[test] +fn test_more_person() { + let mut list = Queue::new(); + list.add(String::from("Marie"), 20); + list.add(String::from("Monica"), 15); + list.add(String::from("Ana"), 5); + list.add(String::from("Alice"), 35); + list.rm(); + + assert_eq!(list.node.as_ref().unwrap().name, "Alice"); + assert_eq!(list.node.as_ref().unwrap().discount, 35); + + list.rm(); + list.rm(); + assert_eq!(list.node.as_ref().unwrap().name, "Alice"); + assert_eq!(list.node.as_ref().unwrap().discount, 35); +} + +#[test] +fn test_search() { + let mut list = Queue::new(); + list.add(String::from("Marie"), 20); + list.add(String::from("Monica"), 15); + list.add(String::from("Ana"), 5); + list.add(String::from("Alice"), 35); + + assert_eq!(list.search("Ana"), Some((&String::from("Ana"), &5))); + + assert_eq!(list.search("Monica"), Some((&String::from("Monica"), &15))); + + assert_eq!(list.search("Alice"), Some((&String::from("Alice"), &35))); + + assert_eq!(list.search("someone_that_does_not_exist"), None); +} + +#[test] +fn test_invert() { + let mut list = Queue::new(); + list.add(String::from("Marie"), 20); + list.add(String::from("Monica"), 15); + list.add(String::from("Ana"), 5); + list.add(String::from("Alice"), 35); + + list.invert_queue(); + assert_eq!(list.node.as_ref().unwrap().name, "Marie"); + assert_eq!(list.node.as_ref().unwrap().discount, 20); + + list.rm(); + list.invert_queue(); + assert_eq!(list.node.as_ref().unwrap().name, "Ana"); + assert_eq!(list.node.as_ref().unwrap().discount, 5); +} diff --git a/tests/lunch_queue_test/src/main.rs b/tests/lunch_queue_test/src/main.rs deleted file mode 100644 index 91403bcf..00000000 --- a/tests/lunch_queue_test/src/main.rs +++ /dev/null @@ -1,113 +0,0 @@ -use lunch_queue::*; - -// Example : -fn main() { - let mut list = Queue::new(); - list.add(String::from("Marie"), 20); - list.add(String::from("Monica"), 15); - list.add(String::from("Ana"), 5); - list.add(String::from("Alice"), 35); - println!("{:?}", list); - - // output: - // Queue { node: Some(Person { name: "Alice", discount: 35, next_person: Some(Person { name: "Ana", discount: 5, next_person: Some(Person { name: "Monica", discount: 15, next_person: Some(Person { name: "Marie", discount: 20, next_person: None }) }) }) }) } - println!("{:?}", list.search("Marie")); - println!("{:?}", list.search("Alice")); - println!("{:?}", list.search("someone")); - // output: - // Some(("Marie", 20)) - // Some(("Alice", 35)) - // None - - println!("removed {:?}", list.rm()); - println!("removed {:?}", list.rm()); - println!("list {:?}", list); - list.invert_queue(); - println!("inverted list {:?}", list); - // output: - // removed Some(("Marie", 20)) - // list Queue { node: Some(Person { name: "Alice", discount: 35, next_person: Some(Person { name: "Ana", discount: 5, next_person: Some(Person { name: "Monica", discount: 15, next_person: None }) }) }) } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_new() { - let list = Queue::new(); - assert!(list.node.is_none()); - } - - #[test] - fn test_one_person() { - let mut list = Queue::new(); - list.add(String::from("Marie"), 14); - list.rm(); - assert!(list.node.is_none()); - } - - #[test] - fn test_two_person() { - let mut list = Queue::new(); - list.add(String::from("Marie"), 13); - list.add(String::from("Monica"), 54); - list.rm(); - - assert_eq!(list.node.as_ref().unwrap().name, "Monica"); - assert_eq!(list.node.as_ref().unwrap().discount, 54); - } - - #[test] - fn test_more_person() { - let mut list = Queue::new(); - list.add(String::from("Marie"), 20); - list.add(String::from("Monica"), 15); - list.add(String::from("Ana"), 5); - list.add(String::from("Alice"), 35); - list.rm(); - - assert_eq!(list.node.as_ref().unwrap().name, "Alice"); - assert_eq!(list.node.as_ref().unwrap().discount, 35); - - list.rm(); - list.rm(); - assert_eq!(list.node.as_ref().unwrap().name, "Alice"); - assert_eq!(list.node.as_ref().unwrap().discount, 35); - } - - #[test] - fn test_search() { - let mut list = Queue::new(); - list.add(String::from("Marie"), 20); - list.add(String::from("Monica"), 15); - list.add(String::from("Ana"), 5); - list.add(String::from("Alice"), 35); - - assert_eq!(list.search("Ana"), Some((String::from("Ana"), 5))); - - assert_eq!(list.search("Monica"), Some((String::from("Monica"), 15))); - - assert_eq!(list.search("Alice"), Some((String::from("Alice"), 35))); - - assert_eq!(list.search("someone_that_does_not_exist"), None); - } - - #[test] - fn test_invert() { - let mut list = Queue::new(); - list.add(String::from("Marie"), 20); - list.add(String::from("Monica"), 15); - list.add(String::from("Ana"), 5); - list.add(String::from("Alice"), 35); - - list.invert_queue(); - assert_eq!(list.node.as_ref().unwrap().name, "Marie"); - assert_eq!(list.node.as_ref().unwrap().discount, 20); - - list.rm(); - list.invert_queue(); - assert_eq!(list.node.as_ref().unwrap().name, "Ana"); - assert_eq!(list.node.as_ref().unwrap().discount, 5); - } -} diff --git a/tests/matrix_determinant_test/Cargo.toml b/tests/matrix_determinant_test/Cargo.toml index 17015c95..357d1cb0 100644 --- a/tests/matrix_determinant_test/Cargo.toml +++ b/tests/matrix_determinant_test/Cargo.toml @@ -2,7 +2,7 @@ name = "matrix_determinant_test" version = "0.1.0" authors = ["OGordoo "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/matrix_determinant_test/src/lib.rs b/tests/matrix_determinant_test/src/lib.rs new file mode 100644 index 00000000..c33778bd --- /dev/null +++ b/tests/matrix_determinant_test/src/lib.rs @@ -0,0 +1,25 @@ +use matrix_determinant::*; + +#[test] +fn positive_values() { + assert_eq!(0, matrix_determinant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])); + assert_eq!(15, matrix_determinant([[6, 5, 4], [4, 6, 9], [1, 1, 2]])); + assert_eq!(-1, matrix_determinant([[3, 0, 1], [4, 1, 2], [3, 2, 2]])); +} + +#[test] +fn also_negatvies() { + assert_eq!(29, matrix_determinant([[1, -2, 2], [-1, 3, 6], [-3, 4, 7]])); + assert_eq!( + 48, + matrix_determinant([[-6, -1, 5], [-3, 2, 2], [1, 5, -5]]) + ); +} + +#[test] +fn big_numbers() { + assert_eq!( + -1808088, + matrix_determinant([[167, 181, 150], [164, 85, 111], [52, 91, 177]]) + ); +} diff --git a/tests/matrix_determinant_test/src/main.rs b/tests/matrix_determinant_test/src/main.rs deleted file mode 100644 index 68b8aee4..00000000 --- a/tests/matrix_determinant_test/src/main.rs +++ /dev/null @@ -1,39 +0,0 @@ -use matrix_determinant::*; - -fn main() { - let matrix = [[1, 2, 4], [2, -1, 3], [4, 0, 1]]; - - println!( - "The determinant of the matrix:\n|1 2 4|\n|2 -1 3| = {}\n|4 0 1|\n", - matrix_determinant(matrix) - ); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn positive_values() { - assert_eq!(0, matrix_determinant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])); - assert_eq!(15, matrix_determinant([[6, 5, 4], [4, 6, 9], [1, 1, 2]])); - assert_eq!(-1, matrix_determinant([[3, 0, 1], [4, 1, 2], [3, 2, 2]])); - } - - #[test] - fn also_negatvies() { - assert_eq!(29, matrix_determinant([[1, -2, 2], [-1, 3, 6], [-3, 4, 7]])); - assert_eq!( - 48, - matrix_determinant([[-6, -1, 5], [-3, 2, 2], [1, 5, -5]]) - ); - } - - #[test] - fn big_numbers() { - assert_eq!( - -1808088, - matrix_determinant([[167, 181, 150], [164, 85, 111], [52, 91, 177]]) - ); - } -} diff --git a/tests/matrix_display_test/Cargo.toml b/tests/matrix_display_test/Cargo.toml index 0bd9cc4e..cdea7c7f 100644 --- a/tests/matrix_display_test/Cargo.toml +++ b/tests/matrix_display_test/Cargo.toml @@ -2,10 +2,9 @@ name = "matrix_display_test" version = "0.1.0" authors = ["Augusto "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] matrix_display = { path = "../../solutions/matrix_display"} -lib = { path = "../lib" } diff --git a/tests/matrix_display_test/src/lib.rs b/tests/matrix_display_test/src/lib.rs new file mode 100644 index 00000000..4582ba47 --- /dev/null +++ b/tests/matrix_display_test/src/lib.rs @@ -0,0 +1,35 @@ +use matrix_display::*; + +#[test] +fn it_works() { + assert_eq!( + Matrix::new(&[&[1, 2, 3], &[4, 5, 6], &[7, 8, 9]]).to_string(), + "(1 2 3)\n(4 5 6)\n(7 8 9)" + ); +} + +#[test] +fn test_matrix_col() { + assert_eq!( + Matrix::new(&[&[1], &[2], &[3]]).to_string(), + "(1)\n(2)\n(3)" + ); +} + +#[test] +fn test_matrix_row() { + assert_eq!(Matrix::new(&[&[1, 2, 3]]).to_string(), "(1 2 3)"); +} + +#[test] +fn test_m_by_n_matrix() { + assert_eq!( + Matrix::new(&[&[1, 2, 3, 4, 5], &[6, 7, 8, 9, 10], &[11, 12, 13, 14, 15]]).to_string(), + "(1 2 3 4 5)\n(6 7 8 9 10)\n(11 12 13 14 15)" + ); +} + +#[test] +fn test_empty_matrix() { + assert_eq!(Matrix::new(&[&[]]).to_string(), "()"); +} diff --git a/tests/matrix_display_test/src/main.rs b/tests/matrix_display_test/src/main.rs deleted file mode 100644 index 7fa5883c..00000000 --- a/tests/matrix_display_test/src/main.rs +++ /dev/null @@ -1,79 +0,0 @@ -// Implement the std::fmt::Display trait for a matrix of i32 -// using the struct Matrix define the associated function new that -// creates a new Matrix from &[&[i32]] -// After implement the std::fmt::Display trait to print the matrix -// like this - -// ``` -// (1 2 3) -// (4 5 6) -// (7 8 9) -// ``` - -use matrix_display::*; - -fn main() { - let matrix = Matrix::new(&[&[1, 2, 3], &[4, 5, 6], &[7, 8, 9]]); - println!("{}", matrix); -} - -#[cfg(test)] -mod tests { - use lib::{Kind, TestProperties}; - use matrix_display::*; - - #[test] - fn it_works() { - let matrix = Matrix::new(&[&[1, 2, 3], &[4, 5, 6], &[7, 8, 9]]); - let display = String::from("(1 2 3)\n(4 5 6)\n(7 8 9)"); - let test = TestProperties { - kind: Kind::Method, - name: "to_string", - }; - test.assert_with_message(&[Box::new(matrix.clone())], matrix.to_string(), display); - } - - #[test] - fn test_matrix_col() { - let matrix = Matrix::new(&[&[1], &[2], &[3]]); - let display = String::from("(1)\n(2)\n(3)"); - let test = TestProperties { - kind: Kind::Method, - name: "to_string", - }; - test.assert_with_message(&[Box::new(matrix.clone())], matrix.to_string(), display); - } - - #[test] - fn test_matrix_row() { - let matrix = Matrix::new(&[&[1, 2, 3]]); - let display = String::from("(1 2 3)"); - let test = TestProperties { - kind: Kind::Method, - name: "to_string", - }; - test.assert_with_message(&[Box::new(matrix.clone())], matrix.to_string(), display); - } - - #[test] - fn test_m_by_n_matrix() { - let matrix = Matrix::new(&[&[1, 2, 3, 4, 5], &[6, 7, 8, 9, 10], &[11, 12, 13, 14, 15]]); - let display = String::from("(1 2 3 4 5)\n(6 7 8 9 10)\n(11 12 13 14 15)"); - let test = TestProperties { - kind: Kind::Method, - name: "to_string", - }; - test.assert_with_message(&[Box::new(matrix.clone())], matrix.to_string(), display); - } - - #[test] - fn test_empty_matrix() { - let matrix = Matrix::new(&[&[]]); - let display = String::from("()"); - let test = TestProperties { - kind: Kind::Method, - name: "to_string", - }; - test.assert_with_message(&[Box::new(matrix.clone())], matrix.to_string(), display); - } -} diff --git a/tests/modify_letter_test/Cargo.toml b/tests/modify_letter_test/Cargo.toml index 88b941e3..c9078961 100644 --- a/tests/modify_letter_test/Cargo.toml +++ b/tests/modify_letter_test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "modify_letter_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/modify_letter_test/src/lib.rs b/tests/modify_letter_test/src/lib.rs new file mode 100644 index 00000000..21d4b662 --- /dev/null +++ b/tests/modify_letter_test/src/lib.rs @@ -0,0 +1,50 @@ +use modify_letter::*; + +#[test] +fn test_remove_letter_sensitive() { + assert_eq!( + remove_letter_sensitive("Jijm jis mijssjing", 'j'), + "Jim is missing" + ); + assert_eq!( + remove_letter_sensitive("Jack is missing", 'j'), + "Jack is missing" + ); + assert_eq!( + remove_letter_sensitive("Jjjijll jis mijssjjing", 'j'), + "Jill is missing" + ); +} + +#[test] +fn test_remove_letter_insensitive() { + assert_eq!( + remove_letter_insensitive("JaillA ais swiaAmmingA", 'A'), + "Jill is swimming" + ); + assert_eq!( + remove_letter_insensitive("Jim is swimming", 'A'), + "Jim is swimming" + ); + assert_eq!( + remove_letter_insensitive("JoaseA ais swiaAAAmmingA", 'A'), + "Jose is swimming" + ); +} + +#[test] +fn test_swap_letter_case() { + assert_eq!(swap_letter_case("AaBbCcDdEe", 'e'), "AaBbCcDdeE"); + assert_eq!(swap_letter_case("AaBbCcDd", 'e'), "AaBbCcDd"); + assert_eq!( + swap_letter_case("AaBbCcDdEEEeeeEeEe", 'e'), + "AaBbCcDdeeeEEEeEeE" + ); +} + +#[test] +fn test_empty_arguments() { + assert_eq!(remove_letter_sensitive("", 'a'), ""); + assert_eq!(remove_letter_insensitive("", 'b'), ""); + assert_eq!(swap_letter_case("", 'c'), ""); +} diff --git a/tests/modify_letter_test/src/main.rs b/tests/modify_letter_test/src/main.rs deleted file mode 100644 index a05f5f09..00000000 --- a/tests/modify_letter_test/src/main.rs +++ /dev/null @@ -1,60 +0,0 @@ -use modify_letter::*; - -fn main() { - println!("{}", remove_letter_sensitive("hEey hEey", 'e')); - println!("{}", remove_letter_insensitive("hEye", 'e')); - println!("{}", swap_letter_case("BbBb", 'b')); -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn test_remove_letter_sensitive() { - assert_eq!( - remove_letter_sensitive("Jijm jis mijssjing", 'j'), - "Jim is missing" - ); - assert_eq!( - remove_letter_sensitive("Jack is missing", 'j'), - "Jack is missing" - ); - assert_eq!( - remove_letter_sensitive("Jjjijll jis mijssjjing", 'j'), - "Jill is missing" - ); - } - - #[test] - fn test_remove_letter_insensitive() { - assert_eq!( - remove_letter_insensitive("JaillA ais swiaAmmingA", 'A'), - "Jill is swimming" - ); - assert_eq!( - remove_letter_insensitive("Jim is swimming", 'A'), - "Jim is swimming" - ); - assert_eq!( - remove_letter_insensitive("JoaseA ais swiaAAAmmingA", 'A'), - "Jose is swimming" - ); - } - - #[test] - fn test_swap_letter_case() { - assert_eq!(swap_letter_case("AaBbCcDdEe", 'e'), "AaBbCcDdeE"); - assert_eq!(swap_letter_case("AaBbCcDd", 'e'), "AaBbCcDd"); - assert_eq!( - swap_letter_case("AaBbCcDdEEEeeeEeEe", 'e'), - "AaBbCcDdeeeEEEeEeE" - ); - } - - #[test] - fn test_empty_arguments() { - assert_eq!(remove_letter_sensitive("", 'a'), ""); - assert_eq!(remove_letter_insensitive("", 'b'), ""); - assert_eq!(swap_letter_case("", 'c'), ""); - } -} diff --git a/tests/moving_targets_test/Cargo.toml b/tests/moving_targets_test/Cargo.toml index cb5f1da5..aa43cec0 100644 --- a/tests/moving_targets_test/Cargo.toml +++ b/tests/moving_targets_test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "moving_targets_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/moving_targets_test/src/lib.rs b/tests/moving_targets_test/src/lib.rs new file mode 100644 index 00000000..55fcd349 --- /dev/null +++ b/tests/moving_targets_test/src/lib.rs @@ -0,0 +1,45 @@ +use moving_targets::*; + +#[test] +fn test_push_pop() { + let mut field = Field::new(); + field.push(Target { size: 10, xp: 2 }); + field.push(Target { size: 5, xp: 1 }); + field.push(Target { size: 20, xp: 4 }); + + assert_eq!(field.pop().unwrap(), Target { size: 20, xp: 4 }); + assert_eq!(field.pop().unwrap(), Target { size: 5, xp: 1 }); + assert_eq!(field.pop().unwrap(), Target { size: 10, xp: 2 }); + assert_eq!(field.pop(), None); +} + +#[test] +fn test_peek() { + let mut field = Field::new(); + field.push(Target { size: 10, xp: 2 }); + field.push(Target { size: 5, xp: 1 }); + field.push(Target { size: 20, xp: 4 }); + + assert_eq!(*field.peek().unwrap(), Target { size: 20, xp: 4 }); + assert_eq!(field.pop().unwrap(), Target { size: 20, xp: 4 }); + assert_eq!(field.pop().unwrap(), Target { size: 5, xp: 1 }); + assert_eq!(*field.peek().unwrap(), Target { size: 10, xp: 2 }); + assert_eq!(*field.peek().unwrap(), Target { size: 10, xp: 2 }); +} + +#[test] +fn test_peek_mut() { + let mut field = Field::new(); + field.push(Target { size: 10, xp: 2 }); + field.push(Target { size: 5, xp: 1 }); + field.push(Target { size: 20, xp: 4 }); + + assert_eq!(*field.peek().unwrap(), Target { size: 20, xp: 4 }); + assert_eq!(field.pop().unwrap(), Target { size: 20, xp: 4 }); + assert_eq!(field.pop().unwrap(), Target { size: 5, xp: 1 }); + assert_eq!(*field.peek_mut().unwrap(), Target { size: 10, xp: 2 }); + + let last_target = field.peek_mut(); + last_target.map(|target| *target = Target { size: 50, xp: 44 }); + assert_eq!(*field.peek().unwrap(), Target { size: 50, xp: 44 }); +} diff --git a/tests/moving_targets_test/src/main.rs b/tests/moving_targets_test/src/main.rs deleted file mode 100644 index 8cef7151..00000000 --- a/tests/moving_targets_test/src/main.rs +++ /dev/null @@ -1,62 +0,0 @@ -use moving_targets::*; - -fn main() { - let mut field = Field::new(); - - println!("{:?}", field.pop()); - field.push(Target { size: 12, xp: 2 }); - println!("{:?}", *field.peek().unwrap()); - field.push(Target { size: 24, xp: 4 }); - println!("{:?}", field.pop()); - let last_target = field.peek_mut().unwrap(); - *last_target = Target { size: 2, xp: 0 }; - println!("{:?}", field.pop()); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_push_pop() { - let mut field = Field::new(); - field.push(Target { size: 10, xp: 2 }); - field.push(Target { size: 5, xp: 1 }); - field.push(Target { size: 20, xp: 4 }); - - assert_eq!(field.pop().unwrap(), Target { size: 20, xp: 4 }); - assert_eq!(field.pop().unwrap(), Target { size: 5, xp: 1 }); - assert_eq!(field.pop().unwrap(), Target { size: 10, xp: 2 }); - assert_eq!(field.pop(), None); - } - - #[test] - fn test_peek() { - let mut field = Field::new(); - field.push(Target { size: 10, xp: 2 }); - field.push(Target { size: 5, xp: 1 }); - field.push(Target { size: 20, xp: 4 }); - - assert_eq!(*field.peek().unwrap(), Target { size: 20, xp: 4 }); - assert_eq!(field.pop().unwrap(), Target { size: 20, xp: 4 }); - assert_eq!(field.pop().unwrap(), Target { size: 5, xp: 1 }); - assert_eq!(*field.peek().unwrap(), Target { size: 10, xp: 2 }); - assert_eq!(*field.peek().unwrap(), Target { size: 10, xp: 2 }); - } - - #[test] - fn test_peek_mut() { - let mut field = Field::new(); - field.push(Target { size: 10, xp: 2 }); - field.push(Target { size: 5, xp: 1 }); - field.push(Target { size: 20, xp: 4 }); - - assert_eq!(*field.peek().unwrap(), Target { size: 20, xp: 4 }); - assert_eq!(field.pop().unwrap(), Target { size: 20, xp: 4 }); - assert_eq!(field.pop().unwrap(), Target { size: 5, xp: 1 }); - assert_eq!(*field.peek_mut().unwrap(), Target { size: 10, xp: 2 }); - let last_target = field.peek_mut(); - last_target.map(|target| *target = Target { size: 50, xp: 44 }); - assert_eq!(*field.peek().unwrap(), Target { size: 50, xp: 44 }); - } -} diff --git a/tests/negative_spelling_test/Cargo.toml b/tests/negative_spelling_test/Cargo.toml index 12987aa5..e0de6b1c 100644 --- a/tests/negative_spelling_test/Cargo.toml +++ b/tests/negative_spelling_test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "negative_spelling_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/negative_spelling_test/src/lib.rs b/tests/negative_spelling_test/src/lib.rs new file mode 100644 index 00000000..97fa5b73 --- /dev/null +++ b/tests/negative_spelling_test/src/lib.rs @@ -0,0 +1,48 @@ +use negative_spelling::*; + +#[test] +fn test_short_numbers() { + assert_eq!(negative_spell(0), "zero"); + assert_eq!(negative_spell(-1), "minus one"); + assert_eq!(negative_spell(-14), "minus fourteen"); + assert_eq!(negative_spell(-20), "minus twenty"); + assert_eq!(negative_spell(-22), "minus twenty-two"); + assert_eq!(negative_spell(-101), "minus one hundred one"); + assert_eq!(negative_spell(-120), "minus one hundred twenty"); + assert_eq!(negative_spell(-123), "minus one hundred twenty-three"); +} + +#[test] +fn test_medium_numbers() { + assert_eq!(negative_spell(-1000), "minus one thousand"); + assert_eq!(negative_spell(-1055), "minus one thousand fifty-five"); + assert_eq!( + negative_spell(-1234), + "minus one thousand two hundred thirty-four" + ); + assert_eq!( + negative_spell(-10123), + "minus ten thousand one hundred twenty-three" + ); +} + +#[test] +fn test_long_numbers() { + assert_eq!( + negative_spell(-910112), + "minus nine hundred ten thousand one hundred twelve" + ); + assert_eq!( + negative_spell(-651123), + "minus six hundred fifty-one thousand one hundred twenty-three" + ); + + assert_eq!(negative_spell(-810000), "minus eight hundred ten thousand"); + assert_eq!(negative_spell(-1000000), "minus one million"); +} + +#[test] +fn test_invalid_numbers() { + assert_eq!(negative_spell(1), "error: positive number"); + assert_eq!(negative_spell(2390904), "error: positive number"); +} diff --git a/tests/negative_spelling_test/src/main.rs b/tests/negative_spelling_test/src/main.rs deleted file mode 100644 index 9e9f4166..00000000 --- a/tests/negative_spelling_test/src/main.rs +++ /dev/null @@ -1,70 +0,0 @@ -use negative_spelling::*; - -fn main() { - println!("{}", negative_spell(-1234)); - println!("{}", negative_spell(100)); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_short_numbers() { - assert_eq!(negative_spell(0), String::from("zero")); - assert_eq!(negative_spell(-1), String::from("minus one")); - assert_eq!(negative_spell(-14), String::from("minus fourteen")); - assert_eq!(negative_spell(-20), String::from("minus twenty")); - assert_eq!(negative_spell(-22), String::from("minus twenty-two")); - assert_eq!(negative_spell(-101), String::from("minus one hundred one")); - assert_eq!( - negative_spell(-120), - String::from("minus one hundred twenty") - ); - assert_eq!( - negative_spell(-123), - String::from("minus one hundred twenty-three") - ); - } - #[test] - fn test_medium_numbers() { - assert_eq!(negative_spell(-1000), String::from("minus one thousand")); - assert_eq!( - negative_spell(-1055), - String::from("minus one thousand fifty-five") - ); - assert_eq!( - negative_spell(-1234), - String::from("minus one thousand two hundred thirty-four") - ); - assert_eq!( - negative_spell(-10123), - String::from("minus ten thousand one hundred twenty-three") - ); - } - #[test] - fn test_long_numbers() { - assert_eq!( - negative_spell(-910112), - String::from("minus nine hundred ten thousand one hundred twelve") - ); - assert_eq!( - negative_spell(-651123), - String::from("minus six hundred fifty-one thousand one hundred twenty-three") - ); - - assert_eq!( - negative_spell(-810000), - String::from("minus eight hundred ten thousand") - ); - assert_eq!(negative_spell(-1000000), String::from("minus one million")); - } - #[test] - fn test_invalid_numbers() { - assert_eq!(negative_spell(1), String::from("error: positive number")); - assert_eq!( - negative_spell(2390904), - String::from("error: positive number") - ); - } -} diff --git a/tests/office_worker_test/Cargo.toml b/tests/office_worker_test/Cargo.toml index 11d43d1c..27aa5b64 100644 --- a/tests/office_worker_test/Cargo.toml +++ b/tests/office_worker_test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "office_worker_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/office_worker_test/src/lib.rs b/tests/office_worker_test/src/lib.rs new file mode 100644 index 00000000..ca31078a --- /dev/null +++ b/tests/office_worker_test/src/lib.rs @@ -0,0 +1,36 @@ +use office_worker::*; + +#[test] +fn test_office_worker() { + assert_eq!( + OfficeWorker::from("Louise,25,admin"), + OfficeWorker { + name: "Louise".to_owned(), + age: 25, + role: WorkerRole::Admin, + } + ); + assert_eq!( + OfficeWorker::from("Rob,11,guest"), + OfficeWorker { + name: "Rob".to_owned(), + age: 11, + role: WorkerRole::Guest, + } + ); + assert_eq!( + OfficeWorker::from("Maria Agata,44,user"), + OfficeWorker { + name: "Maria Agata".to_owned(), + age: 44, + role: WorkerRole::User, + } + ); +} + +#[test] +fn test_worker_role() { + assert_eq!(WorkerRole::from("guest"), WorkerRole::Guest); + assert_eq!(WorkerRole::from("admin"), WorkerRole::Admin); + assert_eq!(WorkerRole::from("user"), WorkerRole::User); +} diff --git a/tests/office_worker_test/src/main.rs b/tests/office_worker_test/src/main.rs deleted file mode 100644 index 836c96fc..00000000 --- a/tests/office_worker_test/src/main.rs +++ /dev/null @@ -1,49 +0,0 @@ -use office_worker::*; - -fn main() { - println!("New worker: {:?}", OfficeWorker::from("Manuel,23,admin")); - println!( - "New worker: {:?}", - OfficeWorker::from("Jean Jacques,44,guest") - ); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_office_worker() { - assert_eq!( - OfficeWorker::from("Louise,25,admin"), - OfficeWorker { - name: "Louise".to_string(), - age: 25, - role: WorkerRole::Admin, - } - ); - assert_eq!( - OfficeWorker::from("Rob,11,guest"), - OfficeWorker { - name: "Rob".to_string(), - age: 11, - role: WorkerRole::Guest, - } - ); - assert_eq!( - OfficeWorker::from("Maria Agata,44,user"), - OfficeWorker { - name: "Maria Agata".to_string(), - age: 44, - role: WorkerRole::User, - } - ); - } - - #[test] - fn test_worker_role() { - assert_eq!(WorkerRole::from("guest"), WorkerRole::Guest); - assert_eq!(WorkerRole::from("admin"), WorkerRole::Admin); - assert_eq!(WorkerRole::from("user"), WorkerRole::User); - } -} diff --git a/tests/partial_sums_test/Cargo.toml b/tests/partial_sums_test/Cargo.toml index 7e6485d4..fabd5a27 100644 --- a/tests/partial_sums_test/Cargo.toml +++ b/tests/partial_sums_test/Cargo.toml @@ -2,9 +2,9 @@ name = "partial_sums_test" version = "0.1.0" authors = ["OGordoo "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -partial_sums = {path = "../../solutions/partial_sums"} \ No newline at end of file +partial_sums = { path = "../../solutions/partial_sums" } diff --git a/tests/partial_sums_test/src/lib.rs b/tests/partial_sums_test/src/lib.rs new file mode 100644 index 00000000..a05f778d --- /dev/null +++ b/tests/partial_sums_test/src/lib.rs @@ -0,0 +1,28 @@ +use partial_sums::*; + +#[test] +fn simple_tests() { + assert_eq!(vec![15, 10, 6, 3, 1, 0], parts_sums(&[1, 2, 3, 4, 5])); + assert_eq!(vec![49, 26, 23, 5, 0], parts_sums(&[5, 18, 3, 23])); + assert_eq!(vec![0, 0, 0, 0, 0, 0], parts_sums(&[0, 0, 0, 0, 0])) +} + +#[test] +fn complex_tests() { + assert_eq!( + vec![72393, 33352, 33350, 32787, 22597, 22515, 0], + parts_sums(&[22515, 82, 10190, 563, 2, 39041]) + ); + assert_eq!( + vec![ + 2337, 2333, 2240, 2208, 2113, 2016, 2001, 1987, 1938, 1936, 1929, 1911, 1811, 1780, + 1729, 1728, 1653, 1593, 1521, 1459, 1369, 1273, 1197, 1155, 1107, 1084, 1017, 995, 927, + 918, 878, 814, 722, 693, 609, 581, 568, 477, 383, 344, 339, 262, 193, 113, 93, 81, 0 + ], + parts_sums(&[ + 81, 12, 20, 80, 69, 77, 5, 39, 94, 91, 13, 28, 84, 29, 92, 64, 40, 9, 68, 22, 67, 23, + 48, 42, 76, 96, 90, 62, 72, 60, 75, 1, 51, 31, 100, 18, 7, 2, 49, 14, 15, 97, 95, 32, + 93, 4 + ]) + ) +} diff --git a/tests/partial_sums_test/src/main.rs b/tests/partial_sums_test/src/main.rs deleted file mode 100644 index 00ca1bc6..00000000 --- a/tests/partial_sums_test/src/main.rs +++ /dev/null @@ -1,41 +0,0 @@ -use partial_sums::parts_sums; - -fn main() { - println!( - "Partial sums of [5, 18, 3, 23] is : {:?}", - parts_sums(&[5, 18, 3, 23]) - ); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn simple_tests() { - assert_eq!(vec![15, 10, 6, 3, 1, 0], parts_sums(&[1, 2, 3, 4, 5])); - assert_eq!(vec![49, 26, 23, 5, 0], parts_sums(&[5, 18, 3, 23])); - assert_eq!(vec![0, 0, 0, 0, 0, 0], parts_sums(&[0, 0, 0, 0, 0])) - } - - #[test] - fn complex_tests() { - assert_eq!( - vec![72393, 33352, 33350, 32787, 22597, 22515, 0], - parts_sums(&[22515, 82, 10190, 563, 2, 39041]) - ); - assert_eq!( - vec![ - 2337, 2333, 2240, 2208, 2113, 2016, 2001, 1987, 1938, 1936, 1929, 1911, 1811, 1780, - 1729, 1728, 1653, 1593, 1521, 1459, 1369, 1273, 1197, 1155, 1107, 1084, 1017, 995, - 927, 918, 878, 814, 722, 693, 609, 581, 568, 477, 383, 344, 339, 262, 193, 113, 93, - 81, 0 - ], - parts_sums(&[ - 81, 12, 20, 80, 69, 77, 5, 39, 94, 91, 13, 28, 84, 29, 92, 64, 40, 9, 68, 22, 67, - 23, 48, 42, 76, 96, 90, 62, 72, 60, 75, 1, 51, 31, 100, 18, 7, 2, 49, 14, 15, 97, - 95, 32, 93, 4 - ]) - ) - } -} diff --git a/tests/profanity_filter_test/Cargo.toml b/tests/profanity_filter_test/Cargo.toml index 822edebd..0b1f3e2e 100644 --- a/tests/profanity_filter_test/Cargo.toml +++ b/tests/profanity_filter_test/Cargo.toml @@ -2,7 +2,7 @@ name = "profanity_filter_test" version = "0.1.0" authors = ["lee "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/profanity_filter_test/src/lib.rs b/tests/profanity_filter_test/src/lib.rs index cd71813e..45e7af23 100644 --- a/tests/profanity_filter_test/src/lib.rs +++ b/tests/profanity_filter_test/src/lib.rs @@ -1,8 +1,10 @@ +use profanity_filter::*; + #[test] fn test_error_ms() { ["", "stupid", "you are stupid"] .into_iter() - .for_each(|m| assert_eq!(Err("ERROR: illegal"), profanity_filter::check_ms(m))); + .for_each(|m| assert_eq!(Err("ERROR: illegal"), check_ms(m))); } #[test] @@ -14,5 +16,5 @@ fn test_ok_ms() { "wait the what...", ] .into_iter() - .for_each(|m| assert_eq!(Ok(m), profanity_filter::check_ms(m))); + .for_each(|m| assert_eq!(Ok(m), check_ms(m))); } diff --git a/tests/reverse_it_test/Cargo.toml b/tests/reverse_it_test/Cargo.toml index c1db6646..70270011 100644 --- a/tests/reverse_it_test/Cargo.toml +++ b/tests/reverse_it_test/Cargo.toml @@ -2,7 +2,7 @@ name = "reverse_it_test" version = "0.1.0" authors = ["lee "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/reverse_it_test/src/lib.rs b/tests/reverse_it_test/src/lib.rs new file mode 100644 index 00000000..a9902f5d --- /dev/null +++ b/tests/reverse_it_test/src/lib.rs @@ -0,0 +1,10 @@ +use reverse_it::*; + +#[test] +fn reverse_it_test() { + assert_eq!("321123", reverse_it(123)); + assert_eq!("987654321123456789", reverse_it(123456789)); + assert_eq!("00", reverse_it(0)); + assert_eq!("-321123", reverse_it(-123)); + assert_eq!("11", reverse_it(1)); +} diff --git a/tests/reverse_it_test/src/main.rs b/tests/reverse_it_test/src/main.rs deleted file mode 100644 index bba22d89..00000000 --- a/tests/reverse_it_test/src/main.rs +++ /dev/null @@ -1,17 +0,0 @@ -use reverse_it::*; - -fn main() { - println!("{}", reverse_it(123456789)); - println!("{}", reverse_it(-123)); -} - -#[test] -fn reverse_it_test() { - assert_eq!("321123", &reverse_it(123)); - assert_eq!("987654321123456789", &reverse_it(123456789)); - assert_eq!("00", &reverse_it(0)); - assert_eq!("-321123", &reverse_it(-123)); - assert_eq!("11", &reverse_it(1)); - assert_eq!("-84638474122147483648", &reverse_it(i32::MIN)); - assert_eq!("74638474122147483647", &reverse_it(i32::MAX)); -} diff --git a/tests/rot21_test/Cargo.toml b/tests/rot21_test/Cargo.toml index 16672690..877ef720 100644 --- a/tests/rot21_test/Cargo.toml +++ b/tests/rot21_test/Cargo.toml @@ -2,7 +2,7 @@ name = "rot21_test" version = "0.1.0" authors = ["MSilva95 "] -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/rot21_test/src/lib.rs b/tests/rot21_test/src/lib.rs new file mode 100644 index 00000000..8325a949 --- /dev/null +++ b/tests/rot21_test/src/lib.rs @@ -0,0 +1,17 @@ +use rot21::*; + +#[test] +fn test_rot21_multiple_cases() { + assert_eq!("ocdn dn v ozno", rot21("this is a test")); + assert_eq!("mviyjh ndhkgz rjmyn", rot21("random simple words")); + assert_eq!( + "ojj hpxc nkvxzn rjmfn", + rot21("too much spaces works") + ); + assert_eq!("mv😋w", rot21("ra😋b")); + assert_eq!("12Â nãj ábpv", rot21("12Â são água")); + + assert_eq!("VWXY", rot21("ABCD")); + assert_eq!("GJJFDIB BJJY", rot21("LOOKING GOOD")); + assert_eq!("WTZ", rot21("BYE")); +} diff --git a/tests/rot21_test/src/main.rs b/tests/rot21_test/src/main.rs deleted file mode 100644 index f38ef200..00000000 --- a/tests/rot21_test/src/main.rs +++ /dev/null @@ -1,76 +0,0 @@ -/* -## rot21 - -### Instructions - -Your purpose in this exercise is to create a `rot21` function that works like the ROT13 cipher. - -Your function will receive a string and it will rotate each letter of that string 21 times to the right. - -Your function should only change letters. If the string includes punctuation, symbols and numbers -they will remain the same. - -### Expected functions - -```rust -pub fn rot21(input: &str) -> String {} -``` - -### Usage - -Here is a program to test your function. - -```rust -use rot21::rot21; - -fn main() { - println!("The letter \"a\" becomes: {}", rot21("a")); - println!("The letter \"m\" becomes: {}", rot21("m")); - println!("The word \"MISS\" becomes: {}", rot21("MISS")); - println!("Your cypher wil be: {}", rot21("Testing numbers 1 2 3")); - println!("Your cypher wil be: {}", rot21("rot21 works!")); -} - -``` - -And its output - -```console -The letter "a" becomes: v -The letter "m" becomes: h -The word "MISS" becomes: HDNN -Your cypher wil be: Oznodib iphwzmn 1 2 3 -Your cypher wil be: mjo21 rjmfn! -student@ubuntu:~/[[ROOT]]/test$ -``` -*/ -use rot21::*; - -fn main() { - println!("The letter \"a\" becomes: {}", rot21("a")); - println!("The letter \"m\" becomes: {}", rot21("m")); - println!("The word \"MISS\" becomes: {}", rot21("MISS")); - println!("Your cypher wil be: {}", rot21("Testing numbers 1 2 3")); - println!("Your cypher wil be: {}", rot21("rot21 works!")); -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_rot21_multiple_cases() { - assert_eq!("ocdn dn v ozno", rot21("this is a test")); - assert_eq!("mviyjh ndhkgz rjmyn", rot21("random simple words")); - assert_eq!( - "ojj hpxc nkvxzn rjmfn", - rot21("too much spaces works") - ); - assert_eq!("mv😋w", rot21("ra😋b")); - assert_eq!("12Â nãj ábpv", rot21("12Â são água")); - - assert_eq!("VWXY", rot21("ABCD")); - assert_eq!("GJJFDIB BJJY", rot21("LOOKING GOOD")); - assert_eq!("WTZ", rot21("BYE")); - } -} diff --git a/tests/smallest_test/Cargo.toml b/tests/smallest_test/Cargo.toml index 6a7f7459..af294eaa 100644 --- a/tests/smallest_test/Cargo.toml +++ b/tests/smallest_test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "smallest_test" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/tests/smallest_test/src/lib.rs b/tests/smallest_test/src/lib.rs new file mode 100644 index 00000000..992d9b6e --- /dev/null +++ b/tests/smallest_test/src/lib.rs @@ -0,0 +1,48 @@ +use smallest::*; +use std::collections::HashMap; + +#[test] +fn test_positive() { + let f = HashMap::from([ + ("Cat", 12), + ("Dog", 333), + ("Elephant", 334), + ("Gorilla", 14), + ("Dolphin", 2), + ]); + + assert_eq!(2, smallest(f)); +} + +#[test] +fn test_negative() { + let f = HashMap::from([ + ("Daniel", 41758712), + ("Ashley", 54551444), + ("Katie", 575556334), + ("Roberti", 574148), + ("Robert", -4), + ]); + + assert_eq!(-4, smallest(f)); +} + +#[test] +fn test_zero() { + let f = HashMap::from([ + ("Mars", 1223), + ("Jupiter", 33343), + ("Saturn", 12443334), + ("Neptune", 14), + ("Venus", 0), + ]); + + assert_eq!(0, smallest(f)); +} + +#[test] +fn empty() { + let f = HashMap::new(); + + assert_eq!(i32::MAX, smallest(f)); +} diff --git a/tests/smallest_test/src/main.rs b/tests/smallest_test/src/main.rs deleted file mode 100644 index 08893510..00000000 --- a/tests/smallest_test/src/main.rs +++ /dev/null @@ -1,59 +0,0 @@ -use smallest::smallest; -use std::collections::HashMap; -fn main() { - let mut hash = HashMap::new(); - hash.insert("Cat", 122); - hash.insert("Dog", 333); - hash.insert("Elephant", 334); - hash.insert("Gorilla", 14); - - println!( - "The smallest of the elements in the HashMap is {}", - smallest(hash) - ); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_positive() { - let mut f = HashMap::new(); - f.insert("Cat", 12); - f.insert("Dog", 333); - f.insert("Elephant", 334); - f.insert("Gorilla", 14); - f.insert("Dolphin", 2); - - assert_eq!(2, smallest(f)); - } - #[test] - fn test_negative() { - let mut f = HashMap::new(); - f.insert("Daniel", 41758712); - f.insert("Ashley", 54551444); - f.insert("Katie", 575556334); - f.insert("Roberti", 574148); - f.insert("Robert", -4); - - assert_eq!(-4, smallest(f)); - } - #[test] - fn test_zero() { - let mut f = HashMap::new(); - f.insert("Mars", 1223); - f.insert("Jupiter", 33343); - f.insert("Saturn", 12443334); - f.insert("Neptune", 14); - f.insert("Venus", 0); - - assert_eq!(0, smallest(f)); - } - #[test] - fn empty() { - let f = HashMap::new(); - - assert_eq!(i32::MAX, smallest(f)); - } -}