47 lines
1.6 KiB
OCaml
47 lines
1.6 KiB
OCaml
open Printf;;
|
|
open Str;;
|
|
|
|
let read_whole_file f =
|
|
let s = really_input_string f (in_channel_length f) in
|
|
close_in f;
|
|
s
|
|
|
|
let rec process_all_mul_inner re str pos acc =
|
|
try
|
|
let new_pos = Str.search_forward re str pos in
|
|
let n1 = int_of_string @@ Str.matched_group 1 str in
|
|
let n2 = int_of_string @@ Str.matched_group 2 str in
|
|
process_all_mul_inner re str (new_pos + 1) (acc + n1 * n2)
|
|
with Not_found -> acc
|
|
let rec process_all_mul_with_dont_inner re str enabled pos acc =
|
|
try
|
|
let new_pos = Str.search_forward re str pos in
|
|
let command = Str.matched_group 0 str in
|
|
if command = "do()" then
|
|
process_all_mul_with_dont_inner re str true (new_pos + 1) acc
|
|
else if command = "don't()" then
|
|
process_all_mul_with_dont_inner re str false (new_pos + 1) acc
|
|
else if enabled then
|
|
let n1 = int_of_string @@ Str.matched_group 1 str in
|
|
let n2 = int_of_string @@ Str.matched_group 2 str in
|
|
process_all_mul_with_dont_inner re str enabled (new_pos + 1) (acc + n1 * n2)
|
|
else
|
|
process_all_mul_with_dont_inner re str enabled (new_pos + 1) acc
|
|
with Not_found -> acc
|
|
|
|
let process_all_mul str =
|
|
let re = Str.regexp "mul(\\([0-9]+\\),\\([0-9]+\\))" in
|
|
process_all_mul_inner re str 0 0
|
|
|
|
let process_all_mul_with_dont str =
|
|
let re = Str.regexp "mul(\\([0-9]+\\),\\([0-9]+\\))\\|do()\\|don't()" in
|
|
process_all_mul_with_dont_inner re str true 0 0
|
|
|
|
let () =
|
|
let f = open_in "input.txt" in
|
|
let str = read_whole_file f in
|
|
let result = process_all_mul str in
|
|
let result2 = process_all_mul_with_dont str in
|
|
printf "%d\n" result;
|
|
printf "%d\n" result2
|