~turminal/aoc2022

2b8438cf75fcfa447abb2682a13023f3449b7ad8 — Bor Grošelj Simić 1 year, 9 months ago d3d0bdf
day 6
3 files changed, 84 insertions(+), 0 deletions(-)

A 6/lex.mll
A 6/t1.ml
A 6/t2.ml
A 6/lex.mll => 6/lex.mll +12 -0
@@ 0,0 1,12 @@
{
type token =
	| Chr of char
	| Eof
}

rule token = parse
	| ['a'-'z'] as c {
		Chr c
	}
        | '\n' { Eof }
	| eof { Eof }

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

type m = Found of int | Not of char list

let rec f lexbuf =
	match Lex.token lexbuf with
	| Eof -> []
	| Chr c -> c :: f lexbuf

let solve m ((c, i): char * int) =
	match m with
	| Found _ -> m
	| Not l ->
			(match List.find_opt ((=) c) l with
			| Some _ ->
				let rec aux c = function
					| [] -> invalid_arg "aux"
					| e :: es when e = c -> []
					| e :: es -> e :: aux c es
				in
				Not (c :: aux c l)
			| None ->
				if List.length l = 3 then
					Found (i + 1)
				else
					Not (c :: l))

let () =
	stdin
		|> Lexing.from_channel
		|> f
		|> List.mapi (fun i x -> (x, i))
		|> List.fold_left solve (Not [])
		|> (function Found i -> i | Not _ -> failwith "oops")
		|> Printf.printf "%d\n"


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

type m = Found of int | Not of char list

let rec f lexbuf =
	match Lex.token lexbuf with
	| Eof -> []
	| Chr c -> c :: f lexbuf

let solve m ((c, i): char * int) =
	match m with
	| Found _ -> m
	| Not l ->
			(match List.find_opt ((=) c) l with
			| Some _ ->
				let rec aux c = function
					| [] -> invalid_arg "aux"
					| e :: es when e = c -> []
					| e :: es -> e :: aux c es
				in
				Not (c :: aux c l)
			| None ->
				if List.length l = 13 then
					Found (i + 1)
				else
					Not (c :: l))

let () =
	stdin
		|> Lexing.from_channel
		|> f
		|> List.mapi (fun i x -> (x, i))
		|> List.fold_left solve (Not [])
		|> (function Found i -> i | Not _ -> failwith "oops")
		|> Printf.printf "%d\n"