Rust Implementation of Problem 22

View source code here on GitHub!

Includes

Problem Solution

pub fn problems::p0022::p0022() -> utils::Answer
 1/*
 2Project Euler Problem 24
 3
 4This one was fairly easy for code golf, thanks to the port of Python's itertools
 5
 6Problem:
 7
 8A permutation is an ordered arrangement of objects. For example, 3124 is one
 9possible permutation of the digits 1, 2, 3 and 4. If all of the permutations
10are listed numerically or alphabetically, we call it lexicographic order. The
11lexicographic permutations of 0, 1 and 2 are:
12
13012   021   102   120   201   210
14
15What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4,
165, 6, 7, 8 and 9?
17*/
18use crate::include::utils::{Answer,get_data_file};
19
20fn score(idx: usize, name: &str) -> u32 {
21    return (idx as u32) * name.bytes().map(|x| (x - b'A' + 1) as u32).sum::<u32>();
22}
23
24pub fn p0022() -> Answer {
25    let raw_str = get_data_file("p0022_names.txt").replace("\"", "").to_ascii_uppercase();
26    let mut names: Vec<&str> = raw_str.split(",").collect();
27    names.sort();
28    return Answer::Int(
29        names
30            .into_iter()
31            .enumerate()
32            .map(|(idx, name)| score(idx + 1, name))
33            .sum::<u32>().into()
34    );
35}

Tags: word-problem, sorting, file-io