From ad04552e3915fb351bf77608113a308e13270b05 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Wed, 6 Feb 2019 11:52:08 -0500 Subject: [PATCH] Add twelve days of christmas example --- twelve_days_of_christmas/Cargo.toml | 7 ++++ twelve_days_of_christmas/src/main.rs | 58 ++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 twelve_days_of_christmas/Cargo.toml create mode 100644 twelve_days_of_christmas/src/main.rs diff --git a/twelve_days_of_christmas/Cargo.toml b/twelve_days_of_christmas/Cargo.toml new file mode 100644 index 0000000..6b355df --- /dev/null +++ b/twelve_days_of_christmas/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "twelve_days_of_christmas" +version = "0.1.0" +authors = ["Timothy Warren "] +edition = "2018" + +[dependencies] diff --git a/twelve_days_of_christmas/src/main.rs b/twelve_days_of_christmas/src/main.rs new file mode 100644 index 0000000..a61355a --- /dev/null +++ b/twelve_days_of_christmas/src/main.rs @@ -0,0 +1,58 @@ +const ORDINALS: [&str; 12] = [ + "first", + "second", + "third", + "fourth", + "fifth", + "sixth", + "seventh", + "eighth", + "ninth", + "tenth", + "eleventh", + "twelfth", +]; + +const GIFTS: [&str; 12] = [ + "Twelve drummers drumming", + "Eleven pipers piping", + "Ten lords a-leaping", + "Nine ladies dancing", + "Eight maids a-milking", + "Seven swans a-swimming", + "Six geese a-laying", + "Five golden rings", + "Four calling birds", + "Three french hens", + "Two turtle doves", + "and a partridge in a pear tree.", +]; + +fn format_verse(day: &str, gifts: &str) -> String { + format!("On the {} day of Christmas, my true love gave to me: \n{}\n", day, gifts) +} + +fn main() { + for n in 0..12 { + let verse: String = match n { + 0 => format_verse("first", "A partridge in a pear tree."), + _ => { + // The highest index is 11, and we want + // the highest index to start, so we can + // easily have the cumulative list each verse. + let gift_index = 11 - n; + + // Get the slice of the array of gifts, from + // the index to the end of the array + let gifts = &GIFTS[gift_index..] + .to_vec() // So we have the join method that returns a string + .join(",\n"); + + format_verse(ORDINALS[n], gifts) + } + }; + + // For some reason, the println! macro only takes string literals + println!("{}", verse); + } +}