Twelve days of christmas improved

This commit is contained in:
Timothy Warren 2019-02-06 12:07:08 -05:00
parent ad04552e39
commit 7a575c7f58
2 changed files with 24 additions and 35 deletions

View File

@ -1,6 +1,6 @@
[package] [package]
name = "twelve_days_of_christmas" name = "twelve_days_of_christmas"
version = "0.1.0" version = "0.2.0"
authors = ["Timothy Warren <twarren@nabancard.com>"] authors = ["Timothy Warren <twarren@nabancard.com>"]
edition = "2018" edition = "2018"

View File

@ -1,16 +1,6 @@
const ORDINALS: [&str; 12] = [ const ORDINALS: [&str; 12] = [
"first", "first", "second", "third", "fourth", "fifth", "sixth",
"second", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
"eleventh",
"twelfth",
]; ];
const GIFTS: [&str; 12] = [ const GIFTS: [&str; 12] = [
@ -28,31 +18,30 @@ const GIFTS: [&str; 12] = [
"and a partridge in a pear tree.", "and a partridge in a pear tree.",
]; ];
fn format_verse(day: &str, gifts: &str) -> String { fn get_gifts(n: usize) -> String {
format!("On the {} day of Christmas, my true love gave to me: \n{}\n", day, gifts) 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() { fn main() {
for n in 0..12 { for n in 0..12 {
let verse: String = match n { println!(
0 => format_verse("first", "A partridge in a pear tree."), "On the {} day of Christmas, my true love gave to me: \n{}\n",
_ => { ORDINALS[n],
// The highest index is 11, and we want get_gifts(n)
// 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);
} }
} }