Project Euler #22: Names scores

This article is part of a series where I'll be diving head first into the Project Euler puzzles. I want to document the challenge of solving such a puzzle and how I got to the answer. I want to prefix this by stating that I can't cheat for any of these challenges; with that I mean I can't look up any other implementations online. After the implementation, I will validate the answer by using this document or a similar sheet.

In this article I'll be solving: Project Euler #22.

Introduction You’re given a file with names, calculate the sum of all the name scores. A name score can be determined by summing up all individual character positions in the alphabet and multiply it by the index of that name within the sorted list of names. This particular puzzle is incredibly easy and in all honestly wasn’t much of a challenge. There are sometimes those Euler puzzles that feel a little bit too easy. The full code I used is this:

use std::fs;

fn alphabet_value(name: &str) -> u32 {
    name
        .chars()
        .map(|c| {
            match (b'A'..=b'Z').position(|l| l as char == c) {
                Some(n) => (n + 1) as u32,
                None => 0
            }
        })
        .sum()
}

fn problem_22() -> u32 {
    let contents = fs::read_to_string("p022_names.txt")
                      .unwrap_or("".to_string());

    let mut names: Vec<&str> = contents.split(",").collect();

    names.sort();

    names
        .iter()
        .enumerate()
        .map(|(i, name)| alphabet_value(name) * (i as u32 + 1))
        .sum()
}

Giving me the correct answer of 871198282. The only tricky bit was figuring out how to create a range from A till Z, but a quick Google search gave me that answer [1]. I also did cheat a little and dropped all the double quotes from the p022_names.txt file.

Sources

[1] Rust-lang/Iteration thought alphabets

The full solution is available on GitHub.

55545352515049484746454443424140393837363534333231302928272625242322212019181716151413121110987654321