Menu
CoddyTech

Scoring Contracts Recap

Lesson 42 of 48 in Coddy's Rust for C# Developers course.

challenge icon

Challenge

Easy

Define scorer::Scorer with score(&self, word: &str) -> usize. In separate modules, implement length::Length as a unit struct scoring the number of bytes, and vowels::Vowels as a unit struct counting ASCII vowels in either case. ranking::best<S: Scorer>(words: &[String], scorer: &S) -> Option<String> returns an owned clone of the highest-scoring word; ties choose the earliest input word and an empty slice returns None. Call the supplied scorer for each word instead of assuming its concrete type. solve reads mode length or vowels, followed by ASCII words. Return the best word or empty when there are no words. Input has at most 100 words, each at most 100 bytes.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, scorer.rs, length.rs, vowels.rs, ranking.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod scorer;
mod length;
mod vowels;
mod ranking;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
use scorer::Scorer;
assert_eq!(length::Length.score("ridge"), 5); assert_eq!(length::Length.score(""), 0);
assert_eq!(vowels::Vowels.score("AEiouY"), 5); assert_eq!(vowels::Vowels.score("rhythm"), 0);
let words = vec!["north".to_string(), "east".to_string(), "south".to_string()];
assert_eq!(ranking::best(&words, &length::Length), Some("north".to_string()));
assert_eq!(ranking::best(&words, &vowels::Vowels), Some("east".to_string()));
struct PreferLastLetter;
impl scorer::Scorer for PreferLastLetter { fn score(&self, w: &str) -> usize { w.bytes().last().unwrap_or(0) as usize } }
assert_eq!(ranking::best(&words, &PreferLastLetter), Some("east".to_string()));
assert_eq!(ranking::best(&[], &PreferLastLetter), None);
let zeros = vec!["dry".to_string(), "sky".to_string()];
assert_eq!(ranking::best(&zeros, &vowels::Vowels), Some("dry".to_string()));
assert_eq!(ranking::best(&words, &length::Length), Some("north".to_string()));
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}

All lessons in Rust for C# Developers

Practice on your own: Online Rust compiler