solve_2.ml 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. open Stdio
  2. open Str
  3. let input_info =
  4. let rec one_string inp nb_rows nb_columns =
  5. let line = In_channel.input_line In_channel.stdin in
  6. match line with
  7. | None -> (inp, (nb_rows, nb_columns))
  8. | Some x -> one_string (inp ^ x) (nb_rows + 1) (String.length x)
  9. in one_string "" 0 0
  10. ;;
  11. let input = fst input_info;;
  12. let nb_rows = (fst (snd input_info));;
  13. let nb_columns = (snd (snd input_info));;
  14. let get_valid_indexes pos =
  15. let filter i =
  16. ( let up = (if ((pos - i*nb_columns) >= 0) then (pos - nb_columns) else -99) in
  17. let down = (if ((pos + i*nb_columns) < nb_columns*nb_rows) then (pos + nb_columns) else -99) in
  18. let upright = (let is_valid_upright = ((((pos - i*(nb_columns - 1)) mod nb_columns) - (pos mod nb_columns)) == i) in
  19. if is_valid_upright then (up + 1) else -99) in
  20. let upleft = (let is_valid_upleft = (((pos mod nb_columns) - ((pos - i*(nb_columns + 1)) mod nb_columns)) == i) in
  21. if is_valid_upleft then (up - 1) else -99) in
  22. let downright = (let is_valid_downright = ((((pos + i*(nb_columns + 1)) mod nb_columns) - (pos mod nb_columns)) == i) in
  23. if is_valid_downright then (down + 1) else -99) in
  24. let downleft = (let is_valid_downleft = (((pos mod nb_columns) - ((pos + i*(nb_columns - 1)) mod nb_columns)) == i) in
  25. if is_valid_downleft then (down - 1) else -99) in
  26. List.filter (fun x -> (snd x) >= 0) [('R',upright);('L',upleft);
  27. ('\\',downright);('/',downleft)]) in
  28. filter 1
  29. ;;
  30. let valid_configs = [
  31. [('R','S');('L','M');('\\','S');('/','M')];
  32. [('R','M');('L','M');('\\','S');('/','S')];
  33. [('R','S');('L','S');('\\','M');('/','M')];
  34. [('R','M');('L','S');('\\','M');('/','S')];
  35. ]
  36. ;;
  37. let count_xmas pos =
  38. let is_xmas pos =
  39. (let list_indexes = List.map (fun x -> (fst x, input.[snd x])) (get_valid_indexes pos) in
  40. if ((List.length list_indexes) == 4) then
  41. (List.exists (fun x -> (compare list_indexes x) == 0) valid_configs) else false) in
  42. if (is_xmas pos) then 1 else 0
  43. ;;
  44. let solve =
  45. let rec aux pos accum=
  46. try
  47. let pos_a = search_forward (regexp "A") input pos in
  48. aux (pos_a + 1) (accum + count_xmas pos_a)
  49. with Not_found -> accum
  50. in
  51. aux 0 0
  52. ;;
  53. let () = printf "Total : %d\n" solve