RsRust

Rust exercises with solutions

Solve in editor

Write your solution right in the browser.

Open exercises with editor

1. Even numbers Beginner

Print all even numbers from 1 to 10, each on its own line.

Expected output: 2 ⏎ 4 ⏎ 6 ⏎ 8 ⏎ 10

Note

(2..=10).step_by(2) jumps in steps of two. Or check with i % 2 == 0.

Show sample solution
fn main() {
    for i in (2..=10).step_by(2) {
        println!("{i}");
    }
}

2. FizzBuzz (1–15) Beginner

Print the numbers 1 to 15. For multiples of 3 print Fizz instead, for multiples of 5 print Buzz, and for both print FizzBuzz.

Expected output: 1 ⏎ 2 ⏎ Fizz ⏎ 4 ⏎ Buzz ⏎ Fizz ⏎ 7 ⏎ 8 ⏎ Fizz ⏎ Buzz ⏎ 11 ⏎ Fizz ⏎ 13 ⏎ 14 ⏎ FizzBuzz

Note

match (i % 3, i % 5) with the cases (0, 0), (0, _), (_, 0), and _ is elegant. Alternatively, use if/else if with the 15 case first.

Show sample solution
fn main() {
    for i in 1..=15 {
        match (i % 3, i % 5) {
            (0, 0) => println!("FizzBuzz"),
            (0, _) => println!("Fizz"),
            (_, 0) => println!("Buzz"),
            _ => println!("{i}"),
        }
    }
}

3. Reverse a word Beginner

Reverse the text "Rust" and print it.

Expected output: tsuR

Note

Strings have no reverse method, but chars() is an iterator with rev(). With collect::<String>() you build text again.

Show sample solution
fn main() {
    let wort = "Rust";
    let umgekehrt: String = wort.chars().rev().collect();
    println!("{umgekehrt}");
}

4. Sum of squares Beginner

Calculate the sum of the squares of the numbers 1 to 10 and print it.

Expected output: 385

Note

Range 1..=10, then map(|x| x * x) and sum::<i32>().

Show sample solution
fn main() {
    let summe: i32 = (1..=10).map(|x| x * x).sum();
    println!("{summe}");
}

5. Palindrome function Intermediate

Write a function ist_palindrom(text: &str) -> bool that returns true if the text reads the same forwards and backwards (ignoring case). Print ist_palindrom("Anna") and ist_palindrom("Rust").

Expected output: true ⏎ false

Note

First convert with to_lowercase(). You compare two iterators with a.chars().eq(a.chars().rev()).

Show sample solution
fn ist_palindrom(text: &str) -> bool {
    let t = text.to_lowercase();
    t.chars().eq(t.chars().rev())
}

fn main() {
    println!("{}", ist_palindrom("Anna"));
    println!("{}", ist_palindrom("Rust"));
}

6. Most frequent word Intermediate

Find the most frequent word in "a b a c b a" and print it.

Expected output: a

Note

Count with the entry API (*map.entry(w).or_insert(0) += 1) and find the maximum with iter().max_by_key(...) over the counts.

Show sample solution
use std::collections::HashMap;

fn main() {
    let text = "a b a c b a";
    let mut zaehler: HashMap<&str, i32> = HashMap::new();
    for wort in text.split_whitespace() {
        *zaehler.entry(wort).or_insert(0) += 1;
    }
    let (wort, _) = zaehler.iter().max_by_key(|&(_, &n)| n).unwrap();
    println!("{wort}");
}

7. Shapes with a trait Intermediate

Define a trait Form with fn flaeche(&self) -> f64 and two structs Rechteck { b, h } and Quadrat { seite } that implement it. Put a 3x4 rectangle and a square with side 2 into a Vec<Box<dyn Form>> and print the sum of the areas.

Expected output: 16

Note

vec![Box::new(Rechteck { .. }), Box::new(Quadrat { .. })], then formen.iter().map(|f| f.flaeche()).sum::<f64>(). An f64 with the value 16.0 is printed as 16.

Show sample solution
trait Form {
    fn flaeche(&self) -> f64;
}

struct Rechteck { b: f64, h: f64 }
struct Quadrat { seite: f64 }

impl Form for Rechteck {
    fn flaeche(&self) -> f64 { self.b * self.h }
}
impl Form for Quadrat {
    fn flaeche(&self) -> f64 { self.seite * self.seite }
}

fn main() {
    let formen: Vec<Box<dyn Form>> = vec![
        Box::new(Rechteck { b: 3.0, h: 4.0 }),
        Box::new(Quadrat { seite: 2.0 }),
    ];
    let summe: f64 = formen.iter().map(|f| f.flaeche()).sum();
    println!("{summe}");
}

8. Parallel sum Advanced

Calculate the sum 1 to 100 with four threads: thread i (0 to 3) sums the numbers from i*25+1 to (i+1)*25 and returns the partial sum. Add up the partial sums in the main thread and print the result.

Expected output: 5050

Note

(0..4u32).map(|i| thread::spawn(move || ...)).collect::<Vec<_>>(), then h.join().unwrap() for each handle. The range (i*25+1)..=((i+1)*25) has a sum::<u32>() method.

Show sample solution
use std::thread;

fn main() {
    let handles: Vec<_> = (0..4u32)
        .map(|i| thread::spawn(move || ((i * 25 + 1)..=((i + 1) * 25)).sum::<u32>()))
        .collect();
    let gesamt: u32 = handles.into_iter().map(|h| h.join().unwrap()).sum();
    println!("{gesamt}");
}