solve_2.ml 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. open Stdio
  2. open Str
  3. type equation = {
  4. result: int;
  5. operands: int list;
  6. }
  7. let input_info =
  8. let rec aux equation_list =
  9. let line = In_channel.input_line In_channel.stdin in
  10. (match line with
  11. | None -> equation_list
  12. | Some x ->
  13. let parts = split (regexp ":") x in
  14. match parts with
  15. | result :: operands ->
  16. let result_int = int_of_string result in
  17. let operands = split (regexp " ") (List.hd operands) in
  18. let operands_int = List.map int_of_string operands in
  19. aux ({result = result_int; operands = operands_int} :: equation_list)
  20. | [] -> aux equation_list)
  21. in aux []
  22. ;;
  23. let concat x y = (int_of_string ((string_of_int x)^(string_of_int y)));;
  24. let is_equation_true equ =
  25. let nb_operators = (List.length equ.operands) - 1 in
  26. let rec aux idx accum l =
  27. if idx == nb_operators then ((accum == equ.result), equ.result) else
  28. match l with
  29. | [] -> (false,equ.result)
  30. | hd :: tl -> (fst ((aux (idx+1) (accum + hd) tl)) ||
  31. fst ((aux (idx+1) (accum * hd) tl)) ||
  32. fst ((aux (idx+1) (concat accum hd) tl)),
  33. equ.result) in
  34. aux 0 (List.hd equ.operands) (List.tl equ.operands)
  35. ;;
  36. let solve =
  37. let are_equations_true = List.map is_equation_true input_info in
  38. let results = List.map (fun x -> if (fst x) then (snd x) else 0) are_equations_true in
  39. List.fold_left (+) 0 results;
  40. ;;
  41. let () = printf "Total: %d\n" solve;;