From b49452ae077000338b765cd24110438b4a0d0099 Mon Sep 17 00:00:00 2001 From: Alex Karle Date: Tue, 6 Dec 2022 23:33:27 -0500 Subject: [PATCH] day6: Generalize scheme solution, add python sol Mostly just curious how the python speed stacks up! (hint: its just as fast). --- 2022/06/sol.py | 16 ++++++++++++++++ 2022/06/sol.scm | 41 +++++++++++++++-------------------------- 2 files changed, 31 insertions(+), 26 deletions(-) create mode 100644 2022/06/sol.py diff --git a/2022/06/sol.py b/2022/06/sol.py new file mode 100644 index 0000000..e7a20e2 --- /dev/null +++ b/2022/06/sol.py @@ -0,0 +1,16 @@ +import sys + +def last_len_uniq(s, i, n): + return len({c for c in s[i-n:i]}) == n + +s = input() + +for i in range(4, len(s) + 1): + if last_len_uniq(s, i, 4): + print(i) + break + +for i in range(14, len(s) + 1): + if last_len_uniq(s, i, 14): + print(i) + break diff --git a/2022/06/sol.scm b/2022/06/sol.scm index 7f91885..5ce4655 100755 --- a/2022/06/sol.scm +++ b/2022/06/sol.scm @@ -1,33 +1,22 @@ #!/usr/local/bin/chicken-csi -ss -(import (chicken io)) - -(define (uniq lst) - (if (null? lst) - '() - (if (member (car lst) (cdr lst)) - (uniq (cdr lst)) - (cons (car lst) (uniq (cdr lst)))))) - -(define (distinct? lst) - (equal? (length lst) (length (uniq lst)))) +(import (chicken io) + srfi-1) ; delete-duplicates (define (last-len-uniq? s i len) - (cond ((< i len) #f) - (else (distinct? (string->list (substring s (- i len) i)))))) - -(define (find-sop s) - (let loop ((i 4)) - (if (last-len-uniq? s i 4) - i - (loop (add1 i))))) + (and (>= i len) + (equal? len + (length (delete-duplicates (string->list (substring s (- i len) i))))))) -(define (find-som s) - (let loop ((i 4)) - (if (last-len-uniq? s i 14) - i - (loop (add1 i))))) +(define (str-find-idx s len-uniq) + (let ((n (string-length s))) + (let loop ((i 0)) + (if (>= i n) + #f + (if (last-len-uniq? s i len-uniq) + i + (loop (add1 i))))))) (define (main args) (let ((input (read-line))) - (print (find-sop input)) - (print (find-som input)))) + (print (str-find-idx input 4)) + (print (str-find-idx input 14)))) -- libgit2 1.8.1