Skip to content

Instantly share code, notes, and snippets.

@p1xelHer0
Created November 7, 2023 16:19
Show Gist options
  • Save p1xelHer0/a02050a2711b525619a79d3bd455bfb3 to your computer and use it in GitHub Desktop.
Save p1xelHer0/a02050a2711b525619a79d3bd455bfb3 to your computer and use it in GitHub Desktop.
Advent of OCaml
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))
@geekodour
Copy link

geekodour commented Nov 11, 2023

Just pasting images from your tweet: https://twitter.com/p1xelHer0/status/1721925508894457964/

image

image

image

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment