From 7a575c7f587aa44fb952f023f795a5f0113ca92b Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Wed, 6 Feb 2019 12:07:08 -0500 Subject: [PATCH] Twelve days of christmas improved --- twelve_days_of_christmas/Cargo.toml | 2 +- twelve_days_of_christmas/src/main.rs | 57 +++++++++++----------------- 2 files changed, 24 insertions(+), 35 deletions(-) diff --git a/twelve_days_of_christmas/Cargo.toml b/twelve_days_of_christmas/Cargo.toml index 6b355df..fca3bd9 100644 --- a/twelve_days_of_christmas/Cargo.toml +++ b/twelve_days_of_christmas/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "twelve_days_of_christmas" -version = "0.1.0" +version = "0.2.0" authors = ["Timothy Warren "] edition = "2018" diff --git a/twelve_days_of_christmas/src/main.rs b/twelve_days_of_christmas/src/main.rs index a61355a..9fae2e1 100644 --- a/twelve_days_of_christmas/src/main.rs +++ b/twelve_days_of_christmas/src/main.rs @@ -1,16 +1,6 @@ const ORDINALS: [&str; 12] = [ - "first", - "second", - "third", - "fourth", - "fifth", - "sixth", - "seventh", - "eighth", - "ninth", - "tenth", - "eleventh", - "twelfth", + "first", "second", "third", "fourth", "fifth", "sixth", + "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth", ]; const GIFTS: [&str; 12] = [ @@ -28,31 +18,30 @@ const GIFTS: [&str; 12] = [ "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 get_gifts(n: usize) -> String { + match n { + 0 => String::from("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 + GIFTS[gift_index..] + .to_vec() // So we have the join method that returns a string + .join(",\n") + } + } } 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); + println!( + "On the {} day of Christmas, my true love gave to me: \n{}\n", + ORDINALS[n], + get_gifts(n) + ); } }