8.17 Exercises

Click to see the list of suggested exercises
  1. Maximum Function Variants

    • Variant 1: Write a function max_i32 that takes two i32 parameters and returns the maximum value.

      fn max_i32(a: i32, b: i32) -> i32 {
          if a > b { a } else { b }
      }
      fn main() {
          let result = max_i32(3, 7);
          println!("The maximum is {}", result);
      }
    • Variant 2: Write a function max_ref that takes references to i32 values and returns a reference to the maximum value.

      fn max_ref<'a>(a: &'a i32, b: &'a i32) -> &'a i32 {
          if a > b { a } else { b }
      }
      fn main() {
          let x = 5;
          let y = 10;
          let result = max_ref(&x, &y);
          println!("The maximum is {}", result);
      }
    • Variant 3: Write a generic function max_generic that works with any type that implements the PartialOrd and Copy traits.

      fn max_generic<T: PartialOrd + Copy>(a: T, b: T) -> T {
          if a > b { a } else { b }
      }
      fn main() {
          let int_max = max_generic(3, 7);
          let float_max = max_generic(2.5, 1.8);
          println!("The maximum integer is {}", int_max);
          println!("The maximum float is {}", float_max);
      }
  2. String Concatenation: Write a function concat that takes two string slices and returns a new String containing both.

    fn concat(s1: &str, s2: &str) -> String {
        let mut result = String::from(s1);
        result.push_str(s2);
        result
    }
    fn main() {
        let result = concat("Hello, ", "world!");
        println!("{}", result);
    }
  3. Distance Calculation: Define a function that calculates the Euclidean distance between two points in 2D space, using tuples as parameters.

    fn distance(p1: (f64, f64), p2: (f64, f64)) -> f64 {
        let dx = p2.0 - p1.0;
        let dy = p2.1 - p1.1;
        (dx * dx + dy * dy).sqrt()
    }
    fn main() {
        let point1 = (0.0, 0.0);
        let point2 = (3.0, 4.0);
        println!("Distance: {}", distance(point1, point2));
    }
  4. Array Reversal: Write a function that takes a mutable slice of i32 and reverses its elements in place.

    fn reverse(slice: &mut [i32]) {
        let len = slice.len();
        for i in 0..len / 2 {
            slice.swap(i, len - 1 - i);
        }
    }
    fn main() {
        let mut data = [1, 2, 3, 4, 5];
        reverse(&mut data);
        println!("Reversed: {:?}", data);
    }
  5. Implementing find Function: Write a function that searches for an element in a slice and returns its index using Option<usize>.

    fn find(slice: &[i32], target: i32) -> Option<usize> {
        for (index, &value) in slice.iter().enumerate() {
            if value == target {
                return Some(index);
            }
        }
        None
    }
    fn main() {
        let numbers = [10, 20, 30, 40, 50];
        match find(&numbers, 30) {
            Some(index) => println!("Found at index {}", index),
            None => println!("Not found"),
        }
    }