~turminal/aoc2022

4af5420a2318008c3ad2c8deb16bfb4bc635b72c — Bor Grošelj Simić 1 year, 10 months ago dbb7db9
day 1
4 files changed, 76 insertions(+), 0 deletions(-)

A 1/lex.mll
A 1/run
A 1/t1.ml
A 1/t2.ml
A 1/lex.mll => 1/lex.mll +17 -0
@@ 0,0 1,17 @@
{
type token =
	| Num of int
	| Newline
  | Eof
}

rule token = parse
	| ['0'-'9']+ '\n' as num { 
    Num (
      String.length num - 1
        |> String.sub num 0
        |> int_of_string
    )
  }
	| '\n' { Newline }
  | eof { Eof }

A 1/run => 1/run +5 -0
@@ 0,0 1,5 @@
#!/bin/sh -ue

ocamllex lex.mll > /dev/null
ocamlc lex.ml "t$1.ml"
exec ./a.out

A 1/t1.ml => 1/t1.ml +27 -0
@@ 0,0 1,27 @@
open Lex

let rec f lexbuf =
	match Lex.token lexbuf with
	| Eof -> []
	| _ as tok -> tok :: f lexbuf

let solve (mx, curr) = function
	| Eof -> (mx, 0)
	| Num n -> (mx, curr + n)
	| Newline -> (curr :: mx, 0)

let rec sum n l =
	match l, n with
	| _, 0 -> 0
	| [], _ -> invalid_arg "sum"
	| a :: l, n -> a + sum (n - 1) l

let () =
	stdin
		|> Lexing.from_channel
		|> f
		|> List.fold_left solve ([], 0)
		|> fst
		|> List.sort (fun a b -> compare b a)
		|> sum 1
		|> Printf.printf "%d\n"

A 1/t2.ml => 1/t2.ml +27 -0
@@ 0,0 1,27 @@
open Lex

let rec f lexbuf =
	match Lex.token lexbuf with
	| Eof -> []
	| _ as tok -> tok :: f lexbuf

let solve (mx, curr) = function
	| Eof -> (mx, 0)
	| Num n -> (mx, curr + n)
	| Newline -> (curr :: mx, 0)

let rec sum n l =
	match l, n with
	| _, 0 -> 0
	| [], _ -> invalid_arg "sum"
	| a :: l, n -> a + sum (n - 1) l

let () =
	stdin
		|> Lexing.from_channel
		|> f
		|> List.fold_left solve ([], 0)
		|> fst
		|> List.sort (fun a b -> compare b a)
		|> sum 3
		|> Printf.printf "%d\n"