谚语串烧-Proverb
1. Readme
谚语
因为没有马蹄钉,一个王国就消失了,或者俗话说.
给出一个输入列表,生成相关的谚语.例如,
- 给定列表
["nail", "shoe", "horse", "rider", "message", "battle", "kingdom"]
- 你将输出这个谚语的全文:
For want of a nail the shoe was lost.
For want of a shoe the horse was lost.
For want of a horse the rider was lost.
For want of a rider the message was lost.
For want of a message the battle was lost.
For want of a battle the kingdom was lost.
And all for the want of a nail.
请注意,输入列表可能会有所不同; 您的解决方案应该能够处理任意长度和内容的列表。输出文本的行不应该是静态的、不变的字符串; 所有的都应该根据给定的输入而变化.
Source
Wikipedia http://en.wikipedia.org/wiki/For_Want_of_a_Nail
2. 开始你的表演
pub fn build_proverb(list: Vec<&str>) -> String { unimplemented!("build a proverb from this list of items: {:?}", list) }
3. 测试代码查看
# #![allow(unused_variables)] #fn main() { #[test] fn test_two_pieces() { let input = vec!["nail", "shoe"]; let expected = vec![ "For want of a nail the shoe was lost.", "And all for the want of a nail.", ] .join("\n"); assert_eq!(build_proverb(input), expected); } // Notice the change in the last line at three pieces. #[test] //#[ignore] fn test_three_pieces() { let input = vec!["nail", "shoe", "horse"]; let expected = vec![ "For want of a nail the shoe was lost.", "For want of a shoe the horse was lost.", "And all for the want of a nail.", ] .join("\n"); assert_eq!(build_proverb(input), expected); } #[test] //#[ignore] fn test_one_piece() { let input = vec!["nail"]; let expected = String::from("And all for the want of a nail."); assert_eq!(build_proverb(input), expected); } #[test] //#[ignore] fn test_zero_pieces() { let input: Vec<&str> = vec![]; let expected = String::new(); assert_eq!(build_proverb(input), expected); } #[test] //#[ignore] fn test_full() { let input = vec![ "nail", "shoe", "horse", "rider", "message", "battle", "kingdom", ]; let expected = vec![ "For want of a nail the shoe was lost.", "For want of a shoe the horse was lost.", "For want of a horse the rider was lost.", "For want of a rider the message was lost.", "For want of a message the battle was lost.", "For want of a battle the kingdom was lost.", "And all for the want of a nail.", ] .join("\n"); assert_eq!(build_proverb(input), expected); } #[test] //#[ignore] fn test_three_pieces_modernized() { let input = vec!["pin", "gun", "soldier", "battle"]; let expected = vec![ "For want of a pin the gun was lost.", "For want of a gun the soldier was lost.", "For want of a soldier the battle was lost.", "And all for the want of a pin.", ] .join("\n"); assert_eq!(build_proverb(input), expected); } #}
4. 答案
# #![allow(unused_variables)] #fn main() { pub fn build_proverb(items: Vec<&str>) -> String { let mut stanzas = Vec::with_capacity(items.len()); for index in 0..items.len() { if index == items.len() - 1 { stanzas.push(format!("And all for the want of a {}.", items[0])); } else { stanzas.push(format!( "For want of a {} the {} was lost.", items[index], items[index + 1] )); } } stanzas.join("\n") } #}