Skip to content

Commit 5ee6a1f

Browse files
committed
✨ (concepts) Add concept exercise bird-watcher
This is inspired by the same in csharp track. Provides introduction to for loops, arrays and a bit of iterators.
1 parent 796f2ca commit 5ee6a1f

File tree

10 files changed

+584
-0
lines changed

10 files changed

+584
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Hints
2+
3+
## General
4+
5+
- The bird count per day is an array that contains exactly 7 integers.
6+
7+
## 1. Check what the counts were last week
8+
9+
- Define an array that contains last week's log.
10+
- Return the array as a result.
11+
12+
## 2. Check how many birds visited today
13+
14+
- Remember that the counts are ordered by day from oldest to most recent, with the last element representing today.
15+
- Accessing the last element can be done by using its (fixed) index (remember to start counting from zero).
16+
17+
## 3. Increment today's count
18+
19+
- Set the element representing today's count to today's count plus 1.
20+
21+
## 4. Check if there was a day with no visiting birds
22+
23+
- Use if statements for performing comparisions with array elements.
24+
- Use `for in` construct to loop over an array.
25+
26+
## 5. Calculate the number of visiting birds for the first x number of days
27+
28+
- A variable can be used to hold the count for the number of visiting birds.
29+
- The array can be _enumerated_ over using [`.iter()`][.iter()] and [`.enumerate()`][.enumerate()] methods.
30+
- The variable can be updated inside the loop.
31+
- Remember: arrays are indexed from `0`.
32+
- Use `break` statement to stop a loop.
33+
34+
## 6. Calculate the number of busy days
35+
36+
- A variable can be used to hold the number of busy days.
37+
- The array can be _iterated_ over using [`.iter()`][.iter()] method.
38+
- The variable can be updated inside the loop.
39+
- A [conditional statement][if-statement] can be used inside the loop.
40+
41+
[if-statement]: https://doc.rust-lang.org/rust-by-example/flow_control/if_else.html
42+
[.iter()]: https://doc.rust-lang.org/rust-by-example/flow_control/for.html?highlight=iter()#for-and-iterators
43+
[.enumerate()]:
44+
https://doc.rust-lang.org/core/iter/trait.Iterator.html#method.enumerate
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Instructions
2+
3+
You're an avid bird watcher that keeps track of how many birds have visited your garden in the last seven days.
4+
5+
You have six tasks, all dealing with the numbers of birds that visited your garden.
6+
7+
## 1. Check what the counts were last week
8+
9+
For comparison purposes, you always keep a copy of last week's log nearby,
10+
which were: 0, 2, 5, 3, 7, 8 and 4. Implement the `last_week_log()` function
11+
that returns last week's log
12+
13+
```rust
14+
last_week_log();
15+
// => [0, 2, 5, 3, 7, 8, 4]
16+
```
17+
18+
## 2. Check how many birds visited today
19+
20+
Implement the `count_today()` function to return how many birds visited your garden today. The bird counts are ordered by day, with the first element being the count of the oldest day, and the last element being today's count.
21+
22+
```rust
23+
let watch_log = [ 2, 5, 0, 7, 4, 1 ];
24+
count_today(watch_log);
25+
// => 1
26+
```
27+
28+
## 3. Increment today's count
29+
30+
Implement the `log_today()` function to increment today's count:
31+
32+
```rust
33+
let watch_log = [ 2, 5, 0, 7, 4, 1 ];
34+
log_today(watch_log);
35+
count_today(watch_log);
36+
// => 2
37+
```
38+
39+
## 4. Check if there was a day with no visiting birds
40+
41+
Implement the `has_day_without_birds()` method that returns `true` if there was a day at which zero birds visited the garden; otherwise, return `false`:
42+
43+
```rust
44+
let watch_log = [ 2, 5, 0, 7, 4, 1 ];
45+
has_day_without_birds(watch_log);
46+
// => true
47+
```
48+
49+
## 5. Calculate the number of visiting birds for the first x number of days
50+
51+
Implement the `tally_days()` function that returns the number of birds that have visited your garden from the start of the week, but limit the count to the specified number of days from the start of the week.
52+
53+
```rust
54+
let watch_log = [ 2, 5, 0, 7, 4, 1 ];
55+
tally_days(watch_log, 4);
56+
// => 14
57+
```
58+
59+
## 6. Calculate the number of busy days
60+
61+
Some days are busier that others. A busy day is one where five or more birds have visited your garden.
62+
Implement the `calc_busy_days()` function to return the number of busy days:
63+
64+
```rust
65+
let watch_log = [ 2, 5, 0, 7, 4, 1 ];
66+
calc_busy_days(watch_log);
67+
// => 2
68+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
# Introduction
2+
3+
An `array` is a collection of objects of the same type `T`, stored in contiguous
4+
memory. Arrays are created using brackets `[]`, and their length, which is known
5+
at compile time, is part of their type signature `[T; length]`(...)
6+
7+
Unlike arrays in some other languages, arrays in Rust have a fixed length.
8+
9+
10+
## Arrays
11+
### Defining an array
12+
We write the values in an array as a comma-separated list inside square
13+
brackets:
14+
15+
```rust
16+
let my_array = [1, 2, 3, 4, 5];
17+
```
18+
19+
We write an array’s type using square brackets with the type of each element, a
20+
semicolon, and then the number of elements in the array, like so:
21+
22+
```rust
23+
let my_array: [i32; 5] = [1, 2, 3, 4, 5];
24+
```
25+
26+
Here, `i32` is the type of each element. After the semicolon, the number 5
27+
indicates the array contains five elements.
28+
29+
You can also initialize an array to contain the same value for each element by
30+
specifying the initial value, followed by a semicolon, and then the length of
31+
the array in square brackets, as shown here:
32+
33+
```rust
34+
let my_array = [3; 5];
35+
// => [3, 3, 3, 3, 3]
36+
```
37+
38+
### Accessing Array Elements
39+
You can access elements of an array using indexing, like this:
40+
41+
```rust
42+
let a = [1, 2, 3, 4, 5];
43+
44+
let first = a[0];
45+
let second = a[1];
46+
```
47+
48+
49+
### Invalid Array Element Access
50+
Let’s see what happens if you try to access an element of an array that is past
51+
the end of the array.
52+
53+
```rust
54+
let a = [1, 2, 3, 4, 5];
55+
56+
let sixth = a[5];
57+
```
58+
59+
The above program will fail to compile with an error similar to:
60+
```txt
61+
let value = a[5];
62+
^^^^^^^^^^^^ index out of bounds: the length is 5 but the index is 5
63+
```
64+
65+
Now consider when you don't know the index you want to access and it is provided to you via a
66+
function parameter or a user input:
67+
68+
```rust
69+
fn access_element(index: usize) -> i32 {
70+
let a = [1, 2, 3, 4, 5];
71+
return a[index];
72+
}
73+
74+
fn main() {
75+
access_element(5);
76+
}
77+
```
78+
79+
In this case, the Rust compiler cannot know
80+
if the index is out of bounds. The code will compile without errors but fail at
81+
runtime with the following error.
82+
83+
```txt
84+
thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 5'
85+
```
86+
87+
88+
### Use as a type
89+
90+
An array type can be used as a variable type, function parameter or return type.
91+
92+
```rust
93+
let my_var: [i32; 5];
94+
95+
fn my_func(input: [i32; 5]) -> [i32; 5] {}
96+
```
97+
98+
### Changing array elements
99+
Like for any other variable, arrays also have to be defined using `mut` keyword
100+
to allow change. An element can be changed by using assignment operator while
101+
accessing it via an index.
102+
103+
```rust
104+
let mut my_array = [2, 2, 3];
105+
my_array[0] = 1;
106+
// => [1, 2, 3]
107+
```
108+
109+
In the above example, we access the first element via it's index 0 and assign a
110+
new value to it.
111+
112+
## For loops
113+
114+
It’s often useful to execute a block of code more than once. For this task, Rust
115+
provides several loops, which will run through the code inside the loop body to
116+
the end and then start immediately back at the beginning.
117+
118+
### `for` and range
119+
120+
The `for in` construct can be used to iterate through an `Iterator`. We will
121+
learn more about `Iterators` in later concepts. One of the easiest ways to create an iterator is to use the range notation
122+
`a..b`. This yields values from a (inclusive) to b (exclusive) in steps of one.
123+
124+
```rust
125+
// A for loop that iterates 10 times
126+
for n in 0..10 {
127+
// n will have a starting value of 0
128+
// n will have the last value as 9
129+
}
130+
```
131+
132+
Alternatively, `a..=b` can be used for a range that is inclusive on both ends. The above can be written as:
133+
134+
```rust
135+
// A for loop that iterates 10 times
136+
for n in 1..=10 {
137+
// n will have a starting value of 1
138+
// n will have the last value as 10
139+
}
140+
```
141+
142+
### Break and Continue a loop
143+
A for loop can be halted by using the `break` statement.
144+
145+
```rust
146+
// A for loop that iterates 10 times
147+
for n in 1..=10 {
148+
println!(n);
149+
break;
150+
}
151+
// => 1
152+
```
153+
154+
One can conditionally break a for loop as follows:
155+
156+
```rust
157+
// A for loop that iterates 10 times
158+
for n in 1..=10 {
159+
println!(n);
160+
if n == 5 {
161+
break;
162+
}
163+
}
164+
// => 1
165+
// => 2
166+
// => 3
167+
// => 4
168+
// => 5
169+
```
170+
171+
A `continue` statement can be used to skip over an iteration.
172+
```rust
173+
// A for loop that iterates 10 times
174+
for n in 1..=10 {
175+
println!(n);
176+
continue;
177+
}
178+
// => 1
179+
```
180+
181+
Similar to `break`, one can also conditionally use `continue`:
182+
183+
```rust
184+
// A for loop that iterates 10 times
185+
for n in 1..=10 {
186+
println!(n);
187+
if n >= 5 {
188+
continue;
189+
}
190+
}
191+
// => 1
192+
// => 2
193+
// => 3
194+
// => 4
195+
// => 5
196+
```
197+
198+
### Looping Through an Array with `for`
199+
The following shows an example of looping through an array using the `for in` construct.
200+
201+
```rust
202+
let a = [10, 20, 30, 40, 50];
203+
204+
for element in a {
205+
println!("the value is: {element}");
206+
}
207+
```
208+
209+
## Iterators
210+
211+
The `for in` construct interacts in several ways with `Iterator`s. An array
212+
implements the `Iterator` trait. Which makes it an iterator. All iterators have some
213+
very useful built-in methods. You will learn more about what a trait is in later
214+
concepts. For now let's explore the various methods.
215+
216+
- `.iter()` allows to access each element of a collection and leaving the collection untouched and available for reuse after the loop.
217+
```rust
218+
let a = ["Bob", "Frank", "Ferris"];
219+
220+
for name in a.iter() {
221+
println!(name);
222+
}
223+
// => Bob
224+
// => Frank
225+
// => Ferris
226+
227+
println!(a);
228+
// => ["Bob", "Frank", "Ferris"]
229+
```
230+
231+
- `.rev()` allows to access each element in reverse order
232+
```rust
233+
let a = ["Bob", "Frank", "Ferris"];
234+
235+
for name in a.iter().rev() {
236+
println!(name);
237+
}
238+
// => Ferris
239+
// => Frank
240+
// => Bob
241+
242+
println!(a);
243+
// => ["Bob", "Frank", "Ferris"]
244+
```
245+
Notice that we still used `.iter()`. Thats because arrays have a `.reverse()`
246+
method available which as the name suggest reverses the array. But this
247+
changes the array. In our example we only intended to traverse the array in
248+
reverse order not actually change.
249+
250+
- `.enumerate()` allows to access each element along with it's index
251+
```rust
252+
let a = ["Bob", "Frank", "Ferris"];
253+
254+
for (i, name) in a.iter().enumerate() {
255+
println!("{}: {}", i, name);
256+
}
257+
// => 0: Bob
258+
// => 1: Frank
259+
// => 2: Ferris
260+
261+
println!(a);
262+
// => ["Bob", "Frank", "Ferris"]
263+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Generated by Cargo
2+
# will have compiled files and executables
3+
/target/
4+
**/*.rs.bk
5+
6+
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
7+
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
8+
Cargo.lock

0 commit comments

Comments
 (0)