1
0
Fork 0

Solutions 3

This commit is contained in:
Jake Walker 2022-10-14 18:14:56 +01:00
parent 367c75fd1f
commit 8da8070961
Signed by: jakew
GPG key ID: 2B83DC56C147243B
15 changed files with 42 additions and 63 deletions

View file

@ -7,9 +7,7 @@
// //
// Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() { if x.len() > y.len() {
x x
} else { } else {

View file

@ -6,8 +6,6 @@
// //
// Execute `rustlings hint lifetimes2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint lifetimes2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { if x.len() > y.len() {
x x
@ -18,9 +16,9 @@ fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
fn main() { fn main() {
let string1 = String::from("long string is long"); let string1 = String::from("long string is long");
let string2 = String::from("xyz");
let result; let result;
{ {
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str()); result = longest(string1.as_str(), string2.as_str());
} }
println!("The longest string is '{}'", result); println!("The longest string is '{}'", result);

View file

@ -4,11 +4,9 @@
// //
// Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE struct Book<'a> {
author: &'a str,
struct Book { title: &'a str,
author: &str,
title: &str,
} }
fn main() { fn main() {

View file

@ -18,19 +18,17 @@
// where the second TODO comment is. Try not to create any copies of the `numbers` Vec! // where the second TODO comment is. Try not to create any copies of the `numbers` Vec!
// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#![forbid(unused_imports)] // Do not change this, (or the next) line. #![forbid(unused_imports)] // Do not change this, (or the next) line.
use std::sync::Arc; use std::sync::Arc;
use std::thread; use std::thread;
fn main() { fn main() {
let numbers: Vec<_> = (0..100u32).collect(); let numbers: Vec<_> = (0..100u32).collect();
let shared_numbers = // TODO let shared_numbers = Arc::new(numbers); // TODO
let mut joinhandles = Vec::new(); let mut joinhandles = Vec::new();
for offset in 0..8 { for offset in 0..8 {
let child_numbers = // TODO let child_numbers = Arc::clone(&shared_numbers); // TODO
joinhandles.push(thread::spawn(move || { joinhandles.push(thread::spawn(move || {
let sum: u32 = child_numbers.iter().filter(|n| *n % 8 == offset).sum(); let sum: u32 = child_numbers.iter().filter(|n| *n % 8 == offset).sum();
println!("Sum of offset {} is {}", offset, sum); println!("Sum of offset {} is {}", offset, sum);

View file

@ -16,11 +16,9 @@
// //
// Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub enum List { pub enum List {
Cons(i32, List), Cons(i32, Box<List>),
Nil, Nil,
} }
@ -33,11 +31,11 @@ fn main() {
} }
pub fn create_empty_list() -> List { pub fn create_empty_list() -> List {
todo!() List::Nil
} }
pub fn create_non_empty_list() -> List { pub fn create_non_empty_list() -> List {
todo!() List::Cons(12, Box::new(List::Cons(52, Box::new(List::Nil))))
} }
#[cfg(test)] #[cfg(test)]

View file

@ -5,8 +5,6 @@
// It can enclose and provide immutable access to borrowed data, and clone the data lazily when mutation or ownership is required. // It can enclose and provide immutable access to borrowed data, and clone the data lazily when mutation or ownership is required.
// The type is designed to work with general borrowed data via the Borrow trait. // The type is designed to work with general borrowed data via the Borrow trait.
// I AM NOT DONE
use std::borrow::Cow; use std::borrow::Cow;
fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> { fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> {
@ -41,8 +39,7 @@ fn main() {
let slice = vec![-1, 0, 1]; let slice = vec![-1, 0, 1];
let mut input = Cow::from(slice); let mut input = Cow::from(slice);
match abs_all(&mut input) { match abs_all(&mut input) {
// TODO Cow::Owned(_) => println!("I own this slice!"),
Cow::Borrowed(_) => println!("I own this slice!"),
_ => panic!("expected borrowed value"), _ => panic!("expected borrowed value"),
} }
} }

View file

@ -8,17 +8,15 @@
// //
// Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main () { fn main () {
let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; 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(), 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(), 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(), Some(&"raspberry"));
assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4 assert_eq!(my_iterable_fav_fruits.next(), None); // TODO: Step 4
} }

View file

@ -3,8 +3,6 @@
// can offer. Follow the steps to complete the exercise. // can offer. Follow the steps to complete the exercise.
// Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
// Step 1. // Step 1.
// Complete the `capitalize_first` function. // Complete the `capitalize_first` function.
// "hello" -> "Hello" // "hello" -> "Hello"
@ -12,7 +10,7 @@ pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars(); let mut c = input.chars();
match c.next() { match c.next() {
None => String::new(), None => String::new(),
Some(first) => ???, Some(first) => first.to_uppercase().to_string() + c.as_str(),
} }
} }
@ -21,7 +19,7 @@ pub fn capitalize_first(input: &str) -> String {
// Return a vector of strings. // Return a vector of strings.
// ["hello", "world"] -> ["Hello", "World"] // ["hello", "world"] -> ["Hello", "World"]
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> { pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
vec![] words.iter().map(|word| capitalize_first(word)).collect()
} }
// Step 3. // Step 3.
@ -29,7 +27,7 @@ pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
// Return a single string. // Return a single string.
// ["hello", " ", "world"] -> "Hello World" // ["hello", " ", "world"] -> "Hello World"
pub fn capitalize_words_string(words: &[&str]) -> String { pub fn capitalize_words_string(words: &[&str]) -> String {
String::new() capitalize_words_vector(words).join("")
} }
#[cfg(test)] #[cfg(test)]

View file

@ -6,8 +6,6 @@
// list_of_results functions. // list_of_results functions.
// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub enum DivisionError { pub enum DivisionError {
NotDivisible(NotDivisibleError), NotDivisible(NotDivisibleError),
@ -23,21 +21,29 @@ pub struct NotDivisibleError {
// Calculate `a` divided by `b` if `a` is evenly divisible by `b`. // Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error. // Otherwise, return a suitable error.
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> { pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
todo!(); if (b == 0) {
Err(DivisionError::DivideByZero)
} else if (a % b != 0) {
Err(DivisionError::NotDivisible(NotDivisibleError { dividend: a, divisor: b }))
} else {
Ok(a / b)
}
} }
// Complete the function and return a value of the correct type so the test passes. // Complete the function and return a value of the correct type so the test passes.
// Desired output: Ok([1, 11, 1426, 3]) // 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 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));
division_results.collect()
} }
// Complete the function and return a value of the correct type so the test passes. // 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)] // 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 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));
division_results.collect()
} }
#[cfg(test)] #[cfg(test)]

View file

@ -1,8 +1,6 @@
// iterators4.rs // iterators4.rs
// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
pub fn factorial(num: u64) -> u64 { pub fn factorial(num: u64) -> u64 {
// Complete this function to return the factorial of num // Complete this function to return the factorial of num
// Do not use: // Do not use:
@ -13,6 +11,7 @@ pub fn factorial(num: u64) -> u64 {
// For an extra challenge, don't use: // For an extra challenge, don't use:
// - recursion // - recursion
// Execute `rustlings hint iterators4` for hints. // Execute `rustlings hint iterators4` for hints.
(1..=num).product()
} }
#[cfg(test)] #[cfg(test)]

View file

@ -10,8 +10,6 @@
// //
// Make the code compile and the tests pass. // Make the code compile and the tests pass.
// I AM NOT DONE
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Clone, Copy, PartialEq, Eq)] #[derive(Clone, Copy, PartialEq, Eq)]
@ -34,7 +32,7 @@ fn count_for(map: &HashMap<String, Progress>, value: Progress) -> usize {
fn count_iterator(map: &HashMap<String, Progress>, value: Progress) -> usize { fn count_iterator(map: &HashMap<String, Progress>, value: Progress) -> usize {
// map is a hashmap with String keys and Progress values. // map is a hashmap with String keys and Progress values.
// map = { "variables1": Complete, "from_str": None, ... } // map = { "variables1": Complete, "from_str": None, ... }
todo!(); map.values().filter(|p| **p == value).count()
} }
fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize { fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
@ -53,7 +51,7 @@ fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Pr
// collection is a slice of hashmaps. // collection is a slice of hashmaps.
// collection = [{ "variables1": Complete, "from_str": None, ... }, // collection = [{ "variables1": Complete, "from_str": None, ... },
// { "variables2": Complete, ... }, ... ] // { "variables2": Complete, ... }, ... ]
todo!(); collection.iter().map(|map| count_iterator(map, value)).sum()
} }
#[cfg(test)] #[cfg(test)]

View file

@ -5,7 +5,6 @@
// Make this code compile by using the proper Rc primitives to express that the sun has multiple owners. // Make this code compile by using the proper Rc primitives to express that the sun has multiple owners.
// I AM NOT DONE
use std::rc::Rc; use std::rc::Rc;
#[derive(Debug)] #[derive(Debug)]
@ -54,17 +53,17 @@ fn main() {
jupiter.details(); jupiter.details();
// TODO // TODO
let saturn = Planet::Saturn(Rc::new(Sun {})); let saturn = Planet::Saturn(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 7 references println!("reference count = {}", Rc::strong_count(&sun)); // 7 references
saturn.details(); saturn.details();
// TODO // TODO
let uranus = Planet::Uranus(Rc::new(Sun {})); let uranus = Planet::Uranus(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 8 references println!("reference count = {}", Rc::strong_count(&sun)); // 8 references
uranus.details(); uranus.details();
// TODO // TODO
let neptune = Planet::Neptune(Rc::new(Sun {})); let neptune = Planet::Neptune(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 9 references println!("reference count = {}", Rc::strong_count(&sun)); // 9 references
neptune.details(); neptune.details();
@ -85,13 +84,13 @@ fn main() {
drop(mars); drop(mars);
println!("reference count = {}", Rc::strong_count(&sun)); // 4 references println!("reference count = {}", Rc::strong_count(&sun)); // 4 references
// TODO drop(earth);
println!("reference count = {}", Rc::strong_count(&sun)); // 3 references println!("reference count = {}", Rc::strong_count(&sun)); // 3 references
// TODO drop(venus);
println!("reference count = {}", Rc::strong_count(&sun)); // 2 references println!("reference count = {}", Rc::strong_count(&sun)); // 2 references
// TODO drop(mercury);
println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference
assert_eq!(Rc::strong_count(&sun), 1); assert_eq!(Rc::strong_count(&sun), 1);

View file

@ -7,12 +7,10 @@
// pass! Make the test fail! // pass! Make the test fail!
// Execute `rustlings hint tests1` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint tests1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#[test] #[test]
fn you_can_assert() { fn you_can_assert() {
assert!(); assert!(true);
} }
} }

View file

@ -3,12 +3,10 @@
// pass! Make the test fail! // pass! Make the test fail!
// Execute `rustlings hint tests2` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint tests2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#[test] #[test]
fn you_can_assert_eq() { fn you_can_assert_eq() {
assert_eq!(); assert_eq!("Hi Mom!", "Hi Mom!");
} }
} }

View file

@ -4,8 +4,6 @@
// we expect to get when we call `is_even(5)`. // we expect to get when we call `is_even(5)`.
// Execute `rustlings hint tests3` or use the `hint` watch subcommand for a hint. // Execute `rustlings hint tests3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
pub fn is_even(num: i32) -> bool { pub fn is_even(num: i32) -> bool {
num % 2 == 0 num % 2 == 0
} }
@ -16,11 +14,11 @@ mod tests {
#[test] #[test]
fn is_true_when_even() { fn is_true_when_even() {
assert!(); assert!(is_even(4));
} }
#[test] #[test]
fn is_false_when_odd() { fn is_false_when_odd() {
assert!(); assert!(!is_even(5));
} }
} }