solved 22

This commit is contained in:
Fabian Schmidt 2024-09-16 12:42:55 +02:00
parent 4a5f756db6
commit 0caf96d6db
2 changed files with 31 additions and 0 deletions

1
names.txt Normal file

File diff suppressed because one or more lines are too long

30
src/bin/problem_22.rs Normal file
View File

@ -0,0 +1,30 @@
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let file = File::open("names.txt").expect("Could not open file");
let mut reader = BufReader::new(file);
let mut sorted_names = vec![];
loop {
let mut buffer = vec![];
let num_bytes = reader.read_until(b',', &mut buffer).expect("could not read until");
if num_bytes == 0 {
break;
}
match sorted_names.binary_search(&buffer[..buffer.len()-1].to_vec()) {
Ok(_pos) => {}
Err(pos) => sorted_names.insert(pos, buffer[..buffer.len()-1].to_vec())
}
}
let score_total = sorted_names.iter().enumerate().map(|(pos, bytes)| {
bytes.iter().map(|&byte| {
// Don't count " in front and back of name, or in the case of Alonso, only front since it's been removed in the sorting stage for him
if byte != b'"' {
(byte - b'@') as usize
} else {
0
}
}).sum::<usize>() * (pos + 1)
}).sum::<usize>();
println!("\nscore: {score_total}");
}