-
Notifications
You must be signed in to change notification settings - Fork 519
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
✨ (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.
- Loading branch information
Showing
10 changed files
with
584 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
# Hints | ||
|
||
## General | ||
|
||
- The bird count per day is an array that contains exactly 7 integers. | ||
|
||
## 1. Check what the counts were last week | ||
|
||
- Define an array that contains last week's log. | ||
- Return the array as a result. | ||
|
||
## 2. Check how many birds visited today | ||
|
||
- Remember that the counts are ordered by day from oldest to most recent, with the last element representing today. | ||
- Accessing the last element can be done by using its (fixed) index (remember to start counting from zero). | ||
|
||
## 3. Increment today's count | ||
|
||
- Set the element representing today's count to today's count plus 1. | ||
|
||
## 4. Check if there was a day with no visiting birds | ||
|
||
- Use if statements for performing comparisions with array elements. | ||
- Use `for in` construct to loop over an array. | ||
|
||
## 5. Calculate the number of visiting birds for the first x number of days | ||
|
||
- A variable can be used to hold the count for the number of visiting birds. | ||
- The array can be _enumerated_ over using [`.iter()`][.iter()] and [`.enumerate()`][.enumerate()] methods. | ||
- The variable can be updated inside the loop. | ||
- Remember: arrays are indexed from `0`. | ||
- Use `break` statement to stop a loop. | ||
|
||
## 6. Calculate the number of busy days | ||
|
||
- A variable can be used to hold the number of busy days. | ||
- The array can be _iterated_ over using [`.iter()`][.iter()] method. | ||
- The variable can be updated inside the loop. | ||
- A [conditional statement][if-statement] can be used inside the loop. | ||
|
||
[if-statement]: https://doc.rust-lang.org/rust-by-example/flow_control/if_else.html | ||
[.iter()]: https://doc.rust-lang.org/rust-by-example/flow_control/for.html?highlight=iter()#for-and-iterators | ||
[.enumerate()]: | ||
https://doc.rust-lang.org/core/iter/trait.Iterator.html#method.enumerate |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
# Instructions | ||
|
||
You're an avid bird watcher that keeps track of how many birds have visited your garden in the last seven days. | ||
|
||
You have six tasks, all dealing with the numbers of birds that visited your garden. | ||
|
||
## 1. Check what the counts were last week | ||
|
||
For comparison purposes, you always keep a copy of last week's log nearby, | ||
which were: 0, 2, 5, 3, 7, 8 and 4. Implement the `last_week_log()` function | ||
that returns last week's log | ||
|
||
```rust | ||
last_week_log(); | ||
// => [0, 2, 5, 3, 7, 8, 4] | ||
``` | ||
|
||
## 2. Check how many birds visited today | ||
|
||
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. | ||
|
||
```rust | ||
let watch_log = [ 2, 5, 0, 7, 4, 1 ]; | ||
count_today(watch_log); | ||
// => 1 | ||
``` | ||
|
||
## 3. Increment today's count | ||
|
||
Implement the `log_today()` function to increment today's count: | ||
|
||
```rust | ||
let watch_log = [ 2, 5, 0, 7, 4, 1 ]; | ||
log_today(watch_log); | ||
count_today(watch_log); | ||
// => 2 | ||
``` | ||
|
||
## 4. Check if there was a day with no visiting birds | ||
|
||
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`: | ||
|
||
```rust | ||
let watch_log = [ 2, 5, 0, 7, 4, 1 ]; | ||
has_day_without_birds(watch_log); | ||
// => true | ||
``` | ||
|
||
## 5. Calculate the number of visiting birds for the first x number of days | ||
|
||
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. | ||
|
||
```rust | ||
let watch_log = [ 2, 5, 0, 7, 4, 1 ]; | ||
tally_days(watch_log, 4); | ||
// => 14 | ||
``` | ||
|
||
## 6. Calculate the number of busy days | ||
|
||
Some days are busier that others. A busy day is one where five or more birds have visited your garden. | ||
Implement the `calc_busy_days()` function to return the number of busy days: | ||
|
||
```rust | ||
let watch_log = [ 2, 5, 0, 7, 4, 1 ]; | ||
calc_busy_days(watch_log); | ||
// => 2 | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,263 @@ | ||
# Introduction | ||
|
||
An `array` is a collection of objects of the same type `T`, stored in contiguous | ||
memory. Arrays are created using brackets `[]`, and their length, which is known | ||
at compile time, is part of their type signature `[T; length]`(...) | ||
|
||
Unlike arrays in some other languages, arrays in Rust have a fixed length. | ||
|
||
|
||
## Arrays | ||
### Defining an array | ||
We write the values in an array as a comma-separated list inside square | ||
brackets: | ||
|
||
```rust | ||
let my_array = [1, 2, 3, 4, 5]; | ||
``` | ||
|
||
We write an array’s type using square brackets with the type of each element, a | ||
semicolon, and then the number of elements in the array, like so: | ||
|
||
```rust | ||
let my_array: [i32; 5] = [1, 2, 3, 4, 5]; | ||
``` | ||
|
||
Here, `i32` is the type of each element. After the semicolon, the number 5 | ||
indicates the array contains five elements. | ||
|
||
You can also initialize an array to contain the same value for each element by | ||
specifying the initial value, followed by a semicolon, and then the length of | ||
the array in square brackets, as shown here: | ||
|
||
```rust | ||
let my_array = [3; 5]; | ||
// => [3, 3, 3, 3, 3] | ||
``` | ||
|
||
### Accessing Array Elements | ||
You can access elements of an array using indexing, like this: | ||
|
||
```rust | ||
let a = [1, 2, 3, 4, 5]; | ||
|
||
let first = a[0]; | ||
let second = a[1]; | ||
``` | ||
|
||
|
||
### Invalid Array Element Access | ||
Let’s see what happens if you try to access an element of an array that is past | ||
the end of the array. | ||
|
||
```rust | ||
let a = [1, 2, 3, 4, 5]; | ||
|
||
let sixth = a[5]; | ||
``` | ||
|
||
The above program will fail to compile with an error similar to: | ||
```txt | ||
let value = a[5]; | ||
^^^^^^^^^^^^ index out of bounds: the length is 5 but the index is 5 | ||
``` | ||
|
||
Now consider when you don't know the index you want to access and it is provided to you via a | ||
function parameter or a user input: | ||
|
||
```rust | ||
fn access_element(index: usize) -> i32 { | ||
let a = [1, 2, 3, 4, 5]; | ||
return a[index]; | ||
} | ||
|
||
fn main() { | ||
access_element(5); | ||
} | ||
``` | ||
|
||
In this case, the Rust compiler cannot know | ||
if the index is out of bounds. The code will compile without errors but fail at | ||
runtime with the following error. | ||
|
||
```txt | ||
thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 5' | ||
``` | ||
|
||
|
||
### Use as a type | ||
|
||
An array type can be used as a variable type, function parameter or return type. | ||
|
||
```rust | ||
let my_var: [i32; 5]; | ||
|
||
fn my_func(input: [i32; 5]) -> [i32; 5] {} | ||
``` | ||
|
||
### Changing array elements | ||
Like for any other variable, arrays also have to be defined using `mut` keyword | ||
to allow change. An element can be changed by using assignment operator while | ||
accessing it via an index. | ||
|
||
```rust | ||
let mut my_array = [2, 2, 3]; | ||
my_array[0] = 1; | ||
// => [1, 2, 3] | ||
``` | ||
|
||
In the above example, we access the first element via it's index 0 and assign a | ||
new value to it. | ||
|
||
## For loops | ||
|
||
It’s often useful to execute a block of code more than once. For this task, Rust | ||
provides several loops, which will run through the code inside the loop body to | ||
the end and then start immediately back at the beginning. | ||
|
||
### `for` and range | ||
|
||
The `for in` construct can be used to iterate through an `Iterator`. We will | ||
learn more about `Iterators` in later concepts. One of the easiest ways to create an iterator is to use the range notation | ||
`a..b`. This yields values from a (inclusive) to b (exclusive) in steps of one. | ||
|
||
```rust | ||
// A for loop that iterates 10 times | ||
for n in 0..10 { | ||
// n will have a starting value of 0 | ||
// n will have the last value as 9 | ||
} | ||
``` | ||
|
||
Alternatively, `a..=b` can be used for a range that is inclusive on both ends. The above can be written as: | ||
|
||
```rust | ||
// A for loop that iterates 10 times | ||
for n in 1..=10 { | ||
// n will have a starting value of 1 | ||
// n will have the last value as 10 | ||
} | ||
``` | ||
|
||
### Break and Continue a loop | ||
A for loop can be halted by using the `break` statement. | ||
|
||
```rust | ||
// A for loop that iterates 10 times | ||
for n in 1..=10 { | ||
println!(n); | ||
break; | ||
} | ||
// => 1 | ||
``` | ||
|
||
One can conditionally break a for loop as follows: | ||
|
||
```rust | ||
// A for loop that iterates 10 times | ||
for n in 1..=10 { | ||
println!(n); | ||
if n == 5 { | ||
break; | ||
} | ||
} | ||
// => 1 | ||
// => 2 | ||
// => 3 | ||
// => 4 | ||
// => 5 | ||
``` | ||
|
||
A `continue` statement can be used to skip over an iteration. | ||
```rust | ||
// A for loop that iterates 10 times | ||
for n in 1..=10 { | ||
println!(n); | ||
continue; | ||
} | ||
// => 1 | ||
``` | ||
|
||
Similar to `break`, one can also conditionally use `continue`: | ||
|
||
```rust | ||
// A for loop that iterates 10 times | ||
for n in 1..=10 { | ||
println!(n); | ||
if n >= 5 { | ||
continue; | ||
} | ||
} | ||
// => 1 | ||
// => 2 | ||
// => 3 | ||
// => 4 | ||
// => 5 | ||
``` | ||
|
||
### Looping Through an Array with `for` | ||
The following shows an example of looping through an array using the `for in` construct. | ||
|
||
```rust | ||
let a = [10, 20, 30, 40, 50]; | ||
|
||
for element in a { | ||
println!("the value is: {element}"); | ||
} | ||
``` | ||
|
||
## Iterators | ||
|
||
The `for in` construct interacts in several ways with `Iterator`s. An array | ||
implements the `Iterator` trait. Which makes it an iterator. All iterators have some | ||
very useful built-in methods. You will learn more about what a trait is in later | ||
concepts. For now let's explore the various methods. | ||
|
||
- `.iter()` allows to access each element of a collection and leaving the collection untouched and available for reuse after the loop. | ||
```rust | ||
let a = ["Bob", "Frank", "Ferris"]; | ||
|
||
for name in a.iter() { | ||
println!(name); | ||
} | ||
// => Bob | ||
// => Frank | ||
// => Ferris | ||
|
||
println!(a); | ||
// => ["Bob", "Frank", "Ferris"] | ||
``` | ||
|
||
- `.rev()` allows to access each element in reverse order | ||
```rust | ||
let a = ["Bob", "Frank", "Ferris"]; | ||
|
||
for name in a.iter().rev() { | ||
println!(name); | ||
} | ||
// => Ferris | ||
// => Frank | ||
// => Bob | ||
|
||
println!(a); | ||
// => ["Bob", "Frank", "Ferris"] | ||
``` | ||
Notice that we still used `.iter()`. Thats because arrays have a `.reverse()` | ||
method available which as the name suggest reverses the array. But this | ||
changes the array. In our example we only intended to traverse the array in | ||
reverse order not actually change. | ||
|
||
- `.enumerate()` allows to access each element along with it's index | ||
```rust | ||
let a = ["Bob", "Frank", "Ferris"]; | ||
|
||
for (i, name) in a.iter().enumerate() { | ||
println!("{}: {}", i, name); | ||
} | ||
// => 0: Bob | ||
// => 1: Frank | ||
// => 2: Ferris | ||
|
||
println!(a); | ||
// => ["Bob", "Frank", "Ferris"] | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
# Generated by Cargo | ||
# will have compiled files and executables | ||
/target/ | ||
**/*.rs.bk | ||
|
||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries | ||
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock | ||
Cargo.lock |
Oops, something went wrong.