From 10eebfbf751dbfe88fadf4e01497a9a5acf13c87 Mon Sep 17 00:00:00 2001 From: Felix Albrigtsen Date: Tue, 6 Dec 2022 10:18:45 +0100 Subject: [PATCH] Do part 2 and cleanup day06 --- day06/main.lisp | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/day06/main.lisp b/day06/main.lisp index 83485c1..f47561d 100644 --- a/day06/main.lisp +++ b/day06/main.lisp @@ -1,20 +1,26 @@ -(defun string-to-list (s) - (assert (stringp s) (s) "~s :questa non e una stringa") - (coerce s 'list)) +; Split to list, remove duplicates, recombine (defun unique-string (str) - (concatenate 'string (remove-duplicates (string-to-list str)))) + (concatenate 'string (remove-duplicates (coerce str 'list)))) -(defun unique-sequence (str n) - (if (= (length (unique-string (subseq str 0 n))) n) - (subseq str 0 n) - (unique-sequence (subseq str 1) n))) +; Returns the index of the first occurrence of a sequence of "len" different characters in "str" +(defun unique-sequence (str len &optional (offset 0)) + (if (= len + (length (unique-string (subseq str offset (+ len offset))))) + offset + (unique-sequence str len (+ offset 1)))) +; unique-sequence gives the index-of, but we want the index-after (defun part1 (str) - (+ 4 (search (unique-sequence str 4) str))) + (+ 4 (unique-sequence str 4))) + +(defun part2 (str) + (+ 14 (unique-sequence str 14))) (let ((in (open "input.txt" :if-does-not-exist nil))) (when in - (print (part1 (read-line in))) + (let ((str (read-line in nil nil))) + (format t "Part 1: ~a~%" (part1 str)) + (format t "Part 2: ~a~%" (part2 str))) (close in)))