Skip to content

Commit

Permalink
20231010
Browse files Browse the repository at this point in the history
  • Loading branch information
xxkeming committed Oct 10, 2023
1 parent d42c582 commit b9df5b1
Show file tree
Hide file tree
Showing 24 changed files with 188 additions and 70 deletions.
4 changes: 2 additions & 2 deletions exercises/clippy/clippy1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


use std::f32;

fn main() {
let pi = 3.14f32;
let pi = f32::consts::PI;
let radius = 5.00f32;

let area = pi * f32::powi(radius, 2);
Expand Down
7 changes: 5 additions & 2 deletions exercises/clippy/clippy2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
// Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


fn main() {
let mut res = 42;
let option = Some(12);
for x in option {
/*for x in option {
res += x;
}*/
if let Some(x) = option {
res += x;
}
println!("{}", res);
Expand Down
13 changes: 7 additions & 6 deletions exercises/clippy/clippy3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,29 @@
// Here's a couple more easy Clippy fixes, so you can see its utility.
// No hints.

// I AM NOT DONE


#[allow(unused_variables, unused_assignments)]
fn main() {
let my_option: Option<()> = None;
if my_option.is_none() {
my_option.unwrap();
// my_option.unwrap();
}

let my_arr = &[
-1, -2, -3
-1, -2, -3,
-4, -5, -6
];
println!("My array! Here it is: {:?}", my_arr);

let my_empty_vec = vec![1, 2, 3, 4, 5].resize(0, 5);
let my_empty_vec = vec![1, 2, 3, 4, 5];
println!("This Vec is empty, see? {:?}", my_empty_vec);

let mut value_a = 45;
let mut value_b = 66;
// Let's swap these two!
value_a = value_b;
value_b = value_a;
//value_a = value_b;
//value_b = value_a;
std::mem::swap(&mut value_a, &mut value_b);
println!("value a: {}; value b: {}", value_a, value_b);
}
10 changes: 5 additions & 5 deletions exercises/conversions/as_ref_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,25 @@
// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


// Obtain the number of bytes (not characters) in the given argument.
// TODO: Add the AsRef trait appropriately as a trait bound.
fn byte_counter<T>(arg: T) -> usize {
fn byte_counter<T: AsRef<str>>(arg: T) -> usize {
arg.as_ref().as_bytes().len()
}

// Obtain the number of characters (not bytes) in the given argument.
// TODO: Add the AsRef trait appropriately as a trait bound.
fn char_counter<T>(arg: T) -> usize {
fn char_counter<T: AsRef<str>>(arg: T) -> usize {
arg.as_ref().chars().count()
}

// Squares a number using as_mut().
// TODO: Add the appropriate trait bound.
fn num_sq<T>(arg: &mut T) {
fn num_sq<T: AsMut<u32>>(arg: &mut T) {
// TODO: Implement the function body.
???
*arg.as_mut() = *arg.as_mut() * *arg.as_mut();
}

#[cfg(test)]
Expand Down
18 changes: 17 additions & 1 deletion exercises/conversions/from_into.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,26 @@ impl Default for Person {
// If while parsing the age, something goes wrong, then return the default of
// Person Otherwise, then return an instantiated Person object with the results

// I AM NOT DONE


impl From<&str> for Person {
fn from(s: &str) -> Person {

let persion: Vec<&str> = s.split(',').collect();
if persion.len() < 2 || persion[0].len() == 0 {
return Person::default();
}

let name = persion[0].to_string();
let age = match persion[1].parse::<usize>() {
Ok(r) => r,
_ => return Person::default()
};

Person {
name,
age
}
}
}

Expand Down
22 changes: 21 additions & 1 deletion exercises/conversions/from_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ enum ParsePersonError {
ParseInt(ParseIntError),
}

// I AM NOT DONE


// Steps:
// 1. If the length of the provided string is 0, an error should be returned
Expand All @@ -52,6 +52,26 @@ enum ParsePersonError {
impl FromStr for Person {
type Err = ParsePersonError;
fn from_str(s: &str) -> Result<Person, Self::Err> {
if s.len() == 0 {
return Err(ParsePersonError::Empty);
}

let persion: Vec<&str> = s.split(',').collect();
if persion.len() != 2 {
return Err(ParsePersonError::BadLen);
}

if persion[0].len() == 0 {
return Err(ParsePersonError::NoName);
}

let name = persion[0].to_string();
let age = persion[1].parse::<usize>().map_err(ParsePersonError::ParseInt)?;

Ok(Person {
name,
age
})
}
}

Expand Down
35 changes: 34 additions & 1 deletion exercises/conversions/try_from_into.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ enum IntoColorError {
IntConversion,
}

// I AM NOT DONE


// Your task is to complete this implementation and return an Ok result of inner
// type Color. You need to create an implementation for a tuple of three
Expand All @@ -41,20 +41,53 @@ enum IntoColorError {
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
if tuple.0 > 255 || tuple.0 < 0 {
return Err(IntoColorError::IntConversion);
}
if tuple.1 > 255 || tuple.1 < 0 {
return Err(IntoColorError::IntConversion);
}
if tuple.2 > 255 || tuple.2 < 0 {
return Err(IntoColorError::IntConversion);
}
Ok(Self { red: tuple.0 as u8, green: tuple.1 as u8, blue: tuple.2 as u8 })
}
}

// Array implementation
impl TryFrom<[i16; 3]> for Color {
type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
if arr[0] > 255 || arr[0] < 0 {
return Err(IntoColorError::IntConversion);
}
if arr[1] > 255 || arr[1] < 0 {
return Err(IntoColorError::IntConversion);
}
if arr[2] > 255 || arr[2] < 0 {
return Err(IntoColorError::IntConversion);
}
Ok(Self { red: arr[0] as u8, green: arr[1] as u8, blue: arr[2] as u8 })
}
}

// Slice implementation
impl TryFrom<&[i16]> for Color {
type Error = IntoColorError;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
if slice.len() != 3 {
return Err(IntoColorError::BadLen);
}
if slice[0] > 255 || slice[0] < 0 {
return Err(IntoColorError::IntConversion);
}
if slice[1] > 255 || slice[1] < 0 {
return Err(IntoColorError::IntConversion);
}
if slice[2] > 255 || slice[2] < 0 {
return Err(IntoColorError::IntConversion);
}
Ok(Self { red: slice[0] as u8, green: slice[1] as u8, blue: slice[2] as u8 })
}
}

Expand Down
4 changes: 2 additions & 2 deletions exercises/conversions/using_as.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


fn average(values: &[f64]) -> f64 {
let total = values.iter().sum::<f64>();
total / values.len()
total / values.len() as f64
}

fn main() {
Expand Down
10 changes: 5 additions & 5 deletions exercises/iterators/iterators1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@
// Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


#[test]
fn main() {
let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"];

let mut my_iterable_fav_fruits = ???; // TODO: Step 1
let mut my_iterable_fav_fruits = my_fav_fruits.iter(); // TODO: Step 1

assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana"));
assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 2
assert_eq!(my_iterable_fav_fruits.next(), Some(&"custard apple")); // TODO: Step 2
assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado"));
assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3
assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach")); // TODO: Step 3
assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry"));
assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4
assert_eq!(my_iterable_fav_fruits.next(), None); // TODO: Step 4
}
22 changes: 18 additions & 4 deletions exercises/iterators/iterators2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


// Step 1.
// Complete the `capitalize_first` function.
Expand All @@ -15,7 +15,13 @@ pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars();
match c.next() {
None => String::new(),
Some(first) => ???,
Some(first) => {
let mut s = first.to_uppercase().to_string();
while let Some(v) = c.next() {
s.push(v);
}
s
}
}
}

Expand All @@ -24,15 +30,23 @@ pub fn capitalize_first(input: &str) -> String {
// Return a vector of strings.
// ["hello", "world"] -> ["Hello", "World"]
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
vec![]
let mut out: Vec<String> = vec![];
for v in words {
out.push(capitalize_first(v));
}
out
}

// Step 3.
// Apply the `capitalize_first` function again to a slice of string slices.
// Return a single string.
// ["hello", " ", "world"] -> "Hello World"
pub fn capitalize_words_string(words: &[&str]) -> String {
String::new()
let mut out = String::new();
for v in words {
out.push_str(&capitalize_first(v));
}
out
}

#[cfg(test)]
Expand Down
22 changes: 16 additions & 6 deletions exercises/iterators/iterators3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


#[derive(Debug, PartialEq, Eq)]
pub enum DivisionError {
Expand All @@ -26,23 +26,33 @@ pub struct NotDivisibleError {
// Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error.
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
todo!();
if b == 0 {
return Err(DivisionError::DivideByZero);
}

if a % b == 0 {
Ok(a/b)
} else {
Err(DivisionError::NotDivisible(NotDivisibleError { dividend: a, divisor: b }))
}
}

// Complete the function and return a value of the correct type so the test
// passes.
// Desired output: Ok([1, 11, 1426, 3])
fn result_with_list() -> () {
fn result_with_list() -> Result<Vec<i32>, DivisionError> {
let numbers = vec![27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));
let division_results = numbers.into_iter().map(|n| divide(n, 27)).flatten().collect::<Vec<_>>();
Ok(division_results)
}

// Complete the function and return a value of the correct type so the test
// passes.
// Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)]
fn list_of_results() -> () {
fn list_of_results() -> Vec<Result<i32, DivisionError>> {
let numbers = vec![27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));
let division_results = numbers.into_iter().map(|n| divide(n, 27)).collect::<Vec<_>>();
division_results
}

#[cfg(test)]
Expand Down
7 changes: 6 additions & 1 deletion exercises/iterators/iterators4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


pub fn factorial(num: u64) -> u64 {
// Complete this function to return the factorial of num
Expand All @@ -15,6 +15,11 @@ pub fn factorial(num: u64) -> u64 {
// For an extra challenge, don't use:
// - recursion
// Execute `rustlings hint iterators4` for hints.
match num {
0 => 1,
1 => 1,
_ => factorial(num - 1) * num
}
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit b9df5b1

Please sign in to comment.