lib.ml 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. open Base
  2. type line = {
  3. lower_bound : int;
  4. upper_bound : int;
  5. char : char;
  6. password : string;
  7. }
  8. let parse_password line = match String.split line ~on:' ' with
  9. | [range; char; password] ->
  10. (match String.lsplit2 range ~on:'-' with
  11. | Some (left_str, right_str) ->
  12. {
  13. lower_bound = Int.of_string(left_str);
  14. upper_bound = Int.of_string(right_str);
  15. char = String.get char 0;
  16. password = password
  17. }
  18. | None -> failwith (Printf.sprintf "Ill-formed range: %s" range))
  19. | _ -> failwith (Printf.sprintf "Ill-formed line: %s" line)
  20. let parse_file filename =
  21. let open Stdio.In_channel in
  22. let lines = with_file ~f:input_lines filename
  23. in List.map ~f:parse_password lines
  24. let old_validate line =
  25. let char_count = String.count ~f:(fun c -> phys_equal c line.char) line.password in
  26. char_count >= line.lower_bound && char_count <= line.upper_bound
  27. let new_validate line =
  28. let first_letter = String.get line.password (line.lower_bound - 1) in
  29. let second_letter = String.get line.password (line.upper_bound - 1) in
  30. Bool.(<>) (Char.(=) first_letter line.char) (Char.(=) second_letter line.char)