Skip to content

Commit 30ba57a

Browse files
committed
do exec
1 parent 1b636c5 commit 30ba57a

File tree

9 files changed

+56
-38
lines changed

9 files changed

+56
-38
lines changed

exercises/iterators/iterators3.rs

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@
99
// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a
1010
// hint.
1111

12-
// I AM NOT DONE
13-
1412
#[derive(Debug, PartialEq, Eq)]
1513
pub enum DivisionError {
1614
NotDivisible(NotDivisibleError),
@@ -26,23 +24,47 @@ pub struct NotDivisibleError {
2624
// Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
2725
// Otherwise, return a suitable error.
2826
pub fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
29-
todo!();
27+
if b == 0 {
28+
Err(DivisionError::DivideByZero)
29+
} else if a % b == 0 {
30+
Ok( a / b)
31+
} else {
32+
Err(DivisionError::NotDivisible(NotDivisibleError { dividend: a, divisor: b }))
33+
}
3034
}
3135

3236
// Complete the function and return a value of the correct type so the test
3337
// passes.
3438
// Desired output: Ok([1, 11, 1426, 3])
35-
fn result_with_list() -> () {
39+
fn result_with_list() -> Result<Vec<i32>, DivisionError> {
3640
let numbers = vec![27, 297, 38502, 81];
37-
let division_results = numbers.into_iter().map(|n| divide(n, 27));
41+
42+
numbers.into_iter().map(|n| divide(n, 27)).collect()
43+
// let division_results = numbers.into_iter().map(|n| divide(n, 27));
44+
45+
46+
// let mut result = vec![];
47+
48+
// for v in division_results {
49+
// match v {
50+
// Ok(number) => {
51+
// result.push(number);
52+
// }
53+
// Err(e) => {
54+
// return Err(e)
55+
// }
56+
// }
57+
// }
58+
59+
// Ok(result)
3860
}
3961

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

4870
#[cfg(test)]

exercises/iterators/iterators4.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a
44
// hint.
55

6-
// I AM NOT DONE
7-
86
pub fn factorial(num: u64) -> u64 {
97
// Complete this function to return the factorial of num
108
// Do not use:
@@ -15,6 +13,7 @@ pub fn factorial(num: u64) -> u64 {
1513
// For an extra challenge, don't use:
1614
// - recursion
1715
// Execute `rustlings hint iterators4` for hints.
16+
(1..num+1).into_iter().fold(1, |mut acc, v|{acc=v*acc; acc})
1817
}
1918

2019
#[cfg(test)]

exercises/iterators/iterators5.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
// Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a
1212
// hint.
1313

14-
// I AM NOT DONE
1514

1615
use std::collections::HashMap;
1716

@@ -35,7 +34,7 @@ fn count_for(map: &HashMap<String, Progress>, value: Progress) -> usize {
3534
fn count_iterator(map: &HashMap<String, Progress>, value: Progress) -> usize {
3635
// map is a hashmap with String keys and Progress values.
3736
// map = { "variables1": Complete, "from_str": None, ... }
38-
todo!();
37+
map.iter().filter(|v|*(v.1) == value).count()
3938
}
4039

4140
fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
@@ -54,7 +53,7 @@ fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Pr
5453
// collection is a slice of hashmaps.
5554
// collection = [{ "variables1": Complete, "from_str": None, ... },
5655
// { "variables2": Complete, ... }, ... ]
57-
todo!();
56+
collection.iter().map(|v| count_iterator(v, value)).sum()
5857
}
5958

6059
#[cfg(test)]

exercises/smart_pointers/arc1.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,19 +21,17 @@
2121
//
2222
// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint.
2323

24-
// I AM NOT DONE
25-
2624
#![forbid(unused_imports)] // Do not change this, (or the next) line.
2725
use std::sync::Arc;
2826
use std::thread;
2927

3028
fn main() {
3129
let numbers: Vec<_> = (0..100u32).collect();
32-
let shared_numbers = // TODO
30+
let shared_numbers = Arc::new(numbers);
3331
let mut joinhandles = Vec::new();
3432

3533
for offset in 0..8 {
36-
let child_numbers = // TODO
34+
let child_numbers = Arc::clone(&shared_numbers);
3735
joinhandles.push(thread::spawn(move || {
3836
let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum();
3937
println!("Sum of offset {} is {}", offset, sum);

exercises/smart_pointers/box1.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,9 @@
1818
//
1919
// Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint.
2020

21-
// I AM NOT DONE
22-
2321
#[derive(PartialEq, Debug)]
2422
pub enum List {
25-
Cons(i32, List),
23+
Cons(i32, Box<List>),
2624
Nil,
2725
}
2826

@@ -35,11 +33,11 @@ fn main() {
3533
}
3634

3735
pub fn create_empty_list() -> List {
38-
todo!()
36+
List::Nil
3937
}
4038

4139
pub fn create_non_empty_list() -> List {
42-
todo!()
40+
List::Cons(0, Box::new(List::Nil))
4341
}
4442

4543
#[cfg(test)]

exercises/smart_pointers/cow1.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@
1212
//
1313
// Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint.
1414

15-
// I AM NOT DONE
16-
1715
use std::borrow::Cow;
1816

1917
fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> {
@@ -48,7 +46,8 @@ mod tests {
4846
let slice = [0, 1, 2];
4947
let mut input = Cow::from(&slice[..]);
5048
match abs_all(&mut input) {
51-
// TODO
49+
Cow::Borrowed(_) => Ok(()),
50+
_ => Err("Expected borrowed value"),
5251
}
5352
}
5453

@@ -60,7 +59,8 @@ mod tests {
6059
let slice = vec![0, 1, 2];
6160
let mut input = Cow::from(slice);
6261
match abs_all(&mut input) {
63-
// TODO
62+
Cow::Owned(_) => Ok(()),
63+
_ => Err("Expected owned value"),
6464
}
6565
}
6666

@@ -72,7 +72,8 @@ mod tests {
7272
let slice = vec![-1, 0, 1];
7373
let mut input = Cow::from(slice);
7474
match abs_all(&mut input) {
75-
// TODO
75+
Cow::Owned(_) => Ok(()),
76+
_ => Err("Expected owned value"),
7677
}
7778
}
7879
}

exercises/smart_pointers/rc1.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
//
1111
// Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint.
1212

13-
// I AM NOT DONE
1413

1514
use std::rc::Rc;
1615

@@ -60,17 +59,17 @@ fn main() {
6059
jupiter.details();
6160

6261
// TODO
63-
let saturn = Planet::Saturn(Rc::new(Sun {}));
62+
let saturn = Planet::Saturn(Rc::clone(&sun));
6463
println!("reference count = {}", Rc::strong_count(&sun)); // 7 references
6564
saturn.details();
6665

6766
// TODO
68-
let uranus = Planet::Uranus(Rc::new(Sun {}));
67+
let uranus = Planet::Uranus(Rc::clone(&sun));
6968
println!("reference count = {}", Rc::strong_count(&sun)); // 8 references
7069
uranus.details();
7170

7271
// TODO
73-
let neptune = Planet::Neptune(Rc::new(Sun {}));
72+
let neptune = Planet::Neptune(Rc::clone(&sun));
7473
println!("reference count = {}", Rc::strong_count(&sun)); // 9 references
7574
neptune.details();
7675

@@ -92,12 +91,15 @@ fn main() {
9291
println!("reference count = {}", Rc::strong_count(&sun)); // 4 references
9392

9493
// TODO
94+
drop(earth);
9595
println!("reference count = {}", Rc::strong_count(&sun)); // 3 references
9696

9797
// TODO
98+
drop(venus);
9899
println!("reference count = {}", Rc::strong_count(&sun)); // 2 references
99100

100101
// TODO
102+
drop(mercury);
101103
println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference
102104

103105
assert_eq!(Rc::strong_count(&sun), 1);

exercises/threads/threads1.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@
88
// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a
99
// hint.
1010

11-
// I AM NOT DONE
12-
1311
use std::thread;
1412
use std::time::{Duration, Instant};
1513

@@ -27,6 +25,8 @@ fn main() {
2725
let mut results: Vec<u128> = vec![];
2826
for handle in handles {
2927
// TODO: a struct is returned from thread::spawn, can you use it?
28+
let r = handle.join();
29+
results.push(r.expect("Should not failed."));
3030
}
3131

3232
if results.len() != 10 {

exercises/threads/threads2.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@
77
// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a
88
// hint.
99

10-
// I AM NOT DONE
11-
12-
use std::sync::Arc;
10+
use std::sync::{Arc, Mutex};
1311
use std::thread;
1412
use std::time::Duration;
1513

@@ -18,14 +16,15 @@ struct JobStatus {
1816
}
1917

2018
fn main() {
21-
let status = Arc::new(JobStatus { jobs_completed: 0 });
19+
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
2220
let mut handles = vec![];
2321
for _ in 0..10 {
2422
let status_shared = Arc::clone(&status);
2523
let handle = thread::spawn(move || {
2624
thread::sleep(Duration::from_millis(250));
25+
let mut s = status_shared.lock().unwrap();
2726
// TODO: You must take an action before you update a shared value
28-
status_shared.jobs_completed += 1;
27+
s.jobs_completed += 1;
2928
});
3029
handles.push(handle);
3130
}
@@ -34,6 +33,6 @@ fn main() {
3433
// TODO: Print the value of the JobStatus.jobs_completed. Did you notice
3534
// anything interesting in the output? Do you have to 'join' on all the
3635
// handles?
37-
println!("jobs completed {}", ???);
36+
println!("jobs completed {}", status.lock().unwrap().jobs_completed);
3837
}
3938
}

0 commit comments

Comments
 (0)