Current Progress: 92/94

This commit is contained in:
2023-06-15 17:30:11 -05:00
parent 1230b6cdb2
commit 05f28181d0
21 changed files with 80 additions and 699 deletions
+1 -2
View File
@@ -6,12 +6,11 @@
// check clippy's suggestions from the output to solve the exercise.
// 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 = std::f32::consts::PI;
let radius = 5.00f32;
let area = pi * f32::powi(radius, 2);
+1 -2
View File
@@ -1,12 +1,11 @@
// clippy2.rs
// 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 {
if let Some(x) = option {
res += x;
}
println!("{}", res);
+7 -6
View File
@@ -1,28 +1,29 @@
// clippy3.rs
// Here's a couple more easy Clippy fixes, so you can see its utility.
// I AM NOT DONE
#[allow(unused_variables, unused_assignments)]
fn main() {
let my_option: Option<()> = None;
if my_option.is_none() {
my_option.unwrap();
println!("My_option contains: {:#?}", my_option);
}
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 mut my_empty_vec = vec![1, 2, 3, 4, 5];
my_empty_vec.clear();
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;
std::mem::swap(&mut value_a, &mut value_b);
// value_a = value_b;
// value_b = value_a;
println!("value a: {}; value b: {}", value_a, value_b);
}
+9 -1
View File
@@ -35,10 +35,18 @@ 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 {
if s.len() == 0 { return Person::default(); }
let v = s.split(",").collect::<Vec<&str>>();
if v.len() != 2 { return Person::default(); }
if v[0].is_empty() { return Person::default(); }
if v[1].parse::<usize>().is_err() { return Person::default(); }
Person{
name: v[0].to_string(),
age: v[1].parse::<usize>().unwrap(),
}
}
}
+9 -1
View File
@@ -28,7 +28,6 @@ enum ParsePersonError {
ParseInt(ParseIntError),
}
// I AM NOT DONE
// Steps:
// 1. If the length of the provided string is 0, an error should be returned
@@ -46,6 +45,15 @@ 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 v = s.split(",").collect::<Vec<&str>>();
if v.len() != 2 { return Err(ParsePersonError::BadLen); }
if v[0].is_empty() { return Err(ParsePersonError::NoName); }
if let Err(e) = v[1].parse::<usize>() { return Err(ParsePersonError::ParseInt(e)); }
Ok(Person{
name: v[0].to_string(),
age: v[1].parse::<usize>().unwrap(),
})
}
}
+11
View File
@@ -38,6 +38,11 @@ enum IntoColorError {
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
Ok(Color {
red: tuple.0 as u8,
green: tuple.1 as u8,
blue: tuple.2 as u8,
})
}
}
@@ -45,6 +50,11 @@ impl TryFrom<(i16, i16, i16)> for Color {
impl TryFrom<[i16; 3]> for Color {
type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
Ok(Color {
red: arr[0] as u8,
green: arr[1] as u8,
blue: arr[2] as u8,
})
}
}
@@ -52,6 +62,7 @@ impl TryFrom<[i16; 3]> for Color {
impl TryFrom<&[i16]> for Color {
type Error = IntoColorError;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
todo!();
}
}
+1 -2
View File
@@ -6,11 +6,10 @@
// and returns the proper type.
// 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() {
+1 -2
View File
@@ -1,7 +1,6 @@
// iterators4.rs
// 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
@@ -13,7 +12,7 @@ pub fn factorial(num: u64) -> u64 {
// For an extra challenge, don't use:
// - recursion
// Execute `rustlings hint iterators4` for hints.
vec![1..num].iter().rfold(1, |acc, x| acc + x)
(1..=num).rfold(1, |acc, x| acc * x)
}
#[cfg(test)]
+8 -3
View File
@@ -10,7 +10,6 @@
//
// Make the code compile and the tests pass.
// I AM NOT DONE
use std::collections::HashMap;
@@ -34,7 +33,10 @@ fn count_for(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 = { "variables1": Complete, "from_str": None, ... }
todo!();
map
.iter()
.filter(|x| *x.1 == value)
.count()
}
fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
@@ -53,7 +55,10 @@ fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Pr
// collection is a slice of hashmaps.
// collection = [{ "variables1": Complete, "from_str": None, ... },
// { "variables2": Complete, ... }, ... ]
todo!();
collection
.iter()
.map(|map| count_iterator(map, value))
.sum()
}
#[cfg(test)]
+1 -2
View File
@@ -1,7 +1,6 @@
// macros1.rs
// Execute `rustlings hint macros1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
macro_rules! my_macro {
() => {
@@ -10,5 +9,5 @@ macro_rules! my_macro {
}
fn main() {
my_macro();
my_macro!();
}
+5 -6
View File
@@ -1,14 +1,13 @@
// macros2.rs
// Execute `rustlings hint macros2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
fn main() {
my_macro!();
}
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
fn main() {
my_macro!();
}
+1 -1
View File
@@ -2,8 +2,8 @@
// Make me compile, without taking the macro out of the module!
// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[macro_use]
mod macros {
macro_rules! my_macro {
() => {
+1 -2
View File
@@ -1,13 +1,12 @@
// macros4.rs
// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[rustfmt::skip]
macro_rules! my_macro {
() => {
println!("Check out my macro!");
}
};
($val:expr) => {
println!("Look at this other macro: {}", $val);
}
+2 -3
View File
@@ -18,7 +18,6 @@
// 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.
// I AM NOT DONE
#![forbid(unused_imports)] // Do not change this, (or the next) line.
use std::sync::Arc;
@@ -26,11 +25,11 @@ use std::thread;
fn main() {
let numbers: Vec<_> = (0..100u32).collect();
let shared_numbers = // TODO
let shared_numbers = Arc::new(numbers);// TODO
let mut joinhandles = Vec::new();
for offset in 0..8 {
let child_numbers = // TODO
let child_numbers = shared_numbers.clone();// TODO
joinhandles.push(thread::spawn(move || {
let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum();
println!("Sum of offset {} is {}", offset, sum);
+3 -4
View File
@@ -16,11 +16,10 @@
//
// Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
#[derive(PartialEq, Debug)]
pub enum List {
Cons(i32, List),
Cons(i32, Box<List>),
Nil,
}
@@ -33,11 +32,11 @@ fn main() {
}
pub fn create_empty_list() -> List {
todo!()
List::Nil
}
pub fn create_non_empty_list() -> List {
todo!()
List::Cons(0, Box::new(List::Nil))
}
#[cfg(test)]
+6 -4
View File
@@ -8,7 +8,6 @@
// This exercise is meant to show you what to expect when passing data to Cow.
// Fix the unit tests by checking for Cow::Owned(_) and Cow::Borrowed(_) at the TODO markers.
// I AM NOT DONE
use std::borrow::Cow;
@@ -44,7 +43,8 @@ mod tests {
let slice = [0, 1, 2];
let mut input = Cow::from(&slice[..]);
match abs_all(&mut input) {
// TODO
Cow::Borrowed(_) => Ok(()),
_ => Err("Expected owned value"),
}
}
@@ -56,7 +56,8 @@ mod tests {
let slice = vec![0, 1, 2];
let mut input = Cow::from(slice);
match abs_all(&mut input) {
// TODO
Cow::Owned(_) => Ok(()),
_ => Err("Expected owned value"),
}
}
@@ -68,7 +69,8 @@ mod tests {
let slice = vec![-1, 0, 1];
let mut input = Cow::from(slice);
match abs_all(&mut input) {
// TODO
Cow::Owned(_) => Ok(()),
_ => Err("Expected owned value"),
}
}
}
+6 -4
View File
@@ -5,7 +5,6 @@
// 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;
@@ -55,17 +54,17 @@ fn main() {
jupiter.details();
// TODO
let saturn = Planet::Saturn(Rc::new(Sun {}));
let saturn = Planet::Saturn(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 7 references
saturn.details();
// TODO
let uranus = Planet::Uranus(Rc::new(Sun {}));
let uranus = Planet::Uranus(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 8 references
uranus.details();
// TODO
let neptune = Planet::Neptune(Rc::new(Sun {}));
let neptune = Planet::Neptune(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 9 references
neptune.details();
@@ -87,12 +86,15 @@ fn main() {
println!("reference count = {}", Rc::strong_count(&sun)); // 4 references
// TODO
drop(earth);
println!("reference count = {}", Rc::strong_count(&sun)); // 3 references
// TODO
drop(venus);
println!("reference count = {}", Rc::strong_count(&sun)); // 2 references
// TODO
drop(mercury);
println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference
assert_eq!(Rc::strong_count(&sun), 1);
+1 -1
View File
@@ -6,7 +6,6 @@
// The program should wait until all the spawned threads have finished and
// should collect their return values into a vector.
// I AM NOT DONE
use std::thread;
use std::time::{Duration, Instant};
@@ -25,6 +24,7 @@ fn main() {
let mut results: Vec<u128> = vec![];
for handle in handles {
// TODO: a struct is returned from thread::spawn, can you use it?
results.push(handle.join().unwrap());
}
if results.len() != 10 {
+4 -5
View File
@@ -3,9 +3,8 @@
// Building on the last exercise, we want all of the threads to complete their work but this time
// the spawned threads need to be in charge of updating a shared value: JobStatus.jobs_completed
// I AM NOT DONE
use std::sync::Arc;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
@@ -14,14 +13,14 @@ struct JobStatus {
}
fn main() {
let status = Arc::new(JobStatus { jobs_completed: 0 });
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let mut handles = vec![];
for _ in 0..10 {
let status_shared = Arc::clone(&status);
let handle = thread::spawn(move || {
thread::sleep(Duration::from_millis(250));
// TODO: You must take an action before you update a shared value
status_shared.jobs_completed += 1;
status_shared.lock().unwrap().jobs_completed += 1;
});
handles.push(handle);
}
@@ -29,6 +28,6 @@ fn main() {
handle.join().unwrap();
// TODO: Print the value of the JobStatus.jobs_completed. Did you notice anything
// interesting in the output? Do you have to 'join' on all the handles?
println!("jobs completed {}", ???);
println!("jobs completed {}", status.lock().unwrap().jobs_completed);
}
}
+2 -2
View File
@@ -1,7 +1,6 @@
// threads3.rs
// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
use std::sync::mpsc;
use std::sync::Arc;
@@ -28,6 +27,7 @@ fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {
let qc = Arc::new(q);
let qc1 = Arc::clone(&qc);
let qc2 = Arc::clone(&qc);
let tx2 = tx.clone();
thread::spawn(move || {
for val in &qc1.first_half {
@@ -40,7 +40,7 @@ fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {
thread::spawn(move || {
for val in &qc2.second_half {
println!("sending {:?}", val);
tx.send(*val).unwrap();
tx2.send(*val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});