Skip to content

Instantly share code, notes, and snippets.

@p1xelHer0
Created November 7, 2023 16:19
Show Gist options
  • Select an option

  • Save p1xelHer0/a02050a2711b525619a79d3bd455bfb3 to your computer and use it in GitHub Desktop.

Select an option

Save p1xelHer0/a02050a2711b525619a79d3bd455bfb3 to your computer and use it in GitHub Desktop.

Revisions

  1. p1xelHer0 created this gist Nov 7, 2023.
    55 changes: 55 additions & 0 deletions advent_of_ocaml.ml
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    open ContainersLabels

    let read_file name = CCIO.(with_in name read_lines_l)

    let rec try_parse parsers line =
    match parsers with
    | [] -> failwith ("could not parse: " ^ line)
    | parse :: parsers -> (
    match parse line with
    | None -> try_parse parsers line
    | Some result -> result)

    let parse fmt map line = try Some (Scanf.sscanf line fmt map) with _ -> None

    module Coordinate = struct
    type t = { x : int; y : int }

    let make x y = { x; y }
    end

    type input = Point of Coordinate.t | Name of string

    let parsers =
    [
    parse "{%i,%i}" (fun x y -> Point (Coordinate.make x y));
    parse "(%i,%i)" (fun x y -> Point (Coordinate.make x y));
    parse "[%i,%i]" (fun x y -> Point (Coordinate.make x y));
    parse "%s" (fun s -> Name s);
    ]

    let parse_line = try_parse parsers
    let parsed_input = "./path/to/file" |> read_file |> List.map ~f:parse_line

    let remove_duplicates l =
    let cons_uniq tl hd = if Stdlib.List.mem hd tl then tl else hd :: tl in
    List.rev (List.fold_left ~f:cons_uniq ~init:[] l)

    let sum = List.fold_left ~f:( + ) ~init:0
    let mean l = l |> sum |> fun n -> n / List.length l

    let median l =
    l |> List.sort ~cmp:(fun a b -> a - b) |> fun s ->
    List.nth s (List.length s / 2)

    let rec insert x l =
    match l with
    | [] -> [ [ x ] ]
    | hd :: tl -> (x :: l) :: List.map ~f:(fun elem -> hd :: elem) (insert x tl)

    let rec permutations l =
    match l with
    | [] -> [ l ]
    | hd :: tl -> List.flatten (List.map ~f:(insert hd) (permutations tl))

    let array_flatten a = Array.(concat (to_list a))