-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactors 022 with sum & mapi ~f:(name_score)
- Also puts replace outside the scope of load_names function
- Loading branch information
Showing
1 changed file
with
8 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,29 @@ | ||
open Core_kernel | ||
open Stdio | ||
|
||
let load_names = | ||
let replace ~pattern ~with_str = | ||
Str.global_replace (Str.regexp_string pattern) with_str in | ||
let replace ~pattern ~with_str = | ||
Str.global_replace (Str.regexp_string pattern) with_str | ||
|
||
let load_names = | ||
In_channel.read_all "p022_names.txt" | ||
|> replace ~pattern:"\"" ~with_str:"" | ||
|> String.split ~on:',' | ||
|> List.sort ~compare:(Stdlib.compare) | ||
|
||
let sum = List.fold ~f:(+) ~init:(0) | ||
|
||
let name_score index name = | ||
let char_val c = Char.to_int c - 64 in | ||
name | ||
|> Bytes.of_string | ||
|> Bytes.to_list | ||
|> List.map ~f:(fun c -> (index + 1) * char_val c) | ||
|> List.fold ~f:(+) ~init:(0) | ||
|> sum | ||
|
||
let solve = | ||
load_names | ||
|> List.mapi ~f:(fun i s -> name_score i s) | ||
|> List.fold ~f:(+) ~init:(0) | ||
|> List.mapi ~f:(name_score) | ||
|> sum | ||
|
||
let () = | ||
printf "%i\n" solve;; |