Skip to content

Commit

Permalink
Refactors 022 with sum & mapi ~f:(name_score)
Browse files Browse the repository at this point in the history
- Also puts replace outside the scope of load_names function
  • Loading branch information
FrankKair committed Mar 8, 2020
1 parent a181242 commit 7342761
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/022/p022.ml
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;;

0 comments on commit 7342761

Please sign in to comment.