Skip to content

Instantly share code, notes, and snippets.

@BartMassey
Created December 6, 2024 21:16
Show Gist options
  • Save BartMassey/29d1307fba3e74b4b68e17cec761a51b to your computer and use it in GitHub Desktop.
Save BartMassey/29d1307fba3e74b4b68e17cec761a51b to your computer and use it in GitHub Desktop.
Advent of Rust 2024 Day 4 — niceness
//! # [*Advent of Rust 2024* Day 4]: Kids and Niceness
//! Bart Massey 2024
//!
//! This code is licensed under the "MIT License". License terms
//! are [here](https://opensource.org/license/mit).
//!
//! This code is a demo of how to solve the given problem with reasonable
//! programming style and correctness,
//!
//! [*Advent of Rust 2024* Day 4]: https://www.rustfinity.com/practice/rust/challenges/aor-2024-4
// XXX Making these integers f32 is probably a bad idea from
// a numerical precision point of view.
/// Weight of good deeds.
pub const GOOD_WEIGHT: f32 = 1.0;
/// Weight of bad deeds.
pub const BAD_WEIGHT: f32 = 2.0;
/// Threshold for weighted goodness at which a kid is nice
/// instead of naughty.
// XXX This should be rational.
pub const NICE_THRESHOLD: f32 = 0.75;
/// Niceness of a kid.
#[derive(Debug, PartialEq)]
pub enum Niceness {
/// Kid is nice, with the given number of good deeds.
Nice(u32),
/// Kid is naughty.
Naughty,
}
impl Niceness {
/// Given `g` good deeds and `b` bad ones, return a [Niceness].
pub fn new(g: u32, b: u32) -> Self {
let gw = GOOD_WEIGHT;
let bw = BAD_WEIGHT;
// XXX None of this should be a floating-point
// computation. We could punish a kid with a
// rounding error!
//
// Weighted goodness.
let wg = g as f32 * gw;
// Weighted total.
let wt = wg + b as f32 * bw;
let is_nice = g + b > 0 && wg >= wt * NICE_THRESHOLD;
match is_nice {
true => Niceness::Nice(g),
false => Niceness::Naughty,
}
}
}
/// Record for a particular kid.
pub struct Kid {
/// Kid's name.
pub name: String,
/// Kid's niceness.
pub niceness: Niceness,
}
impl Kid {
/// Make a new kid record.
pub fn new(name: String, good_deeds: u32, bad_deeds: u32) -> Kid {
let niceness = Niceness::new(good_deeds, bad_deeds);
Kid { name, niceness }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment