solve_1.ml 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 is_equation_true equ =
  24. let nb_operators = (List.length equ.operands) - 1 in
  25. let rec aux idx accum l =
  26. if idx == nb_operators then ((accum == equ.result), equ.result) else
  27. match l with
  28. | [] -> (false,equ.result)
  29. | hd :: tl -> (fst ((aux (idx+1) (accum + hd) tl)) ||
  30. fst ((aux (idx+1) (accum * hd) tl)), equ.result) in
  31. aux 0 (List.hd equ.operands) (List.tl equ.operands)
  32. ;;
  33. let solve =
  34. let are_equations_true = List.map is_equation_true input_info in
  35. let results = List.map (fun x -> if (fst x) then (snd x) else 0) are_equations_true in
  36. List.fold_left (+) 0 results;
  37. ;;
  38. let () = printf "Total: %d\n" solve;;