How to print every month in a specified year that contains five full weekends (Fri, Sat, Sun) in Rust

1 Answer

0 votes
// A month has five full weekends when it has 31 days,
// and the 1st day of the month is a Friday.

use chrono::{Datelike, NaiveDate, Weekday};

// ------------------------------------------------------------
// Month names as a single reusable constant
// ------------------------------------------------------------
const MONTH_NAMES: [&str; 12] = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December",
];

// ------------------------------------------------------------
// Function: returns true if a month has 5 full weekends
// ------------------------------------------------------------
fn has_five_full_weekends(year: i32, month: u32) -> bool {
    // First day of the month
    let first_day = NaiveDate::from_ymd_opt(year, month, 1).unwrap();

    // Number of days in the month
    let days_in_month = first_day
        .with_day(31)
        .map(|_| 31)
        .or_else(|| first_day.with_day(30).map(|_| 30))
        .or_else(|| first_day.with_day(29).map(|_| 29))
        .or_else(|| first_day.with_day(28).map(|_| 28))
        .unwrap();

    let weekday = first_day.weekday(); // Monday=0 ... Friday=4 ... Sunday=6

    days_in_month == 31 && weekday == Weekday::Fri
}

// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
fn main() {
    let y_value = 2026;

    for month in 1..=12 {
        if has_five_full_weekends(y_value, month) {
            println!(
                "{} {} has five full weekends.",
                MONTH_NAMES[(month - 1) as usize],
                y_value
            );
        }
    }
}



/*
run:

May 2026 has five full weekends.

*/

 



answered May 26 by avibootz

Related questions

...