Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Kata:
- To participate in a prize draw each one gives his/her firstname.
- Each letter of a firstname has a value which is its rank in
- the English alphabet. A and a have rank 1, B and b rank 2 and so on.
- The length of the firstname is added to the sum of these ranks
- hence a number n. An array of random weights is linked to the firstnames
- and each n is multiplied by its corresponding weight to get
- what they call a winning number.
- Example: names: COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH weights:
- [1, 4, 4, 5, 2, 1]
- PAUL -> n = length of firstname + 16 + 1 + 21 + 12 = 4 + 50 -> 54
- The weight associated with PAUL is 2 so Paul's winning number is
- 54 * 2 = 108.
- Now one can sort the firstnames in decreasing order of the winning numbers.
- When two people have the same winning number sort them alphabetically by
- their firstnames.
- #Task:
- parameters: st a string of firstnames, we an array of weights, n a rank
- return: the firstname of the participant whose rank is n
- (ranks are numbered from 1)
- #Example: names: COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH weights:
- [1, 4, 4, 5, 2, 1] n: 4
- The function should return: PauL
- Note:
- If st is empty return "No participants".
- If n is greater than the number of participants then return
- "Not enough participants".
- See Examples Test Cases for more examples.
- */
- use std::cmp;
- fn rank(st: &str, we: Vec<i32>, n: usize) -> &str {
- let mut people: Vec<(&str, i32)> = st.split(",").enumerate().map(|(i, name)| {
- (name, name.bytes().fold(name.len() as u8, |mut acc, c| {
- match c {
- b'a' ..= b'z' => acc + c - b'a' + 1,
- b'A' ..= b'Z' => acc + c - b'A' + 1,
- _ => acc,
- }
- }) as i32 * we[i])
- }).collect();
- people.sort_by_key(|&(_, n)| cmp::Reverse(n));
- let (winner, _) = people[n - 1];
- winner
- }
- fn testing(st: &str, we: Vec<i32>, n: usize, exp: &str) -> () {
- assert_eq!(rank(st, we, n), exp)
- }
- #[test]
- fn basics_rank() {
- testing(
- "Addison,Jayden,Sofia,Michael,Andrew,Lily,Benjamin",
- vec![4, 2, 1, 4, 3, 1, 2],
- 4,
- "Benjamin",
- );
- testing(
- "Elijah,Chloe,Elizabeth,Matthew,Natalie,Jayden",
- vec![1, 3, 5, 5, 3, 6],
- 2,
- "Matthew",
- );
- testing(
- "Aubrey,Olivai,Abigail,Chloe,Andrew,Elizabeth",
- vec![3, 1, 4, 4, 3, 2],
- 4,
- "Abigail",
- );
- testing(
- "Lagon,Lily",
- vec![1, 5],
- 2,
- "Lagon",
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement