This commit is contained in:
Nisarga P 2024-02-02 00:08:59 -08:00
parent c2de94d277
commit ef0e19b5c1
17 changed files with 107 additions and 63 deletions

5
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,5 @@
{
"recommendations": [
"rust-lang.rust-analyzer"
]
}

View File

@ -8,13 +8,10 @@
//
// 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);

View File

@ -3,12 +3,10 @@
// 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 {
while let Some(x) = option {
res += x;
}
println!("{}", res);

View File

@ -3,28 +3,21 @@
// 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();
}
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);
println!("This Vec is empty, see? {:?}", my_empty_vec);
println!("This Vec is empty, see? {:?}", vec![1,2,3,4,5].resize(0, 0));
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);
println!("value a: {}; value b: {}", value_a, value_b);
}

View File

@ -7,25 +7,25 @@
// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
use std::ops::Mul;
// 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) {
// TODO: Implement the function body.
???
fn num_sq<T>(arg: &mut T) where T: AsMut<u32> {
// TODO: Implementrhs the function body.
let x = arg.as_mut();
*x = x.mul(*x);
}
#[cfg(test)]

View File

@ -40,10 +40,25 @@ 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 split_s = s.split(",");
let split_vec: Vec<&str> = split_s.collect();
if split_vec.len() < 2 {
return Person::default();
};
let name = split_vec[0].to_string();
if name.len() == 0 {
return Person::default();
};
let age: Result<usize, _> = split_vec[1].parse();
match age {
Ok(a) => Person { name, age: a },
Err(a) => Person::default()
}
}
}

View File

@ -31,8 +31,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
// 2. Split the given string on the commas present in it
@ -52,6 +50,22 @@ 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 split_vec: Vec<&str> = s.split(",").collect();
if split_vec.len() != 2 {
return Err(ParsePersonError::BadLen);
};
let name = split_vec[0];
if name.len() == 0 {
return Err(ParsePersonError::NoName);
}
let age: Result<usize, _> = split_vec[1].parse();
match age {
Ok(a) => Ok(Person{name: name.to_string(), age: a}),
Err(x) => Err(ParsePersonError::ParseInt(x))
}
}
}

View File

@ -27,8 +27,6 @@ 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
// integers, an array of three integers, and a slice of integers.
@ -36,11 +34,22 @@ enum IntoColorError {
// Note that the implementation for tuple and array will be checked at compile
// time, but the slice implementation needs to check the slice length! Also note
// that correct RGB color values must be integers in the 0..=255 range.
fn valid_num(num: i16) -> bool {
num >= 0 && num <= 255
}
// Tuple implementation
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
if !(valid_num(tuple.0) && valid_num(tuple.1) && valid_num(tuple.2)) {
return Err(IntoColorError::IntConversion);
}
return Ok(Color{
red: tuple.0 as u8,
green: tuple.1 as u8,
blue: tuple.2 as u8
});
}
}
@ -48,6 +57,17 @@ 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> {
if arr.len() != 3 {
return Err(IntoColorError::BadLen);
}
if !(valid_num(arr[0]) && valid_num(arr[1]) && valid_num(arr[2])) {
return Err(IntoColorError::IntConversion);
}
return Ok(Color{
red: arr[0] as u8,
green: arr[1] as u8,
blue: arr[2] as u8
});
}
}
@ -55,6 +75,17 @@ impl TryFrom<[i16; 3]> for Color {
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 !(valid_num(slice[0]) && valid_num(slice[1]) && valid_num(slice[2])) {
return Err(IntoColorError::IntConversion);
}
return Ok(Color{
red: slice[0] as u8,
green: slice[1] as u8,
blue: slice[2] as u8
});
}
}

View File

@ -10,11 +10,9 @@
// 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() {

View File

@ -3,8 +3,6 @@
// Execute `rustlings hint macros1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
macro_rules! my_macro {
() => {
println!("Check out my macro!");
@ -12,5 +10,5 @@ macro_rules! my_macro {
}
fn main() {
my_macro();
my_macro!();
}

View File

@ -3,14 +3,12 @@
// 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!();
}

View File

@ -5,8 +5,7 @@
// 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 {
() => {

View File

@ -3,13 +3,11 @@
// 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);
}

View File

@ -12,8 +12,6 @@
//
// Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
use std::borrow::Cow;
fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> {

View File

@ -8,8 +8,6 @@
// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
use std::thread;
use std::time::{Duration, Instant};
@ -27,6 +25,9 @@ fn main() {
let mut results: Vec<u128> = vec![];
for handle in handles {
// TODO: a struct is returned from thread::spawn, can you use it?
if let Ok(x) = handle.join() {
results.push(x);
}
}
if results.len() != 10 {

View File

@ -7,9 +7,8 @@
// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use std::time::Duration;
@ -18,22 +17,23 @@ 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 status_shared: Arc<Mutex<JobStatus>> = 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;
let mut job_status = status_shared.lock().unwrap();
job_status.jobs_completed += 1;
});
handles.push(handle);
}
for handle in handles {
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);
}
}

View File

@ -3,8 +3,6 @@
// 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;
use std::thread;
@ -31,10 +29,13 @@ fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {
let qc1 = Arc::clone(&qc);
let qc2 = Arc::clone(&qc);
let tx1 = tx.clone();
let tx2 = tx.clone();
thread::spawn(move || {
for val in &qc1.first_half {
for val in &qc1.first_half.clone() {
println!("sending {:?}", val);
tx.send(*val).unwrap();
tx1.send(*val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
@ -42,7 +43,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));
}
});