summaryrefslogtreecommitdiff
path: root/solutions/05_vecs
diff options
context:
space:
mode:
authormo8it <mo8it@proton.me>2024-07-05 13:39:50 +0200
committermo8it <mo8it@proton.me>2024-07-05 13:39:50 +0200
commit7123c7ae3a9605fbe962e4ef0a0f1424cd16fef8 (patch)
treec67f7e62bb9a179ae4fdbab492501cb6847e64c7 /solutions/05_vecs
parent77b687d501771c24bd83294d97b8e6f9ffa92d6b (diff)
parent4d9c346a173bb722b929f3ea3c00f84954483e24 (diff)
Merge remote-tracking branch 'upstream/main' into fix-enum-variant-inconsistency
Diffstat (limited to 'solutions/05_vecs')
-rw-r--r--solutions/05_vecs/vecs1.rs23
-rw-r--r--solutions/05_vecs/vecs2.rs55
2 files changed, 78 insertions, 0 deletions
diff --git a/solutions/05_vecs/vecs1.rs b/solutions/05_vecs/vecs1.rs
new file mode 100644
index 0000000..55b5676
--- /dev/null
+++ b/solutions/05_vecs/vecs1.rs
@@ -0,0 +1,23 @@
+fn array_and_vec() -> ([i32; 4], Vec<i32>) {
+ let a = [10, 20, 30, 40]; // Array
+
+ // Used the `vec!` macro.
+ let v = vec![10, 20, 30, 40];
+
+ (a, v)
+}
+
+fn main() {
+ // You can optionally experiment here.
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_array_and_vec_similarity() {
+ let (a, v) = array_and_vec();
+ assert_eq!(a, *v);
+ }
+}
diff --git a/solutions/05_vecs/vecs2.rs b/solutions/05_vecs/vecs2.rs
new file mode 100644
index 0000000..87f7625
--- /dev/null
+++ b/solutions/05_vecs/vecs2.rs
@@ -0,0 +1,55 @@
+fn vec_loop(input: &[i32]) -> Vec<i32> {
+ let mut output = Vec::new();
+
+ for element in input {
+ output.push(2 * element);
+ }
+
+ output
+}
+
+fn vec_map_example(input: &[i32]) -> Vec<i32> {
+ // An example of collecting a vector after mapping.
+ // We map each element of the `input` slice to its value plus 1.
+ // If the input is `[1, 2, 3]`, the output is `[2, 3, 4]`.
+ input.iter().map(|element| element + 1).collect()
+}
+
+fn vec_map(input: &[i32]) -> Vec<i32> {
+ // We will dive deeper into iterators, but for now, this is all what you
+ // had to do!
+ // Advanced note: This method is more efficient because it automatically
+ // preallocates enough capacity. This can be done manually in `vec_loop`
+ // using `Vec::with_capacity(input.len())` instead of `Vec::new()`.
+ input.iter().map(|element| 2 * element).collect()
+}
+
+fn main() {
+ // You can optionally experiment here.
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_vec_loop() {
+ let input = [2, 4, 6, 8, 10];
+ let ans = vec_loop(&input);
+ assert_eq!(ans, [4, 8, 12, 16, 20]);
+ }
+
+ #[test]
+ fn test_vec_map_example() {
+ let input = [1, 2, 3];
+ let ans = vec_map_example(&input);
+ assert_eq!(ans, [2, 3, 4]);
+ }
+
+ #[test]
+ fn test_vec_map() {
+ let input = [2, 4, 6, 8, 10];
+ let ans = vec_map(&input);
+ assert_eq!(ans, [4, 8, 12, 16, 20]);
+ }
+}