id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
sequencelengths
1
47
41,453
c3.lsp
Boerseth_lisp/ansicl/c3.lsp
(load "headers.lsp") (chapter 3 "LISTS") (section 3 1 "Conses") (setf x (cons 'a nil)) x (car x) (cdr x) (setf y (list 'a 'b 'c)) (cdr y) (setf z (list 'a (list 'b 'c) 'd)) (car (cdr z)) (consp (list 'a)) (consp nil) (defun our-listp (x) (or (null x) (consp x))) (our-listp nil) (listp nil) (our-listp (list 'a 'b)) (listp (list 'a 'b)) (defun our-atom (x) (not (consp x))) (our-atom 3) (atom 3) (our-atom nil) (atom nil) (section 3 2 "Equality") (eql (cons 'a nil) (cons 'a nil)) (setf x (cons 'a nil)) (eql x x) (equal x (cons 'a nil)) (defun our-equal (x y) (or (eql x y) (and (consp x) (consp y) (our-equal (car x) (car y)) (our-equal (cdr x) (cdr y))))) (section 3 3 "Why Lisp Has No Pointers") (setf x '(a b c)) (setf y x) (eql x y) (setf x nil) y (section 3 4 "Building Lists") (setf x '(a b c) y (copy-list x)) (defun our-copy-list (lst) (if (atom lst) lst (cons (car lst) (our-copy-list (cdr lst))))) (eql x (copy-list x)) (equal x (copy-list x)) (append '(a b) '(c d) '(e)) (section 3 5 "Compression") (defun compress (x) (if (consp x) (compr (car x) 1 (cdr x)) x)) (defun compr (elt n lst) (if (null lst) (list (n-elts elt n)) (if (eql (car lst) elt) (compr elt (+ n 1) (cdr lst)) (cons (n-elts elt n) (compr (car lst) 1 (cdr lst)))))) (defun n-elts (elt n) (if (> n 1) (list n elt) elt)) (compress '(1 1 1 0 1 0 0 0 0 1)) (defun uncompress (lst) (if (null lst) nil (let ((elmt (car lst)) (tail (uncompress (cdr lst)))) (if (consp elmt) (append (apply #'list-of elmt) tail) (cons elmt tail))))) (defun list-of (n el) (if (zerop n) nil (cons el (list-of (- n 1) el)))) (uncompress '((3 1) 0 1 (4 0) 1)) (list-of 3 'ho) (section 3 6 "Access") (nth 0 '(a b c)) (nthcdr 2 '(a b c d e)) (defun our-nthcdr (n lst) (if (< n 1) lst (our-nthcdr (- n 1) (cdr lst)))) 'our-nthcdr (last '(a b c)) (defun our-last (lst) (if (null (cdr lst)) lst (our-last (cdr lst)))) 'our-last (our-last '(a b c)) (section 3 7 "Mapping Functions") (mapcar #'(lambda (x) (+ x 10)) '(1 2 3)) (mapcar #'list '(a b c) '(1 2 3 4)) (maplist #'(lambda (x) x) '(a b c)) (section 3 8 "Trees") (defun our-copy-tree (tr) (if (atom tr) tr (cons (our-copy-tree (car tr)) (our-copy-tree (cdr tr))))) (substitute 'y 'x '(and (integerp x) (zerop (mod x 2)))) (subst 'y 'x '(and (integerp x) (zerop (mod x 2)))) (defun our-subst (new old tree) (if (eql tree old) new (if (atom tree) tree (cons (our-subst new old (car tree)) (our-subst new old (cdr tree)))))) (section 3 9 "Understanding Recursion") (defun len (lst) (if (null lst) 0 (+ 1 (len (cdr lst))))) (section 3 10 "Sets") (member 'b '(a b c)) (member '(a) '((a) (z)) :test #'equal) (member 'a '((a b) (c d)) :key #'car) (member 2 '((1) (2)) :key #'car :test #'equal) (member 2 '((1) (2)) :test #'equal :key #'car) (member-if #'oddp '(2 3 4)) (defun our-member-if (fn lst) (and (consp lst) (if (funcall fn (car lst)) lst (our-member-if fn (cdr lst))))) (adjoin 'b '(a b c)) (adjoin 'z '(a b c)) (union '(a b c) '(c b s)) (intersection '(a b c) '(b b c)) (set-difference '(a b c d e) '(b c)) (section 3 11 "Sequences") (length '(a b c)) (subseq '(a b c d) 1 2) (subseq '(a b c d) 1) (reverse '(a b c)) (defun mirrorp (s) (let ((len (length s))) (if (evenp len) (let ((mid (/ len 2))) (equal (subseq s 0 mid) (reverse (subseq s mid)))) (let ((mid (/ (+ len 1) 2))) (equal (subseq s 0 mid) (reverse (subseq s (- mid 1)))))))) (mirrorp '(a b b a)) (mirrorp '(a b a)) (mirrorp '(a b c b a)) (mirrorp '(a b c c b a)) (mirrorp '(a b d c b a)) (mirrorp '(a b d a c b a)) (/ 4 2) (/ 5 2) (sort '(0 2 1 3 8) #'>) (sort '(0 2 1 3 8) #'<) (defun nthmost (n lst) (nth (- n 1) (sort (copy-list lst) #'>))) 'nthmost (nthmost 2 '(0 2 1 3 8)) (every #'oddp '(1 3 5)) (some #'evenp '(1 2 3)) (every #'> '(1 3 5) '(0 2 4)) (section 3 12 "Stacks") (setf x '(b)) (push 'a x) x (setf y x) (pop x) x y (defun our-reverse (lst) (let ((acc nil)) (dolist (elmt lst) (push elt acc)) acc)) (let ((x '(a b))) (pushnew 'c x) (pushnew 'a x) x) (section 3 13 "Dotted Lists") (defun properlistp (x) (or (null x) (and (consp x) (properlistp (cdr x))))) (setf pair (cons 'a 'b)) '(a . b) '(a . nil) '(a . (b . (c . nil))) (cons 'a (cons 'b (cons 'c 'd))) '(a . (b . nil)) '(a . (b)) '(a b . nil) '(a b) (section 3 14 "Assoc-lists") (setf trans '((+ . "add") (- . "subtract"))) (assoc '+ trans) (assoc '* trans) (defun our-assoc (key alist) (and (consp alist) (let ((pair (car alist))) (if (eql key (car pair)) pair (our-assoc key (cdr alist)))))) (section 3 15 "Example: Shortest Path") (setf min '((a b c) (b c) (c d))) (cdr (assoc 'a min)) (defun shortest-path (start end net) (bfs end (list (list start)) net)) (defun bfs (end queue net) (if (null queue) nil (let ((path (car queue))) (let ((node (car path))) (if (eql node end) (reverse path) (bfs end (append (cdr queue) (new-paths path node net)) net)))))) (defun new-paths (path node net) (mapcar #'(lambda (n) (cons n path)) (cdr (assoc node net)))) (shortest-path 'a 'd min)
5,653
Common Lisp
.l
233
20.120172
56
0.525395
Boerseth/lisp
0
0
0
GPL-3.0
9/19/2024, 11:50:26 AM (Europe/Amsterdam)
565a85bdf0f1c7bfcea7db7da2e9e2478da59db54462322221ed3d468f657b15
41,453
[ -1 ]
41,454
c2.lsp
Boerseth_lisp/ansicl/c2.lsp
(load "headers.lsp") (chapter 2 "WELCOME TO LISP") (section 2 1 "Form") 1 (+ 2 3) (+ 2 3 4) (+ 2 3 4 5) (/ (- 7 1) (- 4 2)) (section 2 2 "Evaluation") (quote (+ 3 5)) '(+ 3 5) (section 2 3 "Data") 'Artichoke '(my 3 "Sons") '(the list (a b c) has 3 elements) (list 'my (+ 2 1) "Sons") (list '(+ 2 1) (+ 2 1)) () nil (section 2 4 "List Operations") (cons 'a '(b c d)) (cons 'a (cons 'b nil)) (list 'a 'b) (car '(a b c)) (cdr '(a b c)) (car (cdr (cdr '(a b c d)))) (third '(a b c d)) (section 2 5 "Truth") (listp '(a b c)) (listp 27) (null nil) (not nil) (if (listp '(a b c)) (+ 1 2) (+ 5 6)) (if (listp 27) (+ 1 2) (+ 5 6)) (if (listp 27) (+ 2 3)) (if 27 1 2) (and t (+ 1 2)) (section 2 6 "Functions") (defun our-third (x) (car (cdr (cdr x)))) (our-third '(a b c d)) (> (+ 1 4) 3) (defun sum-greater (x y z) (> (+ x y) z)) (sum-greater 1 4 3) (section 2 7 "Recursion") (defun our-member (obj lst) (if (null lst) nil (if (eql obj (car lst)) lst (our-member obj (cdr lst))))) (section 2 8 "Reading Lisp") (section 2 9 "Input and Output") (format t "~A plus ~A equals ~A,~%" 2 3 (+ 2 3)) (defun askem (string) (format t "~A" string) (read)) ;(askem "How old are you?")) (section 2 10 "Variables") (let ((x 1) (y 2)) (+ x y)) (defun ask-number () (format t "Please enter a number.") (let ((val (read))) (if (numberp val) val (ask-number)))) ;(ask-number) (defparameter *glob* 99) (defconstant limit (+ *glob* 1)) (boundp '*glob*) (section 2 11 "Assignment") (setf *glob* 98) (let ((n 10)) (setf n 2) n) (setf x (list 'a 'b 'c)) x (setf (car x) 'n) x (setf a 3 v 6 s 42) a (defconstant constant 5) (defparameter *global* 5) (let ((local 5)) '(do stuff) '(return last)) (setf var 5) (setf (first (list *global* constant)) 4) *global* ; 4 ? (section 2 12 "Functional Programming") (setf lst '(c a r a t)) (remove 'a lst) lst (setf x '(a b c)) (setf x (remove 'a x)) x (section 2 13 "Iteration") (defun show-squares (start end) (do ((i start (+ i 1))) ((> i end) 'done) (format t "~A ~A~%" i (* i i)))) (show-squares 1 6) (defun printall (lst) (do ((element (car lst) (setf lst (cdr lst) element (car lst)))) ((null lst) 'done) (format t "~A~%" element))) (printall '(a b c d e f)) (defun show-squares-rec (i end) (if (> i end) 'done (progn (format t "~A ~A~%" i (* i i)) (show-squares-rec (+ i 1) end)))) (show-squares-rec 1 6) (defun our-length (lst) (let ((len 0)) (dolist (obj lst) (setf len (+ len 1))) len)) (our-length '(1 2 3 4 5 6)) (defun our-length (lst) (if (null lst) 0 (+ (our-length (cdr lst)) 1))) (section 2 14 "Functions as Objects") (function +) #'+ (apply #'+ (list 1 2 3)) (apply #'+ 1 2 '(3 4 5)) (funcall #'+ 1 2 3) (lambda (x y) (+ x y)) ((lambda (x) (+ x 100)) 1) (funcall #'(lambda (x) (+ x 100)) 1) (section 2 15 "Types") (typep 27 'integer) (typep 27 't) (typep "hello" 't) (typep "hello" 'integer) (section 2 16 "Looking Forward")
3,027
Common Lisp
.l
147
18.387755
66
0.57369
Boerseth/lisp
0
0
0
GPL-3.0
9/19/2024, 11:50:26 AM (Europe/Amsterdam)
e1e787ca9874d5e2f69b69008e0c3346bb007d0e6d6727322e2e40ce09fab318
41,454
[ -1 ]
41,455
runner.lsp
Boerseth_lisp/ansicl/runner.lsp
(defun simulate-read (expression) (format t "~A" (concatenate 'string (format nil "~%> ") (format nil "~A" expression)))) (defun simulate-eval (expression) (format t "~%~A" (eval expression))) (defun simulate-repl (expression) (progn (simulate-read expression) (simulate-eval expression))) (defun run-file-as-if-repl (file) (with-open-file (in file) (loop for expression = (read in nil in) until (eq expression in) do (simulate-repl expression)))) (loop for file in EXT:*ARGS* do (run-file-as-if-repl file))
613
Common Lisp
.l
20
24.4
50
0.611205
Boerseth/lisp
0
0
0
GPL-3.0
9/19/2024, 11:50:26 AM (Europe/Amsterdam)
8aa23fc33754376f3b11368941acbced291d5328ec379ce4d2e306b9ed529313
41,455
[ -1 ]
41,456
c1.lsp
Boerseth_lisp/ansicl/c1.lsp
(load "headers.lsp") (chapter 1 "INTRODUCTION") (section 1 1 "New Tools") (defun sum (n) (let ((s 0)) (dotimes (i n s) (incf s i)))) (sum 5) (defun addn (n) #'(lambda (x) (+ x n))) (section 1 2 "New Techniques") (section 1 3 "A New Approach")
268
Common Lisp
.l
13
17.692308
30
0.6
Boerseth/lisp
0
0
0
GPL-3.0
9/19/2024, 11:50:26 AM (Europe/Amsterdam)
e3bcf758011efc53d70f77159a33413a5f191b824a00cf5dfab25f0cb7f71958
41,456
[ -1 ]
41,457
headers.lsp
Boerseth_lisp/ansicl/headers.lsp
(defun chapter (chap name) (concatenate 'string (format nil "~%==================================================") (format nil "~% ~A ~A" chap name) (format nil "~%=================================================="))) (defun section (chap sec name) (concatenate 'string (format nil "~% ~A.~A ~A" chap sec name) (format nil "~%--------------------------------------------------"))) (defun exercise (num desc) "") (defun answer (a) "") (defun done () (format nil "~%")) (defun ddone () (format nil "~%~%"))
548
Common Lisp
.l
15
33.2
73
0.404896
Boerseth/lisp
0
0
0
GPL-3.0
9/19/2024, 11:50:26 AM (Europe/Amsterdam)
f121d92b384ce60d324d2c15d519484053371ad681d381f8b02e59da953c4a58
41,457
[ -1 ]
41,458
c3ex.lsp
Boerseth_lisp/ansicl/c3ex.lsp
(load "headers.lsp") (section "" "" "Exercises") (exercise "1." "Show the following lists in box notation:") (exercise "[a]" "(a b (c d))") (answer " ->[ | ]->[ | ]->[ | ]-> nil | | | V V V a b [ | ]->[ | ]-> nil | | V V c d ") (done) (exercise "[b]" "(a (b (c (d))))") (answer " ->[ | ]->[ | ]-> nil | | V V a [ | ]->[ | ]-> nil | | V V b [ | ]->[ | ]-> nil | | V V c [ | ]-> nil | V d ") (done) (exercise "[c]" "(((a b) c) d)") (answer " ->[ | ]->[ | ]-> nil | | | V | d | [ | ]->[ | ]-> nil | | | V | c V [ | ]->[ | ]-> nil | | V V a b ") (done) (exercise "[d]" "(a (b . c) . d)") (answer " ->[ | ]->[ | ]-> d | | V V a [ | ]-> c | V b ") (ddone) (exercise "2." "Write a version of union that preserves the order of the elements in the original lists: > (new-union '(a b c) '(b a d)) (A B C D) ") (defun new-union-rec (set1 set2) (reverse (include set2 (include set1 nil)))) (defun include (elements inclusion) (if (null elements) inclusion (if (member (car elements) inclusion) (include (cdr elements) inclusion) (include (cdr elements) (cons (car elements) inclusion))))) "" (defun new-union-iter (set1 set2) (let ((new-set nil)) (dolist (el1 set1) (if (not (member el1 new-set)) (setf new-set (cons el1 new-set)))) (dolist (el2 set2) (if (not (member el2 new-set)) (setf new-set (cons el2 new-set)))) (reverse new-set))) "" (defun new-union (set1 set2) (new-union-rec set1 set2)) (new-union '(a b c) '(b a d)) (ddone) (exercise "3." "Define a function that takes a list and returns a list indicating the number of times each (eql) element appears, sorted from most common to least common: > (occurrences '(a b a d a c d c a)) ((A . 4) (C . 2) (D . 2) (B . 1)) ") (defun occurrences-iter (history) (let ((occs nil)) (dolist (elmt history) (let ((entry (assoc elmt occs))) (if (null entry) (setf occs (cons (cons elmt 1) occs)) (setf (cdr entry) (+ 1 (cdr entry)))))) (sort occs #'(lambda (x y) (> (cdr x) (cdr y)))))) (occurrences-iter '(a b a d a c d c a)) (defun occurences-rec (lst) (sort (occurences-lib lst nil) #'> :key #'cdr)) (defun occurences-lib (lst acc) (if (null lst) acc (if (null (assoc (car lst) acc)) (occurences-lib (cdr lst) (cons (cons (car lst) 1) acc)) (let ((cur (assoc (car lst) acc)) (new (cons (car lst) (+ 1 (cdr cur))))) (occurences-lib (cdr lst) (substitute new cur acc :test #'equal)))))) ;(occurrences-rec '(a b a d a c d c a)) ; ;(defun occurrences (history) ; (let ((occs '(nil))) ; (dolist (elmt history) ; (let ((cnt (cdr (assoc elmt occs)))) ; (if (null cnt) ; (setf occs (append '((elmt . 1)) occs)) ; (setf (cdr (assoc elmt occs)) (+ cnt 1))))) ; (sort occs #'(lambda (x y) (> (cdr x) (cdr y)))))) ; ;(defun occurrences (history) ; (let ((occs nil)) ; (dolist (elmt history) ; (let ((cnt (cdr (assoc elmt occs)))) ; (if (null cnt) ; (setf occs (cons (cons elmt 1) occs)) ; (setf (cdr (assoc elmt occs)) (+ cnt 1))))) ; (sort occs #'(lambda (x y) (> (cdr x) (cdr y)))))) ; (ddone) (exercise "4." "Why does (member '(a) '((a) (b))) return nil?") (answer "Because while '(a) and the first element of the list are `equal`, they are not `eql`. The two are differnt conses.") (ddone) (exercise "5." "Suppose a function pos+ takes a list and returns a list of each element plus its position: > (pos+ '(7 5 1 4)) (7 6 3 7) Define this function using (a) recursion, (b) iteration, (c) mapcar. ") (answer "[a]") (defun pos+rec (lst) (pos+rec-lib lst 0)) (defun pos+rec-lib (lst n) (if (not (null lst)) (cons (+ n (car lst)) (pos+rec-lib (cdr lst) (+ 1 n))))) (pos+rec '(7 5 1 4)) (done) (answer "[b]") (defun pos+iter (lst) (let ((n 0) (new-lst '())) (dolist (elmt lst) (push (+ elmt n) new-lst) (setf n (+ n 1))) (reverse new-lst))) (pos+iter '(7 5 1 4)) (done) (answer "[c]") (defun pos+mapcar (lst) (let ((n -1)) (mapcar #'(lambda (x) (setf n (+ n 1)) (+ x n)) lst))) (pos+mapcar '(7 5 1 4)) (ddone) (exercise "6." "After years of deliberation, a government commission has decided that lists should be represented by using the cdr to point to the first element and the car to point to the rest of the list. Define the government version of the following functions:") (exercise "[a]" "cons") (defun cons-g (car-g cdr-g) (cons cdr-g car-g)) (done) (exercise "[b]" "list") (defun list-g (elmt) (cons nil elmt)) "I don't know how to make this for arbitrary many elements." (done) (exercise "[c]" "length (for lists)") (defun length-g (lst) (if (null (car lst)) 0 (+ 1 (length-g (car lst))))) (done) (exercise "[d]" "member (for lists; no keywords)") (defun member-g (elmt lst) (if (eql elmt (cdr lst)) lst (if (null (car lst)) nil (member-g elmt (car lst))))) (ddone) (exercise "7." "Modify the program in figure 3.6 to use fewer cons cells. (Hint: Use dotted lists.)") (exercise "8." "Define a function that takes a list and prints it in dot notaiton: > (showdots '(a b c)) (A . (B . (C . NIL))) NIL ") (defun showdots (lst) (if (consp lst) (format nil "(~A . ~A)" (car lst) (showdots (cdr lst))))) (showdots '(a b c)) (ddone) (exercise "9." "Write a program to find the _longest_ finite path through a network represented as in Section 3.15. The network may contain cycles.") (defun longest-path (start end net) (bfs end (list (list start)) nil net)) "" (defun bfs (end queue longest net) (if (null queue) (if (null longest) nil longest) (let ((path (car queue))) (let ((node (car path))) (if (member node (cdr path)) (bfs end (cdr queue) longest net) (if (eql node end) (if (> (length path) (length longest)) (bfs end (cdr queue) (reverse path) net) (bfs end (cdr queue) longest net)) (bfs end (append (cdr queue) (new-paths path node net)) longest net))))))) "" (defun new-paths (path node net) (mapcar #'(lambda (n) (cons n path)) (cdr (assoc node net)))) "" (setf my-net '((a b c) (b c) (c d))) (longest-path 'a 'd my-net)
6,964
Common Lisp
.l
231
24.922078
266
0.519529
Boerseth/lisp
0
0
0
GPL-3.0
9/19/2024, 11:50:26 AM (Europe/Amsterdam)
3fd67e997781c233591f332141f93783ec4f7a0f807c7683fdc9379c8315cecc
41,458
[ -1 ]
41,481
main.lisp
lambdanil_lispy-stuff/main.lisp
(require "asdf") (require 'uiop) (import 'uiop:split-string 'CL-USER) (defun cls () (format t "~A[H~@*~A[J" #\escape)) (defmacro make-vector (&aux type) "Create a resizable array" (if type `(make-array 0 :fill-pointer 0 :adjustable t :element-type ,type) `(make-array 0 :fill-pointer 0 :adjustable t))) (defmacro take (n &key (start 0)) "Take a list of n values" `(loop for i from ,start to (+ ,start (1- ,n)) collect i)) (defmacro --> (&rest data) "Call a list of functions as nested." (labels ((getlist (funcs) (if (cdr funcs) (cons (car funcs) (list (getlist (cdr funcs)))) (if (listp (car funcs)) (car funcs) (list (car funcs)))))) (getlist data))) ;; This macro is inspired by clojure (defmacro -> (&rest args) "Call a list of functions in order." (let ((data (reverse args))) (labels ((getlist (funcs) (if (cadr funcs) (if (listp (car funcs)) (append (list (caar funcs)) (list (getlist (cdr funcs))) (cdar funcs)) (append (list (car funcs)) (list (getlist (cdr funcs))))) (car funcs)))) (getlist data)))) ;; This one too (defmacro ->> (&rest args) "Call a list of functions in order." (let ((data (reverse args))) (labels ((getlist (funcs) (if (cdr funcs) (if (listp (car funcs)) (append (car funcs) (list (getlist (cdr funcs)))) (append (list (car funcs)) (list (getlist (cdr funcs))))) (car funcs)))) (getlist data)))) (defun vector-push-resize (var vec) "Push to the end of vector." (adjust-array vec (1+ (array-dimension vec 0))) (vector-push var vec)) (defun vector-append (vec1 vec2) "Append vector to the end of another vector" (adjust-array vec1 (+ (array-dimension vec1 0) (array-dimension vec2 0))) (dotimes (n (array-dimension vec2 0)) (vector-push (aref vec2 n) vec1))) (defun remove-nth (index data) "Remove element from list by index." (labels ((remove-nth-tail (index data final) (if (zerop index) (if (not (cdr data)) (reverse final) (revappend final (cdr data))) (remove-nth-tail (1- index) (cdr data) (cons (car data) final))))) (remove-nth-tail index data nil))) (defun delete-nth (i seq) "Delete nth element from sequence." (let ((slide (subseq seq (1+ i))) (num (1- (fill-pointer seq)))) (replace seq slide :start1 i) (adjust-array seq num :fill-pointer num))) (defun load-quicklisp () "Initialize quicklisp." #-quicklisp (let ((quicklisp-init (merge-pathnames "quicklisp/setup.lisp" (user-homedir-pathname)))) (when (probe-file quicklisp-init) (load quicklisp-init)))) (defun get-argv () "Return a list of command line arguments." (or #+CLISP *args* #+SBCL (cdr *posix-argv*) #+LISPWORKS system:*line-arguments-list* #+CMU extensions:*command-line-words* nil)) (defun replace-substring (string part replacement &key (test #'char=)) "Returns a new string in which all the occurences of the part is replaced with replacement." (with-output-to-string (out) (loop with part-length = (length part) for old-pos = 0 then (+ pos part-length) for pos = (search part string :start2 old-pos :test test) do (write-string string out :start old-pos :end (or pos (length string))) when pos do (write-string replacement out) while pos))) (defun get-cmd-output (cmd) "Returns output of shell command as a string." (let ((fstr (make-array '(0) :element-type 'character :fill-pointer 0 :adjustable t))) (with-output-to-string (s fstr) (uiop:run-program cmd :output s)) fstr)) (defun run-cmd (cmd) (uiop:run-program cmd)) (defun run-cmd-with-output (cmd) (uiop:run-program cmd :output t)) (defun join-strings (data &key (separator " ")) "Convert a list of strings into a single string." (labels ((join-strings-tail (data separator final) (if (cdr data) (join-strings-tail (cdr data) separator (concatenate 'string final (car data) separator)) (concatenate 'string final (car data))))) (join-strings-tail data separator nil))) (defun sbcl-compile-executable (func out) "Compile a function into an executable." (sb-ext:save-lisp-and-die out :executable t :toplevel func))
4,802
Common Lisp
.lisp
121
31.049587
106
0.580777
lambdanil/lispy-stuff
0
0
0
GPL-3.0
9/19/2024, 11:50:26 AM (Europe/Amsterdam)
90a606f16962ff062601bd56ce18095bd7b62386dc5fb7fc1f5242738e973a85
41,481
[ -1 ]
41,513
JuanHernandez.lisp
HernandezJuan8_K-Nearest-Neighbor/JuanHernandez.lisp
;;;;; K-NEAREST-NEIGHBOR ;;;;; Juan Hernandez jherna56 ;;;;; Project 1 ;;;;; G01234626 ;;;;; CS 480 Section 001 ;;;;; This is a very short assignment and its intent is to get your feet wet in Lisp. ;;;;; Your task is to write three functions which will enable you to test K-Nearest Neighbor: ;;;;; ;;;;; 1. DIFFERENCE. This function tells you the difference (error) between two lists. ;;;;; You will use three kinds of measurement for error: COUNT, SQUARED, and MANHATTAN. ;;;;; Though the default will be COUNT, you will probably be most familiar with SQUARED ;;;;; since it basically does what the lecture notes showed. ;;;;; ;;;;; 2. K-NEAREST-NEIGHBOR. This function will take a list of examples, and their associated ;;;;; classes, and return what class they predict for an additional unseen example, based on ;;;;; the classes of the K examples whose DIFFERENCE from the unseen example is lowest. ;;;;; ;;;;; 3. GENERALIZATION. This function will take two lists of examples, a training set and a ;;;;; testing set, and return the percentage of testing set examples which were correctly ;;;;; predicted by K-Nearest-Neighbor using the original training set examples. ;;;;; ;;;;; You must do the following: ;;;;; ;;;;; 1. Write the three functions correctly. ;;;;; 2. Test them on the two EXAMPLES below. Determine the correct values. ;;;;; 3. Modify this file into properly-commented and properly compiling lisp code, ;;;;; which has at the end of it, in comments, the answers to the two EXAMPLES questions, ;;;;; PLUS an at least 500-word report detailing how you went about implementing this code ;;;;; and what you learned along the way. ;;;;; ;;;;; You should submit this file as a single LISP file named FooBar.lisp, where Foo is your ;;;;; first name and Bar is your last name (for example, my file would be named SeanLuke.lisp). ;;;;; ;;;;; This file will be sent to your TA. We do not have instructions ;;;;; yet as to how to do this, but we will soon, stay tuned. ;;;;; ;;;;; You should verify your code on 'lisp' on mason.gmu.edu. Here's how it works. If the TAs ;;;;; cannot get your code running on their laptops, and have reduced your score because of it, ;;;;; you have the right to challenge this if you believe that the program works on mason.gmu.edu. ;;;;; If it does, you're fine. Don't develop on mason.gmu.edu, that's painful. Just verify the ;;;;; final result on it before submission. ;;;;; ;;;;; Please do not deviate from the function signatures and data format provided. Though you may ;;;;; have a more clever way of doing things (such as using arrays rather than lists) all you are ;;;;; really doing is making life far harder for the TAs to grade. Thus deviation of any kind, ;;;;; even notional improvements, will considered a CODE ERROR. (defun difference (list1 list2 &key (measure 'count)) "Returns the DIFFERENCE (or ERROR) between two lists of things, using one of three measures: 1. Measure type COUNT: the number of times an item in list1 is different from an item in list2 at the same position. The items don't have to be numbers. Example usage: (difference '(red blue bob) '(blue blue george) :measure 'count) -> 2 2. Measure type SQUARED: the sum squared difference between items in list1 and list2 Obviously, the items must be numbers of some sort. Example usage: (difference '(1 2 3) '(1 3 7) :measure 'squared) -> 17 2. Measure type MANHATTAN: the sum absolute difference (abs (- a b)) between items in list1 and list2. Obviously the items must be numbers of some sort. Example usage: (difference '(1 2 3) '(1 3 7) :measure 'manhattan) -> 5" ;;; HINTS: use equalp to test for the given type, and for equality in COUNT ;;; HINTS: ABS is absolute value ;;; HINTS: I used MAPCAR and LAMBDA to make things easy. You might look them up. ;;; HINTS: This is a place where INCF would be reasonable. ;;; HINTS: My code is about 14 (short) lines long ;;;; IMPLEMENT ME (cond ((equalp measure 'count) ; checks if its count (abs (- (length list1) (count T (mapcar (lambda (j k) (equalp j k)) list1 list2))))) ; this will return how many times an item is different by counting how many is different in a list. ((equalp measure 'squared) ; checks if its squared (reduce '+ (mapcar (lambda (j k) (* (- j k) (- j k))) list1 list2))) ; returns the sum squared difference ((equalp measure 'manhattan) ; checks if its manhatten (reduce '+ (mapcar (lambda (j k) (abs (- j k))) list1 list2))))) ;; checks for sum of abs val difference ;;; I am providing this function for you as an example (defun most-common (list) "Returns the most common item in list, breaking ties arbitrarily" (let ((reduced-elts (mapcar (lambda (elt) (list elt (count elt list))) (remove-duplicates list)))) (first (first (sort reduced-elts #'> :key #'second))))) (defun k-nearest-neighbor (examples new-example &key (k 1) (measure 'count)) "Given a LIST of EXAMPLES, each of the form (list-of-data class), and a NEW-EXAMPLE of the same form, determines the K EXAMPLES which most closely resemble the NEW-EXAMPLE, then returns the most common class among them. The MEASURE used to compute similarity can be provided. Note that the CLASS is a LIST, like (0.9), not 0.9." ;;; HINTS: use MOST-COMMON to select the most common among N classes. ;;; HINTS: you might use SORT and SUBSEQ ;;; HINTS: I used MAPCAR and LAMBDA to make things easy. You might look them up. ;;; HINTS: My code is about 11 lines long ;;;; IMPLEMENT ME (let ((sorted (sort (copy-list examples) (lambda (e f) (< (difference (elt e 0) (elt new-example 0) :measure measure) (difference (elt f 0) (elt new-example 0) :measure measure)))))) ; the above sorts the list by seeing if the difference is less than next difference and storing in a variable (let ((voters (subseq sorted 0 k))) (most-common (mapcar (lambda (e)(elt e 1)) voters))))) ; grabs 0 to k lists then grabs the most common label and returns it (defun generalization (training-examples test-examples &key (k 1) (measure 'count)) "Given a list of TRAINING EXAMPLES, each of the form (list-of-data class), and a set of TEST EXAMPLES, each of the same form, returns the percentage of TEST EXAMPLES correctly classified when passed to K-NEAREST-NEIGHBOR with the TRAINING EXAMPLES. Note that the CLASS is a LIST, like (0.9), not 0.9." ;;; HINTS: use EQUALP to compare classes ;;; HINTS: This is a place where INCF would be reasonable. ;;; HINTS: I used DOLIST ;;; HINTS: My code is about 5 lines long ;;;; IMPLEMENT ME (let ((train (mapcar (lambda (e)(k-nearest-neighbor training-examples e :k k :measure measure)) training-examples))) ;above stores in a list labels of the training example from knn (let ((test (mapcar (lambda (f) (k-nearest-neighbor training-examples f :k k :measure measure)) test-examples))) ; above stores in a list labels of test example from knn (let ((predict (mapcar (lambda (j k) (equalp j k)) train test))) ; above then gets a list to see which ones are right and which ones arent (float (/ (count T predict) (length predict))))))) ; counts the number of T in the list and then divide by ; length and return it as a float ;;;;; SOME EXAMPLES ;;;;; ;;;;; Find out what *VOTING-RECORDS-SHORT* would predict about the *NEUTRAL* congressman using 3-Nearest Neighbor ;;;;; and sum-squared error distance. ;;;;; ;;;;; (k-nearest-neighbor *voting-records-short* *neutral* :k 3 :measure 'squared) ;;;;; ;;;;; Find out how well the first 200 voting records predict the last 94 voting records using 3-Nearest Neighbor ;;;;; and sum-squared error distance. ;;;;; ;;;;; (generalization (butlast *voting-records-short* 94) (last *voting-records-short* 94) :measure 'squared :k 3) ;;;;; ;;;;; WHAT ARE THE CORRECT ANSWERS TO THESE TWO EXAMPLES? (defparameter *neutral* '((0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5) (0.1))) ;; is this the right class? (defparameter *voting-records-short* '(((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.5 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.5) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.9 0.5) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.9 0.9 0.5) (0.9)) ((0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.5) (0.9)) ((0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.5 0.1 0.9 0.9 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.9 0.9 0.1 0.9 0.5 0.9 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.9 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.1 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.9 0.1 0.9 0.5) (0.9)) ((0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.5 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.1 0.9 0.9 0.1 0.9 0.9 0.9 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.1 0.9) (0.1)) ((0.9 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.9 0.1 0.9 0.9 0.9) (0.1)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.5 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.5) (0.1)) ((0.5 0.1 0.9 0.9 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.5 0.9 0.9 0.5 0.5) (0.1)) ((0.9 0.9 0.9 0.5 0.1 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.9 0.1 0.5 0.9) (0.9)) ((0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.1) (0.9)) ((0.1 0.1 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9) (0.1)) ((0.1 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9 0.9 0.9 0.9 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9) (0.1)) ((0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.9 0.1 0.9 0.1 0.9 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.1 0.9) (0.1)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.1 0.9 0.9 0.9) (0.1)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.1 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.9 0.1 0.9 0.1 0.5 0.5 0.5 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.5 0.9 0.9 0.5 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.5 0.9 0.9 0.9 0.1 0.9 0.5 0.5 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.5 0.9) (0.9)) ((0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.5) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.5 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.5) (0.1)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.5) (0.1)) ((0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.5) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.5 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.5 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.5 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.5 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.5 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.5 0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.5 0.9 0.1 0.1 0.9 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.5 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.5 0.9 0.1 0.1) (0.9)) ((0.1 0.5 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.5 0.1) (0.1)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.5 0.1 0.1 0.5 0.5 0.5 0.9 0.1 0.5) (0.1)) ((0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.9) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.9) (0.9)) ((0.9 0.5 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.5 0.9 0.5 0.5) (0.1)) ((0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.5 0.1 0.5) (0.1)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.5 0.1 0.9 0.5) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.9 0.9 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.5 0.9 0.9 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.9 0.9 0.1 0.5 0.5 0.1 0.9 0.5 0.5 0.5 0.9 0.9) (0.9)) ((0.5 0.5 0.9 0.1 0.1 0.1 0.9 0.9 0.5 0.1 0.5 0.5 0.5 0.5 0.5 0.5) (0.9)) ((0.5 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.9) (0.9)) ((0.9 0.5 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.9 0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.9 0.5 0.9 0.9 0.1 0.9 0.1 0.9 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.5 0.9 0.9 0.9) (0.9)) ((0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9) (0.9)) ((0.1 0.9 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.5 0.1 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.5 0.9 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.5 0.9 0.9 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.5 0.9) (0.1)) ((0.9 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.5 0.1 0.9 0.1 0.9 0.9 0.9 0.5) (0.9)) ((0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.9) (0.9)) ((0.9 0.9 0.5 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.5 0.9 0.9 0.1 0.1) (0.9)) ((0.1 0.1 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.9) (0.9)) ((0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.5 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.5 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9) (0.9)) ((0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9) (0.1)) ((0.9 0.1 0.9 0.1 0.5 0.9 0.5 0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.5 0.1 0.9 0.5) (0.9)) ((0.1 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.9 0.1) (0.1)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.1 0.9) (0.9)) ((0.1 0.1 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.1 0.9 0.9 0.9 0.9 0.9 0.1) (0.9)) ((0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.5 0.9 0.1 0.1 0.9 0.9 0.1 0.5) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.9) (0.1)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.5 0.5 0.5 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.5) (0.1)) ((0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.5 0.5) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.5 0.5 0.1 0.5) (0.1)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.5 0.5 0.9 0.9) (0.9)) ((0.9 0.1 0.1 0.9 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.9 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.5 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.9 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.9) (0.1)) ((0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.9 0.1 0.5) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.5 0.9 0.9 0.1 0.5) (0.1)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.5 0.9 0.9) (0.9)) ((0.1 0.1 0.5 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.5 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.1 0.5 0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.5 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.5 0.9 0.1 0.1 0.9 0.1 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.5) (0.1)) ((0.1 0.5 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.5) (0.9)) ((0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.5) (0.9)) ((0.5 0.5 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.5 0.5 0.1 0.1 0.1 0.5 0.5) (0.9)) ((0.1 0.5 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.5) (0.1)) ((0.1 0.5 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.1 0.9) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.5 0.9 0.1 0.1 0.1 0.9 0.9 0.5) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.5 0.9 0.9 0.1 0.1) (0.1)) ((0.1 0.5 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.5 0.1 0.9) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.5 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.5 0.1 0.1 0.1 0.1 0.5 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.5 0.9 0.9 0.9 0.1 0.5 0.5 0.1 0.5 0.5 0.5) (0.9)) ((0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.5 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.1 0.9 0.1 0.1 0.9 0.9 0.1 0.1 0.5 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.9)) ((0.9 0.5 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.1 0.9 0.5 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.5 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.1 0.5) (0.9)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.5 0.5 0.5 0.5 0.1 0.9 0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.1 0.5) (0.1)) ((0.9 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.1 0.9 0.1 0.9 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.5 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.5 0.9 0.1 0.1) (0.1)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.5 0.9 0.1 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.9) (0.9)) ((0.5 0.9 0.9 0.5 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.1 0.1) (0.9)) ((0.1 0.9 0.9 0.1 0.5 0.9 0.1 0.1 0.1 0.1 0.9 0.1 0.9 0.1 0.1 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.5 0.5 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.1 0.9 0.5 0.9 0.9 0.9 0.5 0.1 0.1 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.5 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.9 0.9 0.1 0.1 0.5 0.9 0.9 0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.5 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.5 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.5 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.5 0.9 0.1 0.9) (0.1)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.1 0.9) (0.1)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.5 0.1 0.1 0.1 0.1 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.1 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.5 0.1 0.9 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.5 0.1 0.1 0.1 0.1 0.1 0.1 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.5 0.5) (0.9)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.9 0.9 0.1 0.1 0.9 0.5 0.9 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.5 0.1 0.1 0.1 0.9) (0.9)) ((0.9 0.5 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.5 0.9 0.9 0.9 0.1 0.9 0.1 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.1 0.9 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.1 0.9 0.1 0.9) (0.9)) ((0.9 0.1 0.1 0.1 0.9 0.9 0.5 0.1 0.5 0.1 0.1 0.1 0.1 0.9 0.5 0.1) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.5 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.5 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.5 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.5 0.9 0.1 0.5 0.5 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.1 0.5 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.5 0.9 0.9 0.5 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.5 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.5 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.5) (0.1)) ((0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.5 0.1 0.9 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.5 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.5 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.5 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.5 0.9) (0.9)) ((0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.5 0.9 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.5 0.1 0.9 0.9 0.9) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.5 0.1 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.9 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.9 0.1 0.9 0.1 0.1) (0.1)) ((0.1 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.9 0.1 0.9 0.5 0.9) (0.1)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.5 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.1 0.9 0.1 0.9) (0.1)) ((0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9) (0.1)) ((0.1 0.1 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.5 0.1 0.9 0.9 0.1 0.1) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1) (0.1)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9) (0.9)) ((0.9 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.1 0.5) (0.1)) ((0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.5 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.5 0.1 0.9 0.1 0.9) (0.9)) ((0.1 0.1 0.5 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.1 0.5) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.5 0.9 0.1 0.5 0.1 0.1 0.9 0.1 0.9 0.9 0.1 0.5) (0.9)) ((0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.9 0.5 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9) (0.9)) ((0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9) (0.1)) ((0.9 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.5) (0.9)) ((0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.9 0.1 0.1 0.9) (0.9)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.1 0.1) (0.1)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.1) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.5) (0.9)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.1 0.9) (0.1)) ((0.1 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.1) (0.9)) ((0.9 0.5 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.1 0.5) (0.9)) ((0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.1) (0.9)) ((0.1 0.5 0.9 0.1 0.9 0.9 0.1 0.9 0.1 0.1 0.9 0.1 0.1 0.1 0.1 0.5) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.5 0.9 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.5 0.5 0.1 0.1 0.5 0.9 0.5 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.5) (0.9)) ((0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.1) (0.9)) ((0.9 0.9 0.5 0.5 0.5 0.9 0.1 0.1 0.1 0.1 0.9 0.1 0.9 0.1 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.5 0.1 0.1 0.1 0.9 0.1 0.1 0.9 0.5 0.1 0.1 0.9 0.9) (0.9)) ((0.9 0.9 0.1 0.1 0.9 0.5 0.1 0.1 0.1 0.1 0.9 0.1 0.9 0.9 0.1 0.9) (0.9)) ((0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.9) (0.1)) ((0.9 0.1 0.9 0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.1 0.9 0.9 0.1 0.9) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1) (0.9)) ((0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1) (0.1)) ((0.9 0.1 0.9 0.1 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.9 0.9 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.1 0.1 0.9 0.9 0.1 0.9) (0.1)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.1 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.9 0.9 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.1 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.1 0.9 0.9 0.1 0.1 0.1 0.9 0.5) (0.9)) ((0.9 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.9 0.9) (0.9)) ((0.1 0.1 0.9 0.1 0.1 0.1 0.9 0.9 0.9 0.9 0.1 0.1 0.1 0.1 0.1 0.9) (0.9)))) ;;;;; Answer to question 1: (0.9) ;;;;; Answer to question 2: .5638298 ;;;;; essay ;;;;; I implemented difference by first using cond to check for what measure the function is supposed to do ;;;;; when it got count I first use mapcar and lambda to check if two items from both lists in the same position ;;;;; are the same, that'll put it into a list then I use count to count the numeber of T there are in the list ;;;;; and subtract that from the length of the list (I use list1 here since it would be the same length) ;;;;; and return that if it is count. For Squared, I use a mapcar and lambda to check two items in the same ;;;;; in the same position to to subtract it then square and put it all into a list. I then use reduce to add ;;;;; to add everything up in the list and return that as the sum squared difference. In manhatten it is almost ;;;;; similar that I use mapcar and lambda to subtract it but instead of squared I just get the absolute value ;;;;; and gets put into an array then use reduce to add up everything and return that. ;;;;; For KNN function, I first use let to create a local variable and use sort and set the list I use as ;;;;; a copy of that list. the predicate that is used to sort is seeing the difference at the current position item ;;;;; and the new-example which I am using to sort it from closest-to farthest. I then create another local ;;;;; variable and set it as voters being the subseq from 0 to K to only use that list, then I use mapcar and ;;;;; lambda to create a list that uses contains the labels of the voter and then use most-common function ;;;;; to return, the most common label. ;;;;; The generalization function starts with a local variable I called train which will contain the labels of ;;;;; all the training data by using knn and then another local variable which is called test which will ;;;;; contain all the labels of the test examples made using knn with test examples. I then create another local ;;;;; variable that will contain a list of nils and T to see if test example was correctly classified with the ;;;;; the training examples and this is done by checking if it's equal to each other to give T or nil. ;;;;; then it will take how many it got correct and divide that by the length of the test examples and return ;;;;; as a float. ;;;;; What I learned along the way is how powerful mapcar and lambda are to quickly do operations. I really liked ;;;;; using them as it removed a bunch of code that I wouldve had to use in if this was in C or java or python. ;;;;; I also learned that it can be really simple to just do something and return it and that it you dont have to ;;;;; do as much as you have into as in the other languages. Another thing I learned was that you want to do ;;;;; to do code in lisp and an ai that wont be too costly and take up too much resource or time. ;;;;; I hope that my answers are correct as It seems correct after trying the function and making sure it ;;;;; was doing what I wanted it to do first having to do pseudo code on paper to make sure ;;;;; I understand what the algorithm was going to be.
32,828
Common Lisp
.lisp
454
71.063877
115
0.553903
HernandezJuan8/K-Nearest-Neighbor
0
0
0
GPL-3.0
9/19/2024, 11:50:26 AM (Europe/Amsterdam)
8cab367ea4aa14d4c6edf0cebfed7d5901ba57d4750d7e32baec9aa25f71b314
41,513
[ -1 ]
41,530
juan-hernandez.lisp
HernandezJuan8_Game-Playing-Agent-/juan-hernandez.lisp
;; ASSIGNMENT 4: A MANCALA PLAYER ;; DUE: MONDAY, MAY 2, at MIDNIGHT ;; Juan Hernandez jherna56 G01234626 ;; Report at end of the file ;; :P ;;;; Here is a description of the stuff that would go into your ;;;; file. ;;;; The first thing in your function is a package declaration. ;;;; You should name your package something beginning with a colon ;;;; followed by your full name with hyphens for spaces. ;;;; I named my package :sean-luke . Keep in mind that the name ;;;; is CASE-INSENSITIVE. The only symbol you should export is the ;;;; symbol COMPUTER-MAKE-MOVE, which should be the name of your top- ;;;; level computer move function. Name your file the same ;;;; name as your package declaration, minus the colon. For example, ;;;; my file is named "sean-luke.lisp" (defpackage :juan-hernandez (:use :common-lisp-user :common-lisp) (:export computer-make-move)) (in-package :juan-hernandez) ;;;; Once you've done this, you need to write your code. Here ;;;; is a rough sketch of three functions you will find handy. ;;;; You don't need to implement them like this, except for the ;;;; COMPUTER-MAKE-MOVE function. You can write your code in ;;;; any fashion you like in this file, so long as you do a ;;;; proper alpha-beta heuristic search and your evaluation ;;;; function is stronger than just comparing the differences in ;;;; the mancalas. (defun alpha-beta (state current-depth max-depth max-player expand terminal evaluate alpha beta) "Does alpha-beta search. Note that there is the addition of a variable called MAX-PLAYER rather than a function which specifies if it's max's turn. It's just more convenient in this system. The MAX-PLAYER variable is set to either *player-1* or to *player-2* and indicates if *player-1* or *player-2* should be considered 'max' (the other player is then considered to be 'min')" (if (or (funcall terminal state) (>= current-depth max-depth)) ;; check if we are in max depth or we are terminal (funcall evaluate state max-player) ;; if so then call evulate and return what was returned (dolist (i (funcall expand state) (if (equalp max-player (state-turn state)) alpha beta)) ;; next moves, if max turn then return alpha otherwise return beta (let ((rec (alpha-beta i (+ current-depth 1) max-depth max-player expand terminal evaluate alpha beta))) ;;some recursive fun to get best state (if (equalp max-player (state-turn state)) ;; this if will set the value for either alpha or beta depending on the player (setf alpha (max alpha rec)) ;; alpha set here (setf beta (min beta rec)))) ;; beta set here (if (>= alpha beta) ;; if alpha crossed over to beta (return-from alpha-beta (if (equalp max-player (state-turn state)) beta alpha)))))) ;; then return depending on player (defun evaluate (state max-player) "Evaluates the game situation for MAX-PLAYER. Returns the value of STATE for MAX-PLAYER (who is either *player-1* or *player-2*). This should be a value ranging from *min-wins* to *max-wins*." (let ((n (* 2 *num-pits* *initial-stones-per-pit*)) i j m ret) ;; n is number of stones and some cool variables (setf i (let ((i (left-pit max-player))) (reduce '+ (subseq (state-board state) i (+ 1 i *num-pits*))))) ;; these 2 lines here are similar they grab the sum of the pits the player owns the first one is for max-player (setf j (let ((i (left-pit (other-player max-player)))) (reduce '+ (subseq (state-board state) i (+ 1 i *num-pits*))))) ;; this one is for the other player (setf ret (+ *min-wins* (/ (* (- (- i j) (- n)) (- *max-wins* *min-wins*)) (- n (- n))))) ;; this is the main heustric evaluation for the max-player ret)) (defun computer-make-move (state max-depth) "Given a state, makes a move and returns the new state. If there is no move to make (end of game) returns nil. Each time this function calls the top-level alpha-beta function to search for the quality of a state, computer-make-move should print out the state (using PRINT, not PRINT-STATE) that is being searched. Only search up to max-depth. The computer should assume that he is the player who's turn it is right now in STATE" (let (b (bs *min-wins*)) ;; bs == score (dolist (i (moves state)) (let ((s (alpha-beta (print i) 0 max-depth (state-turn state) 'moves 'game-overp 'evaluate *min-wins* *max-wins*))) ;; this calls alpha beta and prints out state (if (> s bs) (progn (setf b i) (setf bs s))))) ;; saves down b and bs b)) ;; return b ;;;; In comments your file, you put your project notes. ;;;; The last thing in your file should be this line (uncommented ;;;; of course). (in-package :cl-user) #| Report for Project I made the alpha beta function by following algorithm 29 on the lecture notes about min-max with alpha beta pruning. It follows closely to that algorithm so it should work as intended. for evaulate function I made a heurstic evaluation of a given state. This is done by grabbing how sum of the pits the player owns and then doing it for the other player. Then I return the a hueristiv evaluation that uses both of these using a formula for mancala. In computer make move function I keep track of the best state and best score , for every state in the list I do the alpha beta function where if the current score is better than the current best score then ill set the new best and best score with what the curren one is. I return the best state here. The only issue with the code is if there is invalid moves for human player for every move then it will just grid lock with no fix . Another issue I could not overcome was sometimes the computer didnt do a move that it couldve done meaning it could lose easily if it is picked up that a move wont occur even though its an obvious mvoe to make. Overall This project was good and I learned a good deal between states and moving between them. I feel Like I did better here than I did with p3. I lost against the computer but I had a friend play against it and he won so it is definitely beat able if player is good. |#
6,165
Common Lisp
.lisp
93
62.83871
168
0.719609
HernandezJuan8/Game-Playing-Agent-
0
0
0
GPL-3.0
9/19/2024, 11:50:26 AM (Europe/Amsterdam)
44e5560a6f4018b05f13c07ac119ab61488c12029101f6df046715ee8b395fd7
41,530
[ -1 ]
41,547
rps.lisp
thefossenjoyer_lisp-projects/rps.lisp
(defpackage #:rps (:use :cl)) (in-package #:rps) (defun get-user () "Gets user's choice." (format t "Enter your choice (r, p, s): ") (let ((user-choice (read-line))) (cond ((string= user-choice "r") (return-from get-user "rock")) ((string= user-choice "p") (return-from get-user "paper")) ((string= user-choice "s") (return-from get-user "scissors")) ) ) ) (defun get-pc () "Generates pc's choice from a list" (let ((choices-list '("rock" "paper" "scissors"))) (let ((random-choice (nth (random (length choices-list)) choices-list) )) (return-from get-pc random-choice) ) ) ) (defun game-logic (user-choice pc-choice) "Main logic of the RPS game." (cond ((and (string= user-choice "rock") (string= pc-choice "scissors")) (format t "User wins!")) ((and (string= user-choice "scissors") (string= pc-choice "paper")) (format t "User wins!")) ((and (string= user-choice "paper") (string= pc-choice "rock")) (format t "User wins!")) ((and (string= pc-choice "paper") (string= user-choice "rock")) (format t "PC wins!")) ((and (string= pc-choice "rock") (string= user-choice "scissors")) (format t "PC wins!")) ((and (string= pc-choice "scissors") (string= user-choice "paper")) (format t "PC wins!")) ((string= user-choice pc-choice) (format t "tie!~&")) ) ) (defun main () "Main fun." (let ((user-choice (get-user)) (pc-choice (get-pc))) ;;(format t "pc = ~a~&" pc-choice) (game-logic user-choice pc-choice) ) )
1,540
Common Lisp
.lisp
40
34.2
96
0.613099
thefossenjoyer/lisp-projects
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
ba84f94d3b2ecc83a0b81b2fb04d57221052eea19da923eb3e29ae101fed62fa
41,547
[ -1 ]
41,548
guess_game.lisp
thefossenjoyer_lisp-projects/guess_game.lisp
(defvar secret_word "emacs") (defvar lives 3) (defun game_loop () "Running the game." (print "Enter your guess: ") (defvar user_guess) (setf user_guess (make-array '(0) :element-type 'base-char :fill-pointer 0 :adjustable t)) ;; "reseting" user_guess (setf user_guess (read)) (cond ((= 0 lives) (print "Eh.. game over..")) ((string-equal user_guess secret_word) (print "Nice! You won!")) ((not (string-equal user_guess secret_word)) (print "Try again.") (setf lives (- lives 1)) (game_loop)) ) ) (game_loop)
548
Common Lisp
.lisp
15
32.866667
117
0.652591
thefossenjoyer/lisp-projects
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
412dc09a7916f514784d4d73420c56ae1acb48a19a523a65b74b268be6474c98
41,548
[ -1 ]
41,549
guess_game_two.lisp
thefossenjoyer_lisp-projects/guess_game_two.lisp
(defvar word "tux") (defvar lives 3) (defvar points 0) (defun game_loop () "Idk, game loop?" (defvar user_guess) (format t "You have 3 lives. Be careful. Also, you need to score 3 points by guessing the correct letters. ~&") (format t "Lives: ~a ~&" lives) (format t "Points: ~a ~&" points) (print "Guess: ") (setf user_guess (make-array '(0) :element-type 'base-char :adjustable t)) ;; clearing user_guess (flushing stdin) (setf user_guess (read-line)) ;; taking user_input (cond ((= 0 lives) (print "Eh.. game over..")) ((= 3 points) (print "YAY! YOU WON!")) ((search user_guess word) (print "Guessed one letter.") (setf points (+ 1 points)) (game_loop)) ((not(search user_guess word)) (print "Try again.") (setf lives (- lives 1)) (game_loop)) ) ) (game_loop)
814
Common Lisp
.lisp
19
39.157895
116
0.64359
thefossenjoyer/lisp-projects
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
5e2a00ac20b2d6aec4e66e006ca6c36b996fa85d27c3634a230bd52d372eefce
41,549
[ -1 ]
41,569
sample.rat.out.short
tom4244_Compiler_in_Common_Lisp/sample.rat.out.short
Z -> $$ $$ LP M $$ LP -> L L -> D ; LP D -> Q I Q -> int I -> ID IP IP -> , I I -> ID IP IP -> , I I -> ID IP IP -> , I I -> ID IP IP -> , I I -> ID IP IP -> , I I -> ID IP IP -> , I I -> ID IP IP -> & LP -> L L -> D ; LP D -> Q I Q -> boolean I -> ID IP IP -> & LP -> & M -> S MP S -> V V -> if ( C ) S VP C -> E R E E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> & R -> = E -> T EP T -> F TP F -> P P -> IN TP -> & EP -> & S -> A A -> ID := E ; E -> T EP T -> F TP F -> P P -> false TP -> & EP -> & VP -> endif MP -> M M -> S MP S -> V V -> if ( C ) S VP C -> E R E E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> & R -> < E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> & S -> A A -> ID := E ; E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> & VP -> endif MP -> M M -> S MP S -> A A -> ID := E ; E -> T EP T -> F TP F -> P P -> IN TP -> & EP -> & MP -> M M -> S MP S -> A A -> ID := E ; E -> T EP T -> F TP F -> P P -> IN TP -> & EP -> & MP -> M M -> S MP S -> A A -> ID := E ; E -> T EP T -> F TP F -> P P -> IN TP -> * F TP F -> P P -> ( E ) E -> T EP T -> F TP F -> P P -> ( E ) E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> - T EP T -> F TP F -> P P -> IN TP -> & EP -> & TP -> & EP -> - T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> & TP -> & EP -> & MP -> M M -> S MP S -> A A -> ID := E ; E -> T EP T -> F TP F -> P P -> ( E ) E -> T EP T -> F TP F -> P P -> IN TP -> * F TP F -> P P -> IN TP -> & EP -> & TP -> * F TP F -> P P -> ( E ) E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> + T EP T -> F TP F -> P P -> ( E ) E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> * F TP F -> P P -> IN TP -> & EP -> & TP -> & EP -> - T EP T -> F TP F -> P P -> ID PP PP -> & TP -> * F TP F -> P P -> IN TP -> & EP -> & TP -> & EP -> & MP -> M M -> S MP S -> A A -> ID := E ; E -> T EP T -> F TP F -> P P -> true TP -> & EP -> & MP -> M M -> S MP S -> H H -> read ( I ) ; I -> ID IP IP -> , I I -> ID IP IP -> & MP -> M M -> S MP S -> W W -> while ( C ) S JMP C -> E R E E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> & R -> < E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> & S -> Y Y -> { M } M -> S MP S -> A A -> ID := E ; E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> + T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> & MP -> M M -> S MP S -> A A -> ID := E ; E -> T EP T -> F TP F -> - P P -> ID PP PP -> & TP -> & EP -> + T EP T -> F TP F -> P P -> IN TP -> & EP -> & MP -> & MP -> M M -> S MP S -> G G -> write ( E ) ; E -> T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> + T EP T -> F TP F -> P P -> ID PP PP -> & TP -> & EP -> & MP -> & Source file parsing finished with no errors. Assembly Code Listing 1 PUSHM 1000 2 PUSHI 3 3 EQU 4 JUMPZ 7 5 PUSHI 0 6 POPM 1007 7 PUSHM 1000 8 PUSHM 1001 9 LES 10 JUMPZ 13 11 PUSHM 1002 12 POPM 1000 13 PUSHI 3 14 POPM 1005 15 PUSHI 0 16 POPM 1006 17 PUSHI 1 18 PUSHM 1005 19 PUSHI 2 20 SUB 21 PUSHM 1006 22 SUB 23 MUL 24 POPM 1003 25 PUSHI 1 26 PUSHI 3 27 MUL 28 PUSHM 1006 29 PUSHM 1006 30 PUSHI 3 31 MUL 32 ADD 33 PUSHM 1003 34 PUSHI 2 35 MUL 36 SUB 37 MUL 38 POPM 1004 39 PUSHI 1 40 POPM 1007 41 PUSHSTD 42 POPM 1005 43 PUSHSTD 44 POPM 1007 45 LABEL 46 PUSHM 1003 47 PUSHM 1006 48 LES 49 JUMPZ 61 50 PUSHM 1006 51 PUSHM 1003 52 ADD 53 POPM 1006 54 PUSHI -1 55 PUSHM 1003 56 MUL 57 PUSHI 1 58 ADD 59 POPM 1003 60 JUMP 45 61 PUSHM 1006 62 PUSHM 1005 63 ADD 64 POPSTD Symbol Table a 1000 int b 1001 int c 1002 int i 1003 int j 1004 int max 1005 int sum 1006 int signal 1007 boolean
3,881
Common Lisp
.l
359
8.935933
44
0.451879
tom4244/Compiler_in_Common_Lisp
0
0
0
AGPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
abe1d8e27ba80bef27988e07cfa3dbad87f050b14bf0a839c740de54346b5b37
41,569
[ -1 ]
41,570
sample.rat.out.debug
tom4244_Compiler_in_Common_Lisp/sample.rat.out.debug
Lexeme: $$ Z -> $$ $$ LP M $$ Lexeme: $$ Lexeme: int LP -> L L -> D ; LP D -> Q I Q -> int Lexeme: a I -> ID IP a 1000 int Lexeme: , IP -> , I Lexeme: b I -> ID IP b 1001 int Lexeme: , IP -> , I Lexeme: c I -> ID IP c 1002 int Lexeme: , IP -> , I Lexeme: i I -> ID IP i 1003 int Lexeme: , IP -> , I Lexeme: j I -> ID IP j 1004 int Lexeme: , IP -> , I Lexeme: max I -> ID IP max 1005 int Lexeme: , IP -> , I Lexeme: sum I -> ID IP sum 1006 int Lexeme: ; IP -> & op-stk -> NIL Lexeme: boolean LP -> L L -> D ; LP D -> Q I Q -> boolean Lexeme: signal I -> ID IP signal 1007 boolean Lexeme: ; IP -> & op-stk -> NIL Lexeme: if LP -> & M -> S MP S -> V V -> if ( C ) S VP Lexeme: ( Lexeme: a C -> E R E E -> T EP T -> F TP F -> P P -> ID PP 1 PUSHM 1000 (P TP EP R E ) S VP MP $$ @) NIL Lexeme: = PP -> & TP -> & EP -> & R -> = EQU -> op-stack Lexeme: 3 E -> T EP T -> F TP F -> P P -> IN 2 PUSHI 3 (P TP EP ) S VP MP $$ @) (EQU) Lexeme: ) TP -> & op-stk -> EQU 3 EQU (TP EP ) S VP MP $$ @) NIL op-stk -> NIL 4 JUMPZ -998 (TP EP ) S VP MP $$ @) NIL EP -> & Lexeme: signal S -> A A -> ID := E ; 1007 -> op-stack POPM -> op-stack Lexeme: := Lexeme: false E -> T EP T -> F TP F -> P P -> false 5 PUSHI 0 (P TP EP ; VP MP $$ @) (POPM 1007) Lexeme: ; TP -> & EP -> & op-stk -> POPM 6 POPM 1007 (; VP MP $$ @) NIL op-stk -> NIL Lexeme: endif VP -> endif Lexeme: if MP -> M M -> S MP S -> V V -> if ( C ) S VP Lexeme: ( Lexeme: a C -> E R E E -> T EP T -> F TP F -> P P -> ID PP 7 PUSHM 1000 (P TP EP R E ) S VP MP $$ @) NIL Lexeme: < PP -> & TP -> & EP -> & R -> < LES -> op-stack Lexeme: b E -> T EP T -> F TP F -> P P -> ID PP 8 PUSHM 1001 (P TP EP ) S VP MP $$ @) (LES) Lexeme: ) PP -> & TP -> & op-stk -> LES 9 LES (TP EP ) S VP MP $$ @) NIL op-stk -> NIL 10 JUMPZ -998 (TP EP ) S VP MP $$ @) NIL EP -> & Lexeme: a S -> A A -> ID := E ; 1000 -> op-stack POPM -> op-stack Lexeme: := Lexeme: c E -> T EP T -> F TP F -> P P -> ID PP 11 PUSHM 1002 (P TP EP ; VP MP $$ @) (POPM 1000) Lexeme: ; PP -> & TP -> & EP -> & op-stk -> POPM 12 POPM 1000 (; VP MP $$ @) NIL op-stk -> NIL Lexeme: endif VP -> endif Lexeme: max MP -> M M -> S MP S -> A A -> ID := E ; 1005 -> op-stack POPM -> op-stack Lexeme: := Lexeme: 3 E -> T EP T -> F TP F -> P P -> IN 13 PUSHI 3 (P TP EP ; MP $$ @) (POPM 1005) Lexeme: ; TP -> & EP -> & op-stk -> POPM 14 POPM 1005 (; MP $$ @) NIL op-stk -> NIL Lexeme: sum MP -> M M -> S MP S -> A A -> ID := E ; 1006 -> op-stack POPM -> op-stack Lexeme: := Lexeme: 0 E -> T EP T -> F TP F -> P P -> IN 15 PUSHI 0 (P TP EP ; MP $$ @) (POPM 1006) Lexeme: ; TP -> & EP -> & op-stk -> POPM 16 POPM 1006 (; MP $$ @) NIL op-stk -> NIL Lexeme: i MP -> M M -> S MP S -> A A -> ID := E ; 1003 -> op-stack POPM -> op-stack Lexeme: := Lexeme: 1 E -> T EP T -> F TP F -> P P -> IN 17 PUSHI 1 (P TP EP ; MP $$ @) (POPM 1003) Lexeme: * TP -> * F TP Lexeme: ( F -> P P -> ( E ) Lexeme: ( E -> T EP T -> F TP F -> P P -> ( E ) Lexeme: max E -> T EP T -> F TP F -> P P -> ID PP 18 PUSHM 1005 (P TP EP ) TP EP ) TP EP ; MP $$ @) (( ( * POPM 1003 NIL) Lexeme: - PP -> & TP -> & EP -> - T EP Lexeme: 2 T -> F TP F -> P P -> IN 19 PUSHI 2 (P TP EP ) TP EP ) TP EP ; MP $$ @) (- ( ( * POPM 1003 NIL) Lexeme: ) TP -> & op-stk -> - 20 SUB (TP EP ) TP EP ) TP EP ; MP $$ @) (( ( * POPM 1003 NIL) op-stk -> ( EP -> & Lexeme: - TP -> & EP -> - T EP Lexeme: sum T -> F TP F -> P P -> ID PP 21 PUSHM 1006 (P TP EP ) TP EP ; MP $$ @) (- ( * POPM 1003 NIL) Lexeme: ) PP -> & TP -> & op-stk -> - 22 SUB (TP EP ) TP EP ; MP $$ @) (( * POPM 1003 NIL) op-stk -> ( EP -> & Lexeme: ; TP -> & EP -> & op-stk -> * 23 MUL (; MP $$ @) (POPM 1003 NIL) op-stk -> POPM 24 POPM 1003 (; MP $$ @) (NIL) op-stk -> NIL Lexeme: j MP -> M M -> S MP S -> A A -> ID := E ; 1004 -> op-stack POPM -> op-stack Lexeme: := Lexeme: ( E -> T EP T -> F TP F -> P P -> ( E ) Lexeme: 1 E -> T EP T -> F TP F -> P P -> IN 25 PUSHI 1 (P TP EP ) TP EP ; MP $$ @) (( POPM 1004) Lexeme: * TP -> * F TP Lexeme: 3 F -> P P -> IN 26 PUSHI 3 (P TP EP ) TP EP ; MP $$ @) (* ( POPM 1004) Lexeme: ) TP -> & op-stk -> * 27 MUL (TP EP ) TP EP ; MP $$ @) (( POPM 1004) op-stk -> ( EP -> & Lexeme: * TP -> * F TP Lexeme: ( F -> P P -> ( E ) Lexeme: sum E -> T EP T -> F TP F -> P P -> ID PP 28 PUSHM 1006 (P TP EP ) TP EP ; MP $$ @) (( * POPM 1004 NIL) Lexeme: + PP -> & TP -> & EP -> + T EP Lexeme: ( T -> F TP F -> P P -> ( E ) Lexeme: sum E -> T EP T -> F TP F -> P P -> ID PP 29 PUSHM 1006 (P TP EP ) TP EP ) TP EP ; MP $$ @) (( + ( * POPM 1004 NIL) Lexeme: * PP -> & TP -> * F TP Lexeme: 3 F -> P P -> IN 30 PUSHI 3 (P TP EP ) TP EP ) TP EP ; MP $$ @) (* ( + ( * POPM 1004 NIL) Lexeme: ) TP -> & op-stk -> * 31 MUL (TP EP ) TP EP ) TP EP ; MP $$ @) (( + ( * POPM 1004 NIL) op-stk -> ( EP -> & Lexeme: - TP -> & EP -> - T EP 32 ADD (EP ) TP EP ; MP $$ @) (( * POPM 1004 NIL) Lexeme: i T -> F TP F -> P P -> ID PP 33 PUSHM 1003 (P TP EP ) TP EP ; MP $$ @) (- ( * POPM 1004 NIL) Lexeme: * PP -> & TP -> * F TP Lexeme: 2 F -> P P -> IN 34 PUSHI 2 (P TP EP ) TP EP ; MP $$ @) (* - ( * POPM 1004 NIL) Lexeme: ) TP -> & op-stk -> * 35 MUL (TP EP ) TP EP ; MP $$ @) (- ( * POPM 1004 NIL) op-stk -> - 36 SUB (TP EP ) TP EP ; MP $$ @) (( * POPM 1004 NIL) op-stk -> ( EP -> & Lexeme: ; TP -> & EP -> & op-stk -> * 37 MUL (; MP $$ @) (POPM 1004 NIL) op-stk -> POPM 38 POPM 1004 (; MP $$ @) (NIL) op-stk -> NIL Lexeme: signal MP -> M M -> S MP S -> A A -> ID := E ; 1007 -> op-stack POPM -> op-stack Lexeme: := Lexeme: true E -> T EP T -> F TP F -> P P -> true 39 PUSHI 1 (P TP EP ; MP $$ @) (POPM 1007) Lexeme: ; TP -> & EP -> & op-stk -> POPM 40 POPM 1007 (; MP $$ @) NIL op-stk -> NIL Lexeme: read MP -> M M -> S MP S -> H H -> read ( I ) ; Lexeme: ( Lexeme: max I -> ID IP 41 PUSHSTD (I ) ; MP $$ @) NIL 42 POPM 1005 (I ) ; MP $$ @) NIL Lexeme: , IP -> , I Lexeme: signal I -> ID IP 43 PUSHSTD (I ) ; MP $$ @) NIL 44 POPM 1007 (I ) ; MP $$ @) NIL Lexeme: ) IP -> & Lexeme: ; op-stk -> NIL Lexeme: while MP -> M M -> S MP S -> W W -> while ( C ) S JMP 45 LABEL -997 (W MP $$ @) NIL Lexeme: ( Lexeme: i C -> E R E E -> T EP T -> F TP F -> P P -> ID PP 46 PUSHM 1003 (P TP EP R E ) S JMP MP $$ @) NIL Lexeme: < PP -> & TP -> & EP -> & R -> < LES -> op-stack Lexeme: sum E -> T EP T -> F TP F -> P P -> ID PP 47 PUSHM 1006 (P TP EP ) S JMP MP $$ @) (LES) Lexeme: ) PP -> & TP -> & op-stk -> LES 48 LES (TP EP ) S JMP MP $$ @) NIL op-stk -> NIL 49 JUMPZ -998 (TP EP ) S JMP MP $$ @) NIL EP -> & Lexeme: { S -> Y Y -> { M } Lexeme: sum M -> S MP S -> A A -> ID := E ; 1006 -> op-stack POPM -> op-stack Lexeme: := Lexeme: sum E -> T EP T -> F TP F -> P P -> ID PP 50 PUSHM 1006 (P TP EP ; MP } JMP MP $$ @) (POPM 1006) Lexeme: + PP -> & TP -> & EP -> + T EP Lexeme: i T -> F TP F -> P P -> ID PP 51 PUSHM 1003 (P TP EP ; MP } JMP MP $$ @) (+ POPM 1006 NIL) Lexeme: ; PP -> & TP -> & EP -> & op-stk -> + 52 ADD (; MP } JMP MP $$ @) (POPM 1006 NIL) op-stk -> POPM 53 POPM 1006 (; MP } JMP MP $$ @) (NIL) op-stk -> NIL Lexeme: i MP -> M M -> S MP S -> A A -> ID := E ; 1003 -> op-stack POPM -> op-stack Lexeme: := Lexeme: - E -> T EP T -> F TP F -> - P 54 PUSHI -1 (F TP EP ; MP } JMP MP $$ @) (POPM 1003) Lexeme: i P -> ID PP 55 PUSHM 1003 (P TP EP ; MP } JMP MP $$ @) (POPM 1003) 56 MUL (P TP EP ; MP } JMP MP $$ @) (POPM 1003) Lexeme: + PP -> & TP -> & EP -> + T EP Lexeme: 1 T -> F TP F -> P P -> IN 57 PUSHI 1 (P TP EP ; MP } JMP MP $$ @) (+ POPM 1003 NIL) Lexeme: ; TP -> & EP -> & op-stk -> + 58 ADD (; MP } JMP MP $$ @) (POPM 1003 NIL) op-stk -> POPM 59 POPM 1003 (; MP } JMP MP $$ @) (NIL) op-stk -> NIL Lexeme: } MP -> & Lexeme: write 60 JUMP 45 (JMP MP $$ @) NIL MP -> M M -> S MP S -> G G -> write ( E ) ; Lexeme: ( Lexeme: sum E -> T EP T -> F TP F -> P P -> ID PP 61 PUSHM 1006 (P TP EP ) ; MP $$ @) NIL Lexeme: + PP -> & TP -> & EP -> + T EP Lexeme: max T -> F TP F -> P P -> ID PP 62 PUSHM 1005 (P TP EP ) ; MP $$ @) (+) Lexeme: ) PP -> & TP -> & op-stk -> + 63 ADD (TP EP ) ; MP $$ @) NIL op-stk -> NIL EP -> & Lexeme: ; op-stk -> NIL 64 POPSTD (; MP $$ @) NIL Lexeme: $$ MP -> & Source file parsing finished with no errors. Assembly Code Listing 1 PUSHM 1000 2 PUSHI 3 3 EQU 4 JUMPZ 7 5 PUSHI 0 6 POPM 1007 7 PUSHM 1000 8 PUSHM 1001 9 LES 10 JUMPZ 13 11 PUSHM 1002 12 POPM 1000 13 PUSHI 3 14 POPM 1005 15 PUSHI 0 16 POPM 1006 17 PUSHI 1 18 PUSHM 1005 19 PUSHI 2 20 SUB 21 PUSHM 1006 22 SUB 23 MUL 24 POPM 1003 25 PUSHI 1 26 PUSHI 3 27 MUL 28 PUSHM 1006 29 PUSHM 1006 30 PUSHI 3 31 MUL 32 ADD 33 PUSHM 1003 34 PUSHI 2 35 MUL 36 SUB 37 MUL 38 POPM 1004 39 PUSHI 1 40 POPM 1007 41 PUSHSTD 42 POPM 1005 43 PUSHSTD 44 POPM 1007 45 LABEL 46 PUSHM 1003 47 PUSHM 1006 48 LES 49 JUMPZ 61 50 PUSHM 1006 51 PUSHM 1003 52 ADD 53 POPM 1006 54 PUSHI -1 55 PUSHM 1003 56 MUL 57 PUSHI 1 58 ADD 59 POPM 1003 60 JUMP 45 61 PUSHM 1006 62 PUSHM 1005 63 ADD 64 POPSTD Symbol Table a 1000 int b 1001 int c 1002 int i 1003 int j 1004 int max 1005 int sum 1006 int signal 1007 boolean
9,617
Common Lisp
.l
751
11.166445
44
0.518744
tom4244/Compiler_in_Common_Lisp
0
0
0
AGPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
205e123cf6ecc601af33cd891d4111d4de2393c765dde8b31f059cb748a4a0a2
41,570
[ -1 ]
41,571
sample.rat.out
tom4244_Compiler_in_Common_Lisp/sample.rat.out
Source file parsing finished with no errors. Assembly Code Listing 1 PUSHM 1000 2 PUSHI 3 3 EQU 4 JUMPZ 7 5 PUSHI 0 6 POPM 1007 7 PUSHM 1000 8 PUSHM 1001 9 LES 10 JUMPZ 13 11 PUSHM 1002 12 POPM 1000 13 PUSHI 3 14 POPM 1005 15 PUSHI 0 16 POPM 1006 17 PUSHI 1 18 PUSHM 1005 19 PUSHI 2 20 SUB 21 PUSHM 1006 22 SUB 23 MUL 24 POPM 1003 25 PUSHI 1 26 PUSHI 3 27 MUL 28 PUSHM 1006 29 PUSHM 1006 30 PUSHI 3 31 MUL 32 ADD 33 PUSHM 1003 34 PUSHI 2 35 MUL 36 SUB 37 MUL 38 POPM 1004 39 PUSHI 1 40 POPM 1007 41 PUSHSTD 42 POPM 1005 43 PUSHSTD 44 POPM 1007 45 LABEL 46 PUSHM 1003 47 PUSHM 1006 48 LES 49 JUMPZ 61 50 PUSHM 1006 51 PUSHM 1003 52 ADD 53 POPM 1006 54 PUSHI -1 55 PUSHM 1003 56 MUL 57 PUSHI 1 58 ADD 59 POPM 1003 60 JUMP 45 61 PUSHM 1006 62 PUSHM 1005 63 ADD 64 POPSTD Symbol Table a 1000 int b 1001 int c 1002 int i 1003 int j 1004 int max 1005 int sum 1006 int signal 1007 boolean
912
Common Lisp
.l
75
10.76
44
0.812576
tom4244/Compiler_in_Common_Lisp
0
0
0
AGPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
f239c9b1993f4abe6093517ff72c4b780b3351f07e9514d6cd7e240ea586febc
41,571
[ -1 ]
41,572
sample.rat.out.long
tom4244_Compiler_in_Common_Lisp/sample.rat.out.long
Token: Separator Lexeme: $$ <Rat10> -> $$ $$ <Opt Declaration List> <Statement List> $$ Token: Separator Lexeme: $$ Token: Keyword Lexeme: int <Opt Declaration List> -> <Declaration List> <Declaration List> -> <Declaration> ; <Opt Declaration List> <Declaration> -> <Qualifier> <IDs> <Qualifier> -> int Token: Identifier Lexeme: a <IDs> -> <Identifier> <IDs Prime> Token: Separator Lexeme: , <IDs Prime> -> , <IDs> Token: Identifier Lexeme: b <IDs> -> <Identifier> <IDs Prime> Token: Separator Lexeme: , <IDs Prime> -> , <IDs> Token: Identifier Lexeme: c <IDs> -> <Identifier> <IDs Prime> Token: Separator Lexeme: , <IDs Prime> -> , <IDs> Token: Identifier Lexeme: i <IDs> -> <Identifier> <IDs Prime> Token: Separator Lexeme: , <IDs Prime> -> , <IDs> Token: Identifier Lexeme: j <IDs> -> <Identifier> <IDs Prime> Token: Separator Lexeme: , <IDs Prime> -> , <IDs> Token: Identifier Lexeme: max <IDs> -> <Identifier> <IDs Prime> Token: Separator Lexeme: , <IDs Prime> -> , <IDs> Token: Identifier Lexeme: sum <IDs> -> <Identifier> <IDs Prime> Token: Separator Lexeme: ; <IDs Prime> -> <Empty> Token: Keyword Lexeme: boolean <Opt Declaration List> -> <Declaration List> <Declaration List> -> <Declaration> ; <Opt Declaration List> <Declaration> -> <Qualifier> <IDs> <Qualifier> -> boolean Token: Identifier Lexeme: signal <IDs> -> <Identifier> <IDs Prime> Token: Separator Lexeme: ; <IDs Prime> -> <Empty> Token: Keyword Lexeme: if <Opt Declaration List> -> <Empty> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <If> <If> -> if ( <Condition> ) <Statement> VP Token: Separator Lexeme: ( Token: Identifier Lexeme: a <Condition> -> <Expression> <Relop> <Expression> <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Operator Lexeme: = <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> <Empty> <Relop> -> = Token: Integer Lexeme: 3 <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Integer> Token: Separator Lexeme: ) <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Identifier Lexeme: signal <Statement> -> <Assign> <Assign> -> <Identifier> := <Expression> ; Token: Separator Lexeme: := Token: Keyword Lexeme: false <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> false Token: Separator Lexeme: ; <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Keyword Lexeme: endif NIL -> endif Token: Keyword Lexeme: if <Statement List Prime> -> <Statement List> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <If> <If> -> if ( <Condition> ) <Statement> VP Token: Separator Lexeme: ( Token: Identifier Lexeme: a <Condition> -> <Expression> <Relop> <Expression> <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Operator Lexeme: < <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> <Empty> <Relop> -> < Token: Identifier Lexeme: b <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Separator Lexeme: ) <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Identifier Lexeme: a <Statement> -> <Assign> <Assign> -> <Identifier> := <Expression> ; Token: Separator Lexeme: := Token: Identifier Lexeme: c <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Separator Lexeme: ; <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Keyword Lexeme: endif NIL -> endif Token: Identifier Lexeme: max <Statement List Prime> -> <Statement List> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <Assign> <Assign> -> <Identifier> := <Expression> ; Token: Separator Lexeme: := Token: Integer Lexeme: 3 <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Integer> Token: Separator Lexeme: ; <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Identifier Lexeme: sum <Statement List Prime> -> <Statement List> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <Assign> <Assign> -> <Identifier> := <Expression> ; Token: Separator Lexeme: := Token: Integer Lexeme: 0 <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Integer> Token: Separator Lexeme: ; <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Identifier Lexeme: i <Statement List Prime> -> <Statement List> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <Assign> <Assign> -> <Identifier> := <Expression> ; Token: Separator Lexeme: := Token: Integer Lexeme: 1 <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Integer> Token: Operator Lexeme: * <Term Prime> -> * <Factor> <Term Prime> Token: Separator Lexeme: ( <Factor> -> <Primary> <Primary> -> ( <Expression> ) Token: Separator Lexeme: ( <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> ( <Expression> ) Token: Identifier Lexeme: max <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Operator Lexeme: - <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> - <Term> <Expression Prime> Token: Integer Lexeme: 2 <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Integer> Token: Separator Lexeme: ) <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Operator Lexeme: - <Term Prime> -> <Empty> <Expression Prime> -> - <Term> <Expression Prime> Token: Identifier Lexeme: sum <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Separator Lexeme: ) <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Separator Lexeme: ; <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Identifier Lexeme: j <Statement List Prime> -> <Statement List> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <Assign> <Assign> -> <Identifier> := <Expression> ; Token: Separator Lexeme: := Token: Separator Lexeme: ( <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> ( <Expression> ) Token: Integer Lexeme: 1 <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Integer> Token: Operator Lexeme: * <Term Prime> -> * <Factor> <Term Prime> Token: Integer Lexeme: 3 <Factor> -> <Primary> <Primary> -> <Integer> Token: Separator Lexeme: ) <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Operator Lexeme: * <Term Prime> -> * <Factor> <Term Prime> Token: Separator Lexeme: ( <Factor> -> <Primary> <Primary> -> ( <Expression> ) Token: Identifier Lexeme: sum <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Operator Lexeme: + <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> + <Term> <Expression Prime> Token: Separator Lexeme: ( <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> ( <Expression> ) Token: Identifier Lexeme: sum <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Operator Lexeme: * <Primary Prime> -> <Empty> <Term Prime> -> * <Factor> <Term Prime> Token: Integer Lexeme: 3 <Factor> -> <Primary> <Primary> -> <Integer> Token: Separator Lexeme: ) <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Operator Lexeme: - <Term Prime> -> <Empty> <Expression Prime> -> - <Term> <Expression Prime> Token: Identifier Lexeme: i <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Operator Lexeme: * <Primary Prime> -> <Empty> <Term Prime> -> * <Factor> <Term Prime> Token: Integer Lexeme: 2 <Factor> -> <Primary> <Primary> -> <Integer> Token: Separator Lexeme: ) <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Separator Lexeme: ; <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Identifier Lexeme: signal <Statement List Prime> -> <Statement List> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <Assign> <Assign> -> <Identifier> := <Expression> ; Token: Separator Lexeme: := Token: Keyword Lexeme: true <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> true Token: Separator Lexeme: ; <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Keyword Lexeme: read <Statement List Prime> -> <Statement List> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <Read> <Read> -> read ( <IDs> ) ; Token: Separator Lexeme: ( Token: Identifier Lexeme: max <IDs> -> <Identifier> <IDs Prime> Token: Separator Lexeme: , <IDs Prime> -> , <IDs> Token: Identifier Lexeme: signal <IDs> -> <Identifier> <IDs Prime> Token: Separator Lexeme: ) <IDs Prime> -> <Empty> Token: Separator Lexeme: ; Token: Keyword Lexeme: while <Statement List Prime> -> <Statement List> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <While> <While> -> while ( <Condition> ) <Statement> JMP Token: Separator Lexeme: ( Token: Identifier Lexeme: i <Condition> -> <Expression> <Relop> <Expression> <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Operator Lexeme: < <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> <Empty> <Relop> -> < Token: Identifier Lexeme: sum <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Separator Lexeme: ) <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Separator Lexeme: { <Statement> -> <Compound> <Compound> -> { <Statement List> } Token: Identifier Lexeme: sum <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <Assign> <Assign> -> <Identifier> := <Expression> ; Token: Separator Lexeme: := Token: Identifier Lexeme: sum <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Operator Lexeme: + <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> + <Term> <Expression Prime> Token: Identifier Lexeme: i <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Separator Lexeme: ; <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Identifier Lexeme: i <Statement List Prime> -> <Statement List> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <Assign> <Assign> -> <Identifier> := <Expression> ; Token: Separator Lexeme: := Token: Operator Lexeme: - <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> - <Primary> Token: Identifier Lexeme: i <Primary> -> <Identifier> <Primary Prime> Token: Operator Lexeme: + <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> + <Term> <Expression Prime> Token: Integer Lexeme: 1 <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Integer> Token: Separator Lexeme: ; <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Separator Lexeme: } <Statement List Prime> -> <Empty> Token: Keyword Lexeme: write <Statement List Prime> -> <Statement List> <Statement List> -> <Statement> <Statement List Prime> <Statement> -> <Write> <Write> -> write ( <Expression> ) ; Token: Separator Lexeme: ( Token: Identifier Lexeme: sum <Expression> -> <Term> <Expression Prime> <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Operator Lexeme: + <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> + <Term> <Expression Prime> Token: Identifier Lexeme: max <Term> -> <Factor> <Term Prime> <Factor> -> <Primary> <Primary> -> <Identifier> <Primary Prime> Token: Separator Lexeme: ) <Primary Prime> -> <Empty> <Term Prime> -> <Empty> <Expression Prime> -> <Empty> Token: Separator Lexeme: ; Token: Separator Lexeme: $$ <Statement List Prime> -> <Empty> Source file parsing finished with no errors. Assembly Code Listing 1 PUSHM 1000 2 PUSHI 3 3 EQU 4 JUMPZ 7 5 PUSHI 0 6 POPM 1007 7 PUSHM 1000 8 PUSHM 1001 9 LES 10 JUMPZ 13 11 PUSHM 1002 12 POPM 1000 13 PUSHI 3 14 POPM 1005 15 PUSHI 0 16 POPM 1006 17 PUSHI 1 18 PUSHM 1005 19 PUSHI 2 20 SUB 21 PUSHM 1006 22 SUB 23 MUL 24 POPM 1003 25 PUSHI 1 26 PUSHI 3 27 MUL 28 PUSHM 1006 29 PUSHM 1006 30 PUSHI 3 31 MUL 32 ADD 33 PUSHM 1003 34 PUSHI 2 35 MUL 36 SUB 37 MUL 38 POPM 1004 39 PUSHI 1 40 POPM 1007 41 PUSHSTD 42 POPM 1005 43 PUSHSTD 44 POPM 1007 45 LABEL 46 PUSHM 1003 47 PUSHM 1006 48 LES 49 JUMPZ 61 50 PUSHM 1006 51 PUSHM 1003 52 ADD 53 POPM 1006 54 PUSHI -1 55 PUSHM 1003 56 MUL 57 PUSHI 1 58 ADD 59 POPM 1003 60 JUMP 45 61 PUSHM 1006 62 PUSHM 1005 63 ADD 64 POPSTD Symbol Table a 1000 int b 1001 int c 1002 int i 1003 int j 1004 int max 1005 int sum 1006 int signal 1007 boolean
14,151
Common Lisp
.l
485
28.115464
61
0.67333
tom4244/Compiler_in_Common_Lisp
0
0
0
AGPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
6a27379694ff41d3cbc045214ab54fa834d5adeb2abc26f3b4835bcbb61a9c8e
41,572
[ -1 ]
41,573
sample2.rat
tom4244_Compiler_in_Common_Lisp/sample2.rat
$$ $$ int max,sum; boolean j; i := 5; sum := 1 + 3; $$ int max,sum; boolean i; sum := 0; i := 1; read( max); while (i <= max) { sum := sum + i; i := i + 1; while (sum < max) i := 3; } write (sum+max); $$
287
Common Lisp
.l
20
9.45
27
0.380392
tom4244/Compiler_in_Common_Lisp
0
0
0
AGPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
6e62f8fba59399eeafe046171deee67d1385a67c401473b53e70812a4e91c952
41,573
[ -1 ]
41,574
sample.rat
tom4244_Compiler_in_Common_Lisp/sample.rat
$$ $$ int a,b,c,i,j,max,sum; boolean signal; if (a = 3) signal := false; endif if (a < b) a := c; endif max := 3; sum := 0; i := 1 * ((max - 2) - sum); j := (1 * 3)*(sum + (sum*3) - i * 2); signal := true; read( max, signal); while (i < sum) { sum := sum + i; i := -i + 1; } write (sum+max); $$
379
Common Lisp
.l
18
15.555556
41
0.394366
tom4244/Compiler_in_Common_Lisp
0
0
0
AGPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
b3861fe471bcaf3d0532d0b82e756d1e5f17c524b0ea40ec30a5f46c4ac7d5bb
41,574
[ -1 ]
41,589
hello.lisp
lross2k_practice-in-clisp/hello.lisp
; Ubiquitous hello world environment test (print "Hello, world!") #| Multi line comments just for fun |# (format t "Goodbye, world!")
144
Common Lisp
.lisp
7
18.142857
41
0.711111
lross2k/practice-in-clisp
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
5c36ceb20d87de7f8d035117752ae056878b965e3cc98368d7121dfac5168402
41,589
[ -1 ]
41,590
oop.lisp
lross2k_practice-in-clisp/oop.lisp
;; lisp has generic functions with methods that can allow for different behaivours, this means ;; functions have generics and abstraction integrated, nice ;; Generic function definition (defgeneric description (object) (:documentation "Return a description of an object.")) ;; Defining methods for the generic function (defmethod description ((object integer)) (format nil "The integer ~D" object)) (defmethod description ((object float)) (format nil "The float ~3,3f" object)) ;; Trying the different methods of the generic function (print (description 10)) (print (description 3.14)) ;; Classes ;; Superclass (defclass vehicle () ((speed :accessor vehicle-speed :initarg :speed :type real :documentation "The vehicle's current speed.")) (:documentation "The base class of vehicles.")) ;; Actual classes (defclass bicycle (vehicle) ((mass :reader bicycle-mass :initarg :mass :type real :documentation "The bike's mass.")) (:documentation "A bicycle.")) (defclass canoe (vehicle) ((rowers :reader canoe-rowers :initarg :rowers :initform 0 :type (integer 0) :documentation "The number of rowers.")) (:documentation "A canoe.")) ;; Instantiation (defparameter canoe (make-instance 'canoe :speed 10 :rowers 6)) (print (canoe-rowers canoe)) ;(print (canoe-speed canoe)) ;; Can't acces it like this because it's from the superclass (print (vehicle-speed canoe)) ;; Show information of a class with describe (describe 'canoe)
1,619
Common Lisp
.lisp
44
31.272727
94
0.68115
lross2k/practice-in-clisp
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
d9c341c7a1802d84b945adf7b1a994ad8faf4e9779a55394dc83045d4428795e
41,590
[ -1 ]
41,591
io.lisp
lross2k_practice-in-clisp/io.lisp
;; Write a file with random numbers (with-open-file (stream (merge-pathnames #p"data.txt" (user-homedir-pathname)) :direction :output :if-exists :supersede :if-does-not-exist :create) (dotimes (i 100) (format stream "~3,3f~%" (random 100)))) ;; Read the content of the file ;(uiop:read-file-string (merge-pathnames #p"data.txt" ; (user-homedir-pathname)))
516
Common Lisp
.lisp
11
34.909091
66
0.506958
lross2k/practice-in-clisp
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
5b7e318e26f39da2da3ca70c9f4d52dc3a08bf45436d4e2019e12408cedc5ac5
41,591
[ -1 ]
41,592
vars.lisp
lross2k_practice-in-clisp/vars.lisp
; Defining variables (let ((str "Hello, world!")) (print str)) ; Defining and operating on variables (let ((str "Goodbye, world!")) (string-upcase str) (print str)) ; Defining multiple variables (let ((x 1) (y 5)) (+ x y) (print x)) ; Variables with initial values dependant on other vars (let* ((x 1) (y (+ x 1))) y (print y)) #|---------------------- Dynamic variables (kinda like global vars) ------------------------|# ; defparameter requires an initial value, defvar doesn't ; defparameter values are changed after code reload, defvar isn't ; Defining parameters (defparameter salute "Hello, world, again!") (defvar sayonara "I'm done!") (print salute) (print sayonara) ; Changing the values temporally (let ((salute "Oh no")) (print salute)) (let ((sayonara "Not anymore")) (print sayonara)) ; Printing the final values (print salute) (print sayonara)
904
Common Lisp
.lisp
36
22.833333
66
0.668219
lross2k/practice-in-clisp
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
e649536724ca40baede8cb91b400dbc53a0a45cfc42160982b92738aacb14b62
41,592
[ -1 ]
41,593
funcs.lisp
lross2k_practice-in-clisp/funcs.lisp
; simple function definition (defun add (a b) (print (+ a b))) ; call directly (add 2 3) ; anonymous funcall (funcall #'add 6 -3.5) ; anonymous apply (apply #'add (list -5 6.666)) ; multiple value return function (defun many (n) (values n (* n 2) (/ n 3))) ; test multiple return values (multiple-value-list (many 3)) ; bind one special return value (multiple-value-bind (v0 v1 v2) (many 3) (list v0 v1 v2))
421
Common Lisp
.lisp
18
21.666667
32
0.694444
lross2k/practice-in-clisp
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
484502e6831c91cd4f85203ac5f2a4fe7c4c9d1d82cf7ea255b7ea5637a66f42
41,593
[ -1 ]
41,594
electric-motors.lisp
lross2k_practice-in-clisp/electric-motors.lisp
#| - 230V / 4H - inverse time automatic breakers except for 15 HP motors which have instantaneous breaker - service factor of 1,1 - star connection 208V - one of the 4 15 HP motors is used as a backup, in case one of the other 3 fails - average temperature of 33ºC - 53kW load corresponds to illumination distributed charges in a triphasic system - motors work continously with a PF of 0,85 - induction motor with coil rotor has an efficiency of 86% at nominal demand 1. Current from the system source conductor 2. AWG conductor in aluminum of the source conductor of a 2 by phase EMT duct of 38 meters 3. Breaker of the principal box that protects the source conductor |# (defun apply-temp-correction (current) (if (> current 99) (/ current 0.94) (/ current 0.91))) ; one 30 HP induction motor with coil rotor branch and capacitors (princ "230V, coil rotor, 30HP") (terpri) ; 86% efficiency means there is another value for input power ; I = P / (sqrt3 V FP) (defvar i-30 (/ (* (/ 30 0.86) 746) (* (sqrt 3) (* 230 0.85)))) (defvar i-30-temp (apply-temp-correction i-30)) (princ "I_30 = ") (write i-30) (princ " A") (terpri) (terpri) ; two 40 HP syncronic motors (princ "230V, syncronic motor, 40HP") (terpri) (princ "I_40 = ") (defvar i-40 (* 83 (/ 1 0.85))) (defvar i-40-temp (apply-temp-correction i-40)) (write i-40) (princ " A") (terpri) (terpri) ; four 15 HP squirrel cage induction motors (princ "230V, squirrel cage rotor motor, 15HP") (terpri) (princ "I_15 = ") (defparameter i-15 42) (defparameter i-15-temp (apply-temp-correction i-15)) (write i-15) (princ " A") (terpri) (terpri) ; 53 kW installed load, DF max 0,85 with PF 1, not continous load (princ "53 kW luminic load") (terpri) (defvar i-load (* (/ 53e3 (* 230 (* (sqrt 3) 1))) 0.85)) (defvar i-load-temp (apply-temp-correction i-load)) (princ "I_load = ") (write i-load) (princ " A") (terpri) (terpri) ; whole system's source conductor (defvar i-system (+ (* (+ i-40 i-load) 1.25) (+ i-40 (+ i-30 (* 3 i-15))))) (princ "Feeder current without temperature correction: ") (write i-system) (princ " A") (terpri) (defvar i-system-temp (+ (* (+ i-40-temp i-load-temp) 1.25) (+ i-40-temp (+ i-30-temp (* 3 i-15-temp))))) (princ "Feeder current with temperature correction: ") (write i-system-temp) (princ " A") (terpri) ; AWG conductor for the system in copper, 1 by phase in cable trays (princ "Copper AWG #500 MCM which can whitstand 620 A @ 75ºC") ; NEC 310.15(B)(17) (terpri) (terpri) ; Copper conductors for each motor derivation (princ "125% because of 430.22(A)") (terpri) (princ "230V, coil rotor, 30HP") (terpri) (princ "I_30 = ") (write (apply-temp-correction (* i-30 1.25))) (princ " A") (terpri) (princ "Copper AWG #4 which can whitstand 125 A @75ºC") (terpri) (princ "230V, syncronic motor, 40HP") (terpri) (princ "I_40 = ") (write (apply-temp-correction (* i-40 1.25))) (princ " A") (terpri) (princ "Copper AWG #3 which can whitstand 145 A @75ºC, but it isn't available in Costa Rica") (terpri) (princ "therefore Copper AWG #2 which can whitstand 170 A @75ºC") (terpri) (princ "230V, squirrel cage rotor motor, 15HP") (terpri) (princ "I_15 = ") (write (apply-temp-correction (* i-15 1.25))) (princ " A") (terpri) (princ "Copper AWG #8 which can whitstand 60 A @60ºC") (princ "static load") (terpri) (princ "I_load = ") (write (apply-temp-correction (* i-load 1.25))) (princ " A") (terpri) (princ "Copper AWG #2 which can whitstand 170 A @75ºC") (terpri) (terpri) ; Breaker for the main branch (princ "150% for the 30 HP motor: ") (write (* i-30 1.5)) (princ " A") (terpri) (princ "110 A breaker") (terpri) (princ "250% for the 40 HP motors: ") (write (* i-40 2.5)) (princ " A") (terpri) (princ "225 A breaker") (terpri) (princ "800% for 15 HP motors: ") (write (* i-15 8.0)) (princ " A") (terpri) (princ "300 A breaker") (terpri) (princ "ilumination loads: ") (write i-load) (princ " A") (terpri) (terpri) (princ "Therefore, the current for main branch is: ") (write (+ 300 (+ i-30 (+ (* i-40 2) (+ (* i-15 2) i-load))))) (princ " A") (terpri) (princ "700 A breaker for the main branch") ; 240.6(A) (terpri)
4,128
Common Lisp
.lisp
101
39.445545
105
0.686029
lross2k/practice-in-clisp
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
115d83bb1eda973ea84bea665c5217c7ad4e63416ba0d7b323554898e32049b6
41,594
[ -1 ]
41,595
lists.lisp
lross2k_practice-in-clisp/lists.lisp
; Saving a list to a variable (defparameter list1 (list 1 2 3 4 5 6 7 8 9 10)) ; Accessing the list in different ways (print list1) (print (first list1)) (print (tenth list1)) ; Changing a value in the list (setf (third list1) 11) (print list1) (setf (nth 9 list1) -1.102831) (print list1) (setf (nth 2 list1) "a") (print list1) ; Simple function to test map (defun map_test (n) (print (/ n 2))) ; Using map for simple addition (mapcar #'map_test (list 1 2 3 4 5)) ; Using reduce function (print (reduce #'- (list 1 3 5 7 9 11))) ; Using the standard sort function (print (sort (list 9 2 6 2 9 1 8 4 5) #'<)) ; Destructuring list (destructuring-bind (first third &rest all) (list 1 2 3 4 5 6 7) (print first) (print third) (print all))
782
Common Lisp
.lisp
28
25.285714
48
0.668901
lross2k/practice-in-clisp
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
69d13c02fade2e5049b6313274756a05379df9be0f9312341ea58e5331afd1cb
41,595
[ -1 ]
41,596
macros.lisp
lross2k_practice-in-clisp/macros.lisp
;; Simple while loop as you can clearly see (let ((i 0)) (loop while (< i 3) do (progn (incf i))) (print i) ) ;; Handy macro to make the while loop more C like (defmacro while (condition &body body) `(loop while ,condition do (progn ,@body))) ;; Same while loop from the beginning, less lisp-y (let ((i 0)) (while (< i 3) (incf i)) (print i) )
364
Common Lisp
.lisp
15
21.933333
50
0.647399
lross2k/practice-in-clisp
0
0
0
GPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
64b752d4590b32f22ac20ba8917054bd4acdc063f341130abb45cc3502b8fac0
41,596
[ -1 ]
41,620
example.lisp
bohonghuang_cl-libagbplay/example.lisp
(defpackage cl-libagbplay-example (:use #:cl #:libagbplay #:raylib) (:import-from #:cffi #:make-shareable-byte-vector #:with-pointer-to-vector-data) (:nicknames #:libagbplay-example) (:export #:run-example)) (in-package #:libagbplay-example) (defparameter +buffer-size+ 4096) (defun run-example () (with-window (800 450 "cl-libagbplay example") (let* ((player (make-agb-player #P"rom.gba" :verification nil)) (buffer (make-shareable-byte-vector (* +buffer-size+ 4 2))) (song-id 0) (song-count (agb-player-get-song-number player))) (set-target-fps 30) (set-audio-stream-buffer-size-default +buffer-size+) (with-audio-device (with-audio-stream (stream 48000 32 2) (unwind-protect (progn (agb-player-set-song player song-id) (agb-player-play player) (play-audio-stream stream) (loop :until (window-should-close) :do (progn (with-pointer-to-vector-data (buffer-pointer buffer) (when (is-audio-stream-processed stream) (agb-player-take-buffer player buffer-pointer +buffer-size+) (update-audio-stream stream buffer-pointer +buffer-size+))) (with-drawing (when (cond ((is-key-pressed +key-up+) (decf song-id)) ((is-key-pressed +key-down+) (incf song-id)) ((is-key-pressed +key-left+) (decf song-id 10)) ((is-key-pressed +key-right+) (incf song-id 10)) ((is-key-pressed +key-space+) (agb-player-pause player)) (t nil)) (agb-player-set-song player (setf song-id (mod song-id song-count)))) (clear-background +raywhite+) (draw-fps 0 0) (draw-text (format nil "Current Song: ~A" song-id) 50 50 32 +black+))))) (agb-player-stop player) (with-pointer-to-vector-data (buffer-pointer buffer) (agb-player-take-buffer player buffer-pointer +buffer-size+)) (agb-player-delete player) (stop-audio-stream stream)))))))
2,500
Common Lisp
.lisp
45
36.777778
103
0.501631
bohonghuang/cl-libagbplay
0
0
0
LGPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
5ca5845c9bab58674a484c7952427520957fd8b90441a9d56e56dc0841b81b97
41,620
[ -1 ]
41,621
cl-libagbplay.lisp
bohonghuang_cl-libagbplay/cl-libagbplay.lisp
(defpackage cl-libagbplay (:use #:cl #:cffi) (:nicknames #:libagbplay) (:export #:agb-player #:agb-player-delete #:agb-player-play #:agb-player-pause #:agb-player-stop #:agb-player-playing-p #:agb-player-set-song #:agb-player-get-song-number #:agb-player-take-buffer #:make-agb-player)) (in-package #:libagbplay) (define-foreign-library libagbplay (:darwin "libagbplay.dylib") (:unix "libagbplay.so") (:windows "libagbplay.dll") (t (:default "libagbplay"))) (unless (foreign-library-loaded-p 'libagbplay) (let ((*foreign-library-directories* '("."))) (use-foreign-library libagbplay))) (eval-when (:compile-toplevel :load-toplevel :execute) (defmethod translate-name-from-foreign ((spec string) (package (eql *package*)) &optional varp) (let ((name (translate-camelcase-name spec :upper-initial-p t))) (if varp (intern (format nil "*~a" name)) name))) (defmethod translate-name-to-foreign ((spec symbol) (package (eql *package*)) &optional varp) (let ((name (translate-camelcase-name spec :upper-initial-p t))) (if varp (subseq name 1 (1- (length name))) name)))) (defctype size-t #.(cond ((= 4 (foreign-type-size :pointer)) :uint32) ((= 8 (foreign-type-size :pointer)) :uint64) (t (error "Failed type lisp-pointer-type")))) (defcstruct agb-player (handle :pointer)) (defcstruct (%agb-player-config :class agb-player-config-type) (buffer-size size-t) (max-loop-count :int8) (verification-enabled :bool)) (defstruct agb-player-config max-loop-count buffer-size verification-enabled) (defmethod translate-into-foreign-memory (object (type agb-player-config-type) pointer) (with-foreign-slots ((buffer-size max-loop-count) pointer (:struct %agb-player-config)) (setf buffer-size (coerce (agb-player-config-buffer-size object) 'unsigned-byte)) (setf max-loop-count (coerce (agb-player-config-max-loop-count object) '(signed-byte 8))) (setf verification-enabled (agb-player-config-verification-enabled object)))) (defmethod translate-from-foreign (pointer (type agb-player-config-type)) (with-foreign-slots ((buffer-size max-loop-count verification-enabled) pointer (:struct %agb-player-config)) (make-agb-player-config :buffer-size buffer-size :max-loop-count max-loop-count :verification-enabled verification-enabled))) (defcfun "AgbPlayerCreateFromRomData" (:struct agb-player) (data :pointer) (size :uint) (config (:struct %agb-player-config))) (defcfun "AgbPlayerCreateFromPath" (:struct agb-player) (path :string) (config (:struct %agb-player-config))) (defgeneric make-agb-player (object &key max-loop-count buffer-size)) (defmethod make-agb-player ((path pathname) &key (max-loop-count -1) (buffer-size 8192) (verification t)) (agb-player-create-from-path (namestring path) (make-agb-player-config :max-loop-count max-loop-count :buffer-size buffer-size :verification-enabled verification))) (defmethod make-agb-player ((rom vector) &key (max-loop-count -1) (buffer-size 8192) (verification t)) (with-pointer-to-vector-data (rom-pointer rom) (agb-player-create-from-rom-data rom-pointer (length rom) (make-agb-player-config :max-loop-count max-loop-count :buffer-size buffer-size :verification-enabled verification)))) (defcfun "AgbPlayerDelete" :void (player (:struct agb-player))) (defcfun "AgbPlayerPlay" :void (player (:struct agb-player))) (defcfun "AgbPlayerPause" :void (player (:struct agb-player))) (defcfun "AgbPlayerStop" :void (player (:struct agb-player))) (defcfun "AgbPlayerIsPlaying" :void (player (:struct agb-player))) (defun agb-player-playing-p (player) (agb-player-playing-p player)) (defcfun "AgbPlayerSetSong" :void (player (:struct agb-player)) (song-id :uint16)) (defcfun "AgbPlayerGetSongNumber" :uint (player (:struct agb-player))) (defcfun "AgbPlayerTakeBuffer" :void (player (:struct agb-player)) (buffer :pointer) (size size-t))
4,376
Common Lisp
.lisp
92
39.891304
110
0.657666
bohonghuang/cl-libagbplay
0
0
0
LGPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
af5e4778a44038449996a02bed17d285ba919baa6d1b99a7d561c9b27e54deb9
41,621
[ -1 ]
41,622
cl-libagbplay.asd
bohonghuang_cl-libagbplay/cl-libagbplay.asd
#+sb-core-compression (defmethod asdf:perform ((o asdf:image-op) (c asdf:system)) (uiop:dump-image (asdf:output-file o c) :executable t :compression t)) (defsystem cl-libagbplay :version "1.0.0" :author "Bohong Huang <[email protected]>" :maintainer "Bohong Huang <[email protected]>" :license "lgpl3" :description "Play GBA game music in Common Lisp" :homepage "https://github.com/BohongHuang/cl-libagbplay" :bug-tracker "https://github.com/BohongHuang/cl-libagbplay/issues" :source-control (:git "https://github.com/BohongHuang/cl-libagbplay.git") :components ((:file "cl-libagbplay")) :depends-on (#:cffi-libffi)) (defsystem cl-libagbplay/example :components ((:file "example")) :build-operation program-op :build-pathname "libagbplay" :entry-point "libagbplay-example:run-example" :depends-on (#:asdf #:cl-libagbplay #:cl-raylib))
899
Common Lisp
.asd
22
36.954545
75
0.715429
bohonghuang/cl-libagbplay
0
0
0
LGPL-3.0
9/19/2024, 11:50:34 AM (Europe/Amsterdam)
6210af4f60f7fcd8b472dea8f013f7a8e4d511d036142c27638b2cc86fdaa849
41,622
[ -1 ]
41,641
lisp-15.lisp
old-tom-bombadil_lisp-1_5/lisp-15.lisp
; lisp implementation as documented in Lisp 1.5 Programmers Manual (defun tww-pairlis (x y a) "itemwise pair the first two lists and cons onto the third" (cond ((null x) a) (T (cons (cons (car x) (car y)) (tww-pairlis (cdr x ) (cdr y) a))))) (defun tww-assoc (x a) "find the pair in a starting with x" (cond ((equal (caar a) x) (car a)) (T (tww-assoc x (cdr a))))) (defun tww-evcon (c a) (cond ((tww-eval (caar c) a) (tww-eval (cadar c) a)) (T (tww-evcon (cdr c) a)))) (defun tww-eval (e a) (cond ((atom e) (cdr (assoc e a))) ;atoms evaluate to their environment value ((atom (car e)) (cond ((eq (car e) 'QUOTE) (cadr e)) ((eq (car e) 'COND) (tww-evcon (cdr e) a)) (T (tww-apply (car e) (tww-evlis (cdr e) a) a)))) (T (tww-apply (car e) (tww-evlis (cdr e) a) a)))) (defun tww-apply (fn x a) (cond ((atom fn) (cond ((eq fn 'CAR) (caar x)) ((eq fn 'CDR) (cdar x)) ((eq fn 'CONS) (cons (car x) (cadr x))) ((eq fn 'ATOM ) (atom (car x))) ((eq fn 'EQ) (eq (car x) (cadr x))) (T (tww-apply (tww-eval fn a) x a)))) ((eq (car fn) 'LAMBDA) (tww-eval (caddr fn) (tww-pairlis (cadr fn) x a))) ((eq (car fn) 'LABEL) (tww-apply (caddr fn) x (cons (cons (cadr fn) (caddr fn)) a))))) (defun tww-evlis (m a) (cond ((null m) NIL) (T (cons (tww-eval (car m) a) (tww-evlis (cdr m) a))))) (defun evalquote (fn x) (tww-apply fn x nil)) ;;(evalquote '(LAMBDA (x) (COND ((ATOM X) (QUOTE BLAH)) ((QUOTE T) (CAR x)))) '(14)) ;; (evalquote '(LAMBDA (x) (COND ((ATOM X) (QUOTE BLAH)) ((QUOTE T) (CAR x)))) '((1 2 3)))
1,586
Common Lisp
.lisp
35
41.685714
91
0.572078
old-tom-bombadil/lisp-1.5
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
33cb299fc0a3b8aff21158992e3674cbdb6335121ab843a73b4e30664f98043e
41,641
[ -1 ]
41,658
test-sb-alien.lisp
millejoh_cl-libpff/test-sb-alien.lisp
(defpackage :cl-libpff-test-sb-alien (:use #:cl #:sb-alien)) (in-package :cl-libpff-test-sb-alien) (load-shared-object "/usr/local/lib/libpff.so") (define-alien-routine "libpff_get_version" c-string) (defun test-get-version () (libpff-get-version)) (define-alien-routine "libpff_check_file_signature" int (filename c-string) (error (* t))) (defun test-file-signature () (let ((fname "/mnt/c/Users/mille/Documents/Outlook Files/Outlook1.pst") (invalid-fname "/home/millejoh/Dropbox/20170627 Scarlett DS11_Complete.pdf")) (if (= 1 (libpff-check-file-signature fname nil)) (format t "~A is a valid PFF datafile.~%" fname) (warn "Something isn't right with signature of ~A.~%" fname)) (if (= 1 (libpff-check-file-signature invalid-fname nil)) (format t "~A is a valid PFF datafile.~%" fname) (warn "Something isn't right with signature of ~A.~%" fname)))) (define-alien-routine "libpff_file_initialize" int (fhandle (* t)) (error (* t))) (defun test-file-initialize () )
1,041
Common Lisp
.lisp
24
39.291667
85
0.684211
millejoh/cl-libpff
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
3632a32d3acb41f44648c38fd7e9f133de68a2cfbc5fadd1ac69a7bf9eac5ac0
41,658
[ -1 ]
41,659
test-cffi.lisp
millejoh_cl-libpff/test-cffi.lisp
(defpackage :cl-libpff-test-cffi (:use #:cl #:cffi)) (in-package :cl-libpff-test-cffi) (defparameter *test-pst-file-1* "/mnt/c/Users/mille_9b1cm14/OneDrive/Documents/Outlook Files/test.pst") (defparameter *test-pst-file-2* "/mnt/c/Users/mille_9b1cm14/AppData/Local/Microsoft/Outlook/[email protected]") (define-foreign-library libpff (:unix (:or "libpff.so" "libpff.so.1" "/usr/local/lib/libpff.so")) (t (:default "libpff"))) (use-foreign-library libpff) (defcfun "libpff_get_version" :string) (defun test-cffi-get-version () (libpff-get-version)) (defcfun "libpff_check_file_signature" :int (filename :string) (err :pointer)) (defun test-check-file-signture () (let ((fname "/mnt/c/Users/mille/Documents/Outlook Files/Outlook1.pst") (invalid-fname "/home/millejoh/Dropbox/20170627 Scarlett DS11_Complete.pdf")) (if (= 1 (libpff-check-file-signature fname (null-pointer))) (format t "~A is a valid PFF datafile.~%" fname) (warn "Something isn't right with signature of ~A.~%" fname)) (if (= 1 (libpff-check-file-signature invalid-fname (null-pointer))) (format t "~A is a valid PFF datafile.~%" fname) (warn "Something isn't right with signature of ~A.~%" fname)))) (defcfun "libpff_file_initialize" :int (file :pointer) (error :pointer)) (defcfun "libpff_file_free" :int (file :pointer) (error :pointer)) (defun test-file-initialize () (let ((f (foreign-alloc :pointer :initial-element (null-pointer)))) (unless (= 1 (libpff-file-initialize f (null-pointer))) (warn "Something went wrong initializing a file object.")) (unless (null-pointer-p f) (libpff-file-f)) (foreign-free f))) (defcfun "libpff_file_open" :int (file :pointer) (filename :string) (access-flags :int) (error :pointer)) (defcfun "libpff_file_close" :int (file :pointer) (error :pointer)) (defcfun "libpff_file_get_size" :int (file :pointer) (size (:pointer :int64)) (err :pointer)) (defcfun "libpff_file_get_content_type" :int (file :pointer) (content-type (:pointer :uint8)) (err :pointer)) (defcfun "libpff_file_get_type" :int (file :pointer) (type (:pointer :uint8)) (err :pointer)) (defcfun "libpff_file_get_message_store" :int (file :pointer) (message-store :pointer) (err :pointer)) (defcfun "libpff_file_get_root_item" :int (handle :pointer) (root-item :pointer) (err :pointer)) (defcfun "libpff_file_get_root_folder" :int (handle :pointer) (root-folder :pointer) (err :pointer)) (defun test-file-open (&optional (path *test-pst-file-1*)) (unless (probe-file path) (warn "File ~A does not exist.~%" path)) (let ((f (foreign-alloc :pointer :initial-element (null-pointer)))) (format t "handle: ~A (~A)~%" f (mem-aref f :pointer 0)) (unless (= 1 (libpff-file-initialize f (null-pointer))) (warn "Something went wrong initializing a file object.")) (format t "handle: ~A (~A)~%" f (mem-aref f :pointer 0)) (unless (= 1 (libpff-file-open (mem-aref f :pointer 0) path 1 (null-pointer))) (warn "Something went wrong opening file ~A.~%" path)) (unless (= 1 (libpff-file-close (mem-aref f :pointer 0) (null-pointer))) (warn "Something went wrong closing file ~A.~%" path)) (libpff-file-free f (null-pointer)) (foreign-free f))) (defparameter +default-error+ (cffi:null-pointer)) (defun make-t-pointer () (cffi:foreign-alloc :pointer :initial-element (cffi:null-pointer))) (defclass pst-object () ((handle :accessor pst-handle :initform (make-t-pointer)))) (defclass pst-store (pst-object) ((source :accessor pst-store-source :initarg :source) (type :reader pst-store-type :initform 0) (root-folder :reader pst-store-root-folder :initform (make-t-pointer)) (message-store :reader pst-store-message-store :initform (make-t-pointer)) (size :reader pst-store-size :initform 0))) (defclass item (pst-object) ((id :reader pst-item-id :initform 0) (subitem-count :reader pst-))) (defmacro define-libpff-accessor (object-type accessor return-type) (let ((ffi-accessor-fn (intern (format nil "LIBPFF-~A-GET-~A" object-type accessor))) (accessor-fn (intern (format nil "_GET-~S-~S" object-type accessor)))) `(defun ,accessor-fn (ptr) (with-foreign-object (rval ,return-type) (let ((result (,ffi-accessor-fn ptr rval +default-error+))) (values (mem-ref rval ,return-type) result)))))) (define-libpff-accessor file size :long) (define-libpff-accessor file type :uint8) (define-libpff-accessor file content-type :uint8) ;; (define-libpff-accessor item identifier :unsigned-int) ;; (define-libpff-accessor item number-of-entries :unsigned-int) ;; (define-libpff-accessor item number-of-sub-items :unsigned-int) ;; (define-libpff-accessor item type :unsigned-char) ;; (define-libpff-accessor folder type ::unsigned-char) ;; (define-libpff-accessor folder utf8-name-size :int) ;; (define-libpff-accessor folder utf16-name-size :int) ;; (define-libpff-accessor folder number-of-sub-folders :int) (defmethod initialize-instance :after ((store pst-store) &key &allow-other-keys) (with-slots (handle source type size root-folder message-store) store (format t "~A" source) (libpff-file-initialize handle (cffi:null-pointer)) (when (probe-file source) (let ((rtype (foreign-alloc :uint8 :initial-element 0)) (rsize (foreign-alloc :int :initial-element 0))) (when (libpff-file-open handle source 1 +default-error+) (libpff-file-get-content-type handle rtype +default-error+) (libpff-file-get-size handle rsize +default-error+) (libpff-file-get-root-folder handle root-folder +default-error+) (libpff-file-get-message-store handle message-store +default-error+) (setf type (mem-aref rtype :uint8) size (mem-aref rsize :int)) (foreign-free rtype) (foreign-free rsize)))))) (defun new-test-store (&optional (filename *test-pst-file-1*)) (unless (probe-file filename) (error "File does not exist: ~A." filename)) (make-instance 'pst-store :source *test-pst-file-1*))
6,148
Common Lisp
.lisp
135
41.377778
122
0.69124
millejoh/cl-libpff
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
c05be570323858803e1e9233d15ae08ad4e8480228d1c13d41953ed058984d4e
41,659
[ -1 ]
41,660
test.lisp
millejoh_cl-libpff/test.lisp
(defpackage :cl-libpff-test (:use #:cl #:libpff-ffi #:plus-c)) (in-package :cl-libpff-test) (defparameter *test-pst-file-1* "/mnt/c/Users/mille_9b1cm14/OneDrive/Documents/Outlook Files/test.pst") (defparameter *test-pst-file-2* "/mnt/c/Users/mille/AppData/Local/Microsoft/Outlook/[email protected]") (defun test-version () (libpff-get-version)) (defun test-file-signature () (let ((fname "/mnt/c/Users/mille/Documents/Outlook Files/Outlook1.pst" ) (invalid-fname "/home/millejoh/Dropbox/20170627 Scarlett DS11_Complete.pdf")) (if (= 1 (libpff-check-file-signature fname (cffi:null-pointer))) (format t "~A is a valid PFF datafile.~%" fname) (warn "Something isn't right with signature of ~A.~%" fname)) (if (= 1 (libpff-check-file-signature invalid-fname (cffi:null-pointer))) (format t "~A is a valid PFF datafile.~%" fname) (warn "Something isn't right with signature of ~A.~%" fname)))) (defun test-initialize-file () (let ((f (cffi:foreign-alloc :pointer :initial-element (cffi:null-pointer)))) (unless (= 1 (libpff-file-initialize f (cffi:null-pointer))) (warn "Something went wrong initializing a file object.")) (unless (cffi:null-pointer-p f) (libpff-file-free f (cffi:null-pointer))) (cffi:foreign-free f))) (defun make-file-handle () (let ((f (cffi:foreign-alloc :pointer :initial-element (cffi:null-pointer)))) (unless (= 1 (libpff-file-initialize f (cffi:null-pointer))) (warn "Something went wrong initializing a file object.")) f)) (defun free-file-handle (handle) (unless (cffi:null-pointer-p handle) (libpff-file-free handle (cffi:null-pointer)))) (defun test-open-pst (&optional (file-name *test-pst-file-1*)) (let* ((f (make-file-handle)) (errptr (cffi:null-pointer))) (c-let ((handle :pointer :ptr f) (size :int)) (print (libpff-ffi::libpff-file-open handle file-name 1 errptr)) (print (libpff-ffi::libpff-file-get-size handle (size &) errptr)) (print size) (free-file-handle f)))) (defparameter +default-error+ (cffi:null-pointer)) (defun make-t-pointer () (cffi:foreign-alloc :pointer :initial-element (cffi:null-pointer))) (defclass pst-object () ((handle :accessor pst-handle :initform (make-t-pointer)))) (defclass pst-store (pst-object) ((source :accessor pst-store-source :initarg :source) (type :reader pst-store-type :initform 0) (size :reader pst-store-size :initform 0))) (defclass item (pst-object) ((id :reader pst-item-id :initform 0) (subitem-count :reader pst-subitem-count))) (defclass folder (item) ((name :reader folder-name :initform nil))) (defmethod initialize-instance :after ((store pst-store) &key &allow-other-keys) (with-slots (handle source type size root-folder message-store) store (format t "~A" source) (libpff-file-initialize handle (cffi:null-pointer)) (c-let ((handle :pointer :ptr handle)) (unless (= 1 (libpff-file-open handle source +libpff-open-read+ +default-error+)) (error "libpff: Could not open file ~A." source))))) (defmethod get-type ((folder folder)) (with-slots (handle) folder (c-let ((handle :pointer :ptr handle) (type :int)) (let ((ret (libpff-folder-get-type handle (type &) +default-error+))) (values type ret))))) (defmethod get-name ((folder folder)) (with-slots (handle) folder (c-let ((handle :pointer :ptr handle) (string-size :int) (name :pointer)) (let* ((ret1 (libpff-folder-get-utf8-name-size handle (string-size &) +default-error+)) (ret2 (libpff-folder-get-utf8-name handle (name &) string-size +default-error+))) (if (= 1 ret1 ret2) (cffi:foreign-string-to-lisp (name &) :count (1- string-size)) (warn "Could not get folder's name.")))))) (defmethod get-root-folder ((store pst-store)) (with-slots (handle) store (c-let ((handle :pointer :ptr handle)) (let* ((folder (make-instance 'folder)) (rtval (libpff-file-get-root-folder handle (pst-handle folder) +default-error+))) (values folder rtval))))) (defmethod subitem-count ((f folder)) (with-slots (handle) f (c-let ((handle :pointer :ptr handle) (icnt :int)) (let ((ret (libpff-folder-get-number-of-sub-folders handle (icnt &) +default-error+))) (values icnt ret))))) (defmethod get-subitem-by-index ((f folder) idx) (with-slots (handle) f (c-let ((handle :pointer :ptr handle)) (let* ((subfolder (make-instance 'folder)) (ret (libpff-folder-get-sub-folder handle idx (pst-handle subfolder) +default-error+))) (values subfolder ret))))) (defun new-test-store (&optional (filename *test-pst-file-1*)) (unless (probe-file filename) (error "File does not exist: ~A." filename)) (make-instance 'pst-store :source filename))
4,926
Common Lisp
.lisp
100
43.71
114
0.664724
millejoh/cl-libpff
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
91d972e81711cd531874f1f4b0a3f21cc7f73fe0fcff181f56db37413a8bf4e3
41,660
[ -1 ]
41,661
package.lisp
millejoh_cl-libpff/src/package.lisp
(in-package :cl-user) (defpackage #:libpff-ffi (:use)) (defpackage #:libpff (:use #:cl #:autowrap.minimal #:plus-c #:libpff-ffi))
136
Common Lisp
.lisp
5
25
55
0.674419
millejoh/cl-libpff
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
18d00ffbaaad02a8637b9b2ebc28fcdd0097c8b9cd1ef9f97af7df106a70ed10
41,661
[ -1 ]
41,662
library.lisp
millejoh_cl-libpff/src/library.lisp
(in-package :libpff-ffi) (cffi:define-foreign-library libpff (:unix (:or "libpff.so" "libpff.so.1" "/usr/local/lib/libpff.so")) (t (:default "libpff"))) (autowrap:c-include '(cl-libpff autospec "interface.h") :spec-path '(cl-libpff autospec) :exclude-definitions ("remove")) (cffi:use-foreign-library libpff)
336
Common Lisp
.lisp
8
37.625
67
0.68
millejoh/cl-libpff
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
193a1eab3ddd89e002bebf6848d68ec6604bdc582fb53315c1fc3e35abf3c11d
41,662
[ -1 ]
41,663
cl-libpff-test.asd
millejoh_cl-libpff/cl-libpff-test.asd
(in-package :cl-user) (asdf:defsystem :cl-libpff-test :serial t :pathname "" :depends-on ("cl-libpff") :components ((:file "test") (:file "test-cffi") (:file "test-sb-alien")))
216
Common Lisp
.asd
8
21.125
40
0.565217
millejoh/cl-libpff
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
14e14db8133ea103b05977ceb263cfa1f742023c13d0530342ae980311b76615
41,663
[ -1 ]
41,664
cl-libpff.asd
millejoh_cl-libpff/cl-libpff.asd
(in-package :cl-user) (asdf:defsystem #:cl-libpff :serial t :description "" :author "John M. Miller" :license "MIT" :version "0.1" :pathname "src" :depends-on ("cffi" "cl-autowrap" "cl-plus-c") :components ((:file "package") (:file "library") (:module #:autospec :pathname "autospec" :components ((:static-file "interface.h")))))
409
Common Lisp
.asd
14
22.571429
61
0.56599
millejoh/cl-libpff
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
a90b51bd78c571bd9016aa8e7ed748d70dafb50e4649f796965ec84f1522b58f
41,664
[ -1 ]
41,687
statistics.lisp
dzangfan_lineva/statistics.lisp
(ql:quickload :uiop :silent t) (ql:quickload :alexandria :silent t) (defparameter *maximum-depth* 3) (defun read-all-forms (file-name) (let ((sharp-dot (get-dispatch-macro-character #\# #\.))) (set-dispatch-macro-character #\# #\. (lambda (s c n) (declare (ignore s c n)) nil)) (unwind-protect (handler-bind ((error (lambda (c) (let ((r (find-restart 'continue c))) (when r (invoke-restart r)))))) (with-open-file (stream file-name) (loop :for next-form := (read stream nil :end-of-file) :for i :from 1 :until (eq :end-of-file next-form) :collecting next-form))) (set-dispatch-macro-character #\# #\. sharp-dot)))) (defun collect-toplevel-forms (forms predicate) (loop :for form :in forms :if (funcall predicate form) :collecting form)) (defun collect-forms (forms predicate &optional (depth *maximum-depth*)) (unless (plusp depth) (return-from collect-forms nil)) (let ((collected nil)) (when (and (not (alexandria:circular-list-p forms)) (alexandria:proper-list-p forms)) (when (funcall predicate forms) (push forms collected)) (loop :for form :in forms :for more-forms := (collect-forms form predicate (- depth 1)) :do (setf collected (append more-forms collected)))) collected)) (defun symbol-approx-equal (s1 s2) (and (symbolp s1) (symbolp s2) (string-equal (symbol-name s1) (symbol-name s2)))) (defun is-a (operator-symbol form) (and form (symbol-approx-equal operator-symbol (car form)))) (defun form<defun+long-body> (form) (and (alexandria:proper-list-p form) (or (is-a :defun form) (is-a :defmacro form)) (let ((body (cdddr form))) (when (and body (stringp (first body))) (setf body (cdr body))) (cdr body)))) (defun extract-concern (file-name-list) (loop :for file-name :in file-name-list :for forms := (handler-case (read-all-forms file-name) (t () nil)) :for concern := (collect-forms forms #'form<defun+long-body>) :appending concern)) (defun summary-concern (defuns) (loop :with counter := (make-hash-table :test #'eq) :for d :in defuns :for body := (cdddr d) :for body* := (if (stringp (first body)) (cdr body) body) :do (loop :for concern :in body* :do (cond ((listp concern) (symbolp (first concern)) (incf (gethash (car concern) counter 0))) ((atom concern) (incf (gethash concern counter 0))))) :finally (let ((alist (alexandria:hash-table-alist counter))) (return (sort alist #'> :key #'cdr))))) (defun statis-source* (&rest file-name-list) (let* ((file-names (apply #'list* file-name-list)) (concerns (extract-concern file-names))) (summary-concern concerns))) (defun statis-source (&rest file-names) (statis-source* file-names)) (defparameter directories () "Parameter: Root directories containing lisp sources directly or indirectly.") (defparameter files (loop :for dir :in directories :appending (uiop:directory-files dir "**/*.lisp"))) (defparameter result (statis-source* files)) (remove-if (lambda (record) (< (cdr record) 10)) result) '(:date "2022-9-18" :description "Most frequently used forms in `defun' and `defmacro' which have more than one form in their bodies. Ran over 671 lisp files." :result ((DECLARE . 513) (LET . 163) (WHEN . 124) (CHECK-TYPE . 118) (UNLESS . 79) (LET* . 62) (SETF . 53) (LOOP . 49) (IF . 39) (SB-INT:QUASIQUOTE . 34) (MULTIPLE-VALUE-BIND . 33) (ASSERT . 29) (FORMAT . 27) (OR . 23) (VALUES . 21) (NIL . 19) (SETQ . 17) (COND . 17) (FAST-WRITE-SEQUENCE . 14) (CLRHASH . 14) (SIGNAL-ERROR-IF-CURRENT-THREAD . 14) (T . 14) (TEST-BROKEN-INPUT . 13) (APPLY . 13) (DOLIST . 13) (ETYPECASE . 12) (ECASE . 10) (STRING-UPCASE . 10)))
4,196
Common Lisp
.lisp
94
36.095745
73
0.589574
dzangfan/lineva
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
4ef809766a268a91d3d8c1ba19ecc1b964432dbb20fcb9c0032c41023ba74340
41,687
[ -1 ]
41,688
lineva.lisp
dzangfan_lineva/lineva.lisp
(in-package :cl-user) (defpackage :lineva (:nicknames :la) (:use :common-lisp) (:export #:instruction #:definst #:leva #:available-instructions #:describe-instruction) (:documentation "Package providing linear evaluation feature.")) (in-package :lineva) (defmacro always-eval (&body body) "Equal to (eval-when (:compile-toplevel :load-toplevel :execute) ...)" `(eval-when (:compile-toplevel :load-toplevel :execute) ,@body)) (defparameter *expander-table* (make-hash-table :test #'eq) "A table of code transformer, whose keys are symbols and values are function which has signature (KEY REST-CODE OTHER-PARAMETERS) -> CODE KEY is its corresponding symbol in the *evaluator-table*, REST-CODE is expanded code in linear evaluation. Take the following code for example: ((K₁ ...) (K₂ ...) (K₃ ...) (K₄ ...)) the function corresponding to K₂ will receive code expanded from ((K₃ ...) (K₄ ...)) as its REST-CODE. OTHER-PARAMETERS is a parameter list customized by user, which correspond to ... in the code above.") (defparameter *expander-document-table* (make-hash-table :test #'eq) "Documentation table of item in *expander-table*") (defun find-expander (symbol) "Find expander in *expander-table* by SYMBOL, signal a error if nothing is found." (or (gethash symbol *expander-table*) (error "Unknown key ~S in *EXPANDER-TABLE*" symbol))) (always-eval (defparameter *rest-code-name* '$rest-code) (defun unary-p (list) "Return true if LIST is a list containing only one element." (and list (listp list) (null (cdr list))))) (defmacro leva (&body body) "Evaluate every instruction in BODY sequentially. Every instruction has one of following form: (:instruction-name ...) :instruction-name [= (:instruction-name)] compound-form where compound-form can be any valid lisp form except the first two. For example (la:leva (:let (x 10) (y 20)) ; Define local variables :break ; Create breakpoint (list x y)) ; Any Lisp form See `definst' for more information about user-defined instruction-name. See `available-instructions' for all defined instructions. Use `describe-instruction' to get document of a instruction." (loop :with body* := (reverse body) :and result := nil :for step :in body* :for step* := (if (keywordp step) (list step) step) :if (and step* (listp step*) (keywordp (car step*))) :do (destructuring-bind (key &rest params) step* (let* ((expander (find-expander key)) (rest-code (if (unary-p result) (first result) `(progn ,@result))) (result* (funcall expander key rest-code params))) (setf result (list result*)))) :else :do (push step* result) :end :finally (return (if (unary-p result) (first result) `(progn ,@result))))) (always-eval (defun has-docstring-p (body) "Determine whether BODY has docstring." (and body (stringp (first body)))) (defun extract-docstring (keyword lambda-list body) "Extract docstring and construct a better docstring by KEYWORD and LAMBDA-LIST." (let ((origin-doc (if (has-docstring-p body) (first body) nil)) (header (format nil "~S ~S" keyword lambda-list))) (if origin-doc (format nil "~A~%~%~A" header origin-doc) header)))) (defun define-instruction (keyword docstring function) "Define a new instruction called KEYWORD with FUNCTION. If the instruction has been defined, the old definition will be ignored." (when (remhash keyword *expander-table*) (warn "Instruction ~S has been defined. Old definition will be ignored" keyword)) (remhash keyword *expander-document-table*) (setf (gethash keyword *expander-table*) function (gethash keyword *expander-document-table*) docstring) (values)) (defmacro definst (keyword lambda-list &body body) "Define a instruction named KEYWORD. KEYWORD and LAMBDA-LIST correspond to instruction in `leva': (KEYWORD LAMBDA-LIST...) i.e. (:instruction ...) the BODY is a code which yield real code that the instruction KEYWORD defined. Special symbol `$rest-code' represents rest code of linear evaluation. If the first element of BODY is a `string', it will be seen as `documentation' of instruction KEYWORD. For example (definst :println (thing) \"Print THING and newline.\" `(progn (princ ,thing) (terpri) ,$rest-code)) then (la:leva (:println \"Hello world!\") (values)) will expand to (progn (princ \"Hello world!\") (terpri) (values))" (assert (keywordp keyword) (keyword) "Name of instruction should be a keyword, but found ~S" keyword) (let* ((key (gensym "key")) (params (gensym "params")) (doc (extract-docstring keyword lambda-list body)) (body* (if (has-docstring-p body) (cdr body) body))) `(define-instruction ,keyword ,doc (lambda (,key ,*rest-code-name* ,params) (declare (ignore ,key)) (destructuring-bind ,lambda-list ,params ,@body*))))) (defmethod documentation (keyword (type (eql 'la:instruction))) (declare (ignore type)) (gethash keyword *expander-document-table*)) (defmethod (setf documentation) (new-value object (type (eql 'la:instruction))) (declare (ignore type)) (assert (keywordp object) (object) "Name of instruction should be a keyword, but found ~S" object) (assert (stringp new-value) (new-value) "Value of documentation should be a string, but found ~S" new-value) (setf (gethash object *expander-document-table*) new-value)) (defun available-instructions () "Return all defined instructions." (loop :for key :being :the :hash-keys :of *expander-table* :collecting key :into keys :finally (return (sort keys #'string<)))) (defun describe-instruction (keyword &optional (stream *standard-output*)) "Display documentation of KEYWORD." (let ((doc (documentation keyword 'instruction))) (if doc (princ doc stream) (format stream "Instruction is not found. Available instructions:~%~A" (available-instructions))) (terpri stream))) ;; Display (definst :printf (format-string &rest arguments) "Print content to standard output. FORMAT-STRING and ARGUMENTS have the same meaning of `format'. >>> (la:leva (:printf \"Hello ~S!~%\" :world))" `(progn (format t ,format-string ,@arguments) ,$rest-code)) (definst :println (thing) "Print content to standard output and add newline. Use `princ' to output. >>> (la:leva (:println \"Hello world!\"))" `(progn (princ ,thing) (terpri) ,$rest-code)) (definst :pn (thing) "Print content to standard output and add newline. Use `prin1' to output. >>> (la:leva (:pn \"Hello world!\"))" `(progn (prin1 ,thing) (terpri) ,$rest-code)) ;; Local variable (definst :let (&rest let-arguments) "Define local variables by `let'. LET-ARGUMENTS has the same meaning of `let'. >>> (la:leva (:let (x 10) (y 20)) (+ x y))" `(let ,let-arguments ,$rest-code)) (definst :let-assert (&rest let-arguments) "Define local variables by `let' and assert its value. LET-ARGUMENTS has the same meaning of `let'. >>> (la:leva (:let-assert (x 10) (y 20) (z nil)) (+ x y z))" (if (null let-arguments) $rest-code (destructuring-bind (name value) (first let-arguments) `(let ((,name ,value)) (assert ,name (,name) "~A should not be `nil'" ',name) (leva (:let-assert ,@(rest let-arguments)) ,$rest-code))))) (definst :flet (&rest flet-arguments) "Define local function by `flet', FLET-ARGUMENTS has the same meaning with `flet'. >>> (la:leva (:flet (add1 (x) (+ 1 x)) (dot2 (x) (* 2 x))) (dot2 (add1 10)))" `(flet ,flet-arguments ,$rest-code)) (definst :labels (&rest labels-arguments) "Define local function by `labels'. LABELS-ARGUMENTS has the same meaning with `labels' >>> (la:leva (:labels (fib (n) (if (< n 2) 1 (+ (fib (- n 1)) (fib (- n 2)))))) (fib 5))" `(labels ,labels-arguments ,$rest-code)) (definst :macrolet (&rest macrolet-arguments) "Define local macro by `macrolet'. MACROLET-ARGUMENTS has the same meaning with `macrolet'. >>> (la:leva (:macrolet (record (&rest values) `(list ,@values))) (record \"Joe\" 20 nil))" `(macrolet ,macrolet-arguments ,$rest-code)) (definst :symbol-macrolet (&rest symbol-macrolet-arguments) " Define a local symbol-macro by `symbol-macrolet'. SYMBOL-MACROLET-ARGUMENTS has the same meaning with `symbol-macrolet'. >>> (la:leva (:symbol-macrolet (x (format t \"...~%\"))) (list x x x))" `(symbol-macrolet ,symbol-macrolet-arguments ,$rest-code)) (definst :defun (name lambda-list &body body) "Define a local function by `labels'. >>> (la:leva (:defun fac (n) (if (zerop n) 1 (* n (fac (- n 1))))) (fac 3))" `(labels ((,name ,lambda-list ,@body)) ,$rest-code)) (definst :defvar (name &optional value) "Define a local variable by `let'. >>> (la:leva (:defvar x 10) x)" `(let ((,name ,value)) ,$rest-code)) (definst :bind (lambda-list expression) "Define local variables by `destructuring-bind'. >>> (la:leva (:bind (a b &rest c) '(1 2 3 4 5)) (list a b c))" `(destructuring-bind ,lambda-list ,expression ,$rest-code)) (definst :setf (place value &key (if t)) "Invoke `setf' to set PLACE to VALUE if IF is not `nil'. >>> (la:leva (:defvar name :alexandria) (:setf name (symbol-name name) :if (not (stringp name))) name)" `(progn (when ,if (setf ,place ,value)) ,$rest-code)) ;; Debug (definst :break (&optional format-control &rest format-arguments) "Enter debugger by call `break'. Arguments has the same meaning with `break'. >>> (la:leva (:break \"Let's ~A!!!\" :burn))" (let ((break-args (and format-control `(,format-control ,@format-arguments)))) `(progn (break ,@break-args) ,$rest-code))) (definst :inspect (object) "Enter inspector with OBJECT. >>> (la:leva (:defvar x '(:foo :bar)) (:inspect x))" `(progn (inspect ,object) ,$rest-code)) (definst :assert (&rest conditions) "Quickly assert that all CONDITIONS is true. >>> (la:leva (:defvar x 10) (:assert (numberp x) (plusp x) (evenp x)) x)" (if (null conditions) $rest-code `(progn (assert ,(first conditions)) (leva (:assert ,@(cdr conditions)) ,$rest-code)))) (definst :check-type (&rest check-type-parameters) "Invoke `check-type' over each element of CHECK-TYPE-PARAMETERS. >>> (la:leva (:let (name \"Joe\") (age 20)) (:check-type (name (array character *) \"a string\") (age (integer 0 150))) (list name age))" (if (null check-type-parameters) $rest-code `(progn (check-type ,@(car check-type-parameters)) (leva (:check-type ,@(cdr check-type-parameters)) ,$rest-code)))) ;; Control flow (definst :return (value &key (if t)) "Return VALUE if condition IF is true. >>> (la:leva (:defvar x (read)) (:return (- x) :if (minusp x)) x)" `(if ,if ,value ,$rest-code)) (definst :try (&rest values) "Return first value in VALUES which is not `nil'. If all VALUES is `nil', evaluate rest code. >>> (la:leva (:defvar table '(:bing \"cn.bing.com\")) (:try (getf table :google) (getf table :duckduckgo) (getf table :bing)) \"No search engine available.\")" (if (null values) $rest-code `(or ,(car values) (leva (:try ,@(cdr values)) ,$rest-code)))) (definst :defer (&rest forms) "Evaluate rest codes, then evaluate FORMS sequentially. Result of rest code will be returned. Evaluation of rest code will be protected by `unwind-protect'. >>> (la:leva (:defun close-conn () (format t \"Bye!~%\")) (format t \"Hello!~%\") (:defer (close-conn) (terpri)) (format t \"[...]~%\"))" `(unwind-protect ,$rest-code ,@forms))
12,627
Common Lisp
.lisp
329
32.413374
80
0.627572
dzangfan/lineva
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
401498fa604be0b49829d2d2b14794c6c67c3675b4c85024ef2ea7e26ef1cb98
41,688
[ -1 ]
41,689
lineva-test.lisp
dzangfan_lineva/lineva-test.lisp
(in-package :cl-user) (defpackage :lineva/test (:use :common-lisp :fiveam)) (in-package :lineva/test) (defmacro does-leva-expand-to (result (&rest leva-args)) `(is (equalp (macroexpand '(la:leva ,@leva-args)) ,result))) (test empty-leva (does-leva-expand-to '(progn) ())) (test one-elt-leva (does-leva-expand-to 1 (1)) (does-leva-expand-to '(- 1) ((- 1)))) (test many-trivial-elt-leva (does-leva-expand-to '(progn 1 2 3) (1 2 3)) (does-leva-expand-to '(progn (print 1) 1.5 (print 2) 3) ((print 1) 1.5 (print 2) 3))) (test fake-inst-leva (does-leva-expand-to ''(:println "Hello world!") ('(:println "Hello world!"))) (does-leva-expand-to '(progn '(:println 1) '(:println 2)) ('(:println 1) '(:println 2))) (does-leva-expand-to '(values :break) ((values :break)))) (test simple-inst-leva (does-leva-expand-to '(let ((x 10)) (progn)) ((:let (x 10)))) (does-leva-expand-to '(let ((x 10) (y 20)) (+ x y)) ((:let (x 10) (y 20)) (+ x y))) (does-leva-expand-to '(progn (print 1) (print 2) (let ((x 10)) x)) ((print 1) (print 2) (:let (x 10)) x)) (does-leva-expand-to '(progn (print 1) (print 2) (let ((x 10)) (progn))) ((print 1) (print 2) (:let (x 10)))) (does-leva-expand-to '(let ((x 10)) (progn (print 1) (print x))) ((:let (x 10)) (print 1) (print x)))) (test inst-local-variables (is (eql 30 (la:leva (:let (x 10) (y 20)) (+ x y)))) (is (eql :error (handler-case (la:leva (:let-assert (x 10) (y 20) (z nil)) (+ x y)) (t () :error)))) (is (eql 60 (la:leva (:let-assert (x 10) (y 20) (z 30)) (+ x y z)))) (is (eql 22 (la:leva (:flet (add1 (x) (+ 1 x)) (dot2 (x) (* 2 x))) (dot2 (add1 10))))) (is (eql 8 (la:leva (:labels (fib (n) (if (< n 2) 1 (+ (fib (- n 1)) (fib (- n 2)))))) (fib 5)))) (is (equal '("Joe" 20 nil) (la:leva (:macrolet (record (&rest values) `(list ,@values))) (record "Joe" 20 nil)))) (let ((output (with-output-to-string (s) (is (equal '(nil nil nil) (la:leva (:symbol-macrolet (x (format s "...~%"))) (list x x x))))))) (is (string= (format nil "...~%...~%...~%") output))) (is (eql 6 (la:leva (:defun fac (n) (if (zerop n) 1 (* n (fac (- n 1))))) (fac 3)))) (is (eql 10 (la:leva (:defvar x 10) x))) (is (equal '(1 2 (3 4 5)) (la:leva (:bind (a b &rest c) '(1 2 3 4 5)) (list a b c)))) (is (string= "ALEXANDRIA" (la:leva (:defvar name :alexandria) (:setf name (symbol-name name) :if (not (stringp name))) (string-upcase name))))) (test inst-debug (does-leva-expand-to '(progn (print 1) (progn (break) (print 2))) ((print 1) :break (print 2))) (is (eql 10 (la:leva (:defvar x 10) (:assert (numberp x) (plusp x) (evenp x)) x))) (is (eql :error (handler-case (la:leva (:defvar x 11) (:assert (numberp x) (plusp x) (evenp x)) x) (t () :error)))) (is (equal '("Joe" 20) (la:leva (:let (name "Joe") (age 20)) (:check-type (name (array character *) "a string") (age (integer 0 150))) (list name age)))) (is (eql :error (handler-case (la:leva (:let (name "Joe") (age 200)) (:check-type (name (array character *) "a string") (age (integer 0 150))) (list name age)) (t () :error))))) (test inst-control-flow (is (eql 10 (la:leva (:defvar x -10) (:return (- x) :if (minusp x)) (error "Bye!")))) (is (string= "cn.bing.com" (la:leva (:defvar table '(:bing "cn.bing.com")) (:try (getf table :google) (getf table :duckduckgo) (getf table :bing)) "No search engine available."))) (let ((output (with-output-to-string (s) (is (eql :done (la:leva (:defun close-conn () (format s "Bye!~%")) (format s "Hello!~%") (:defer (close-conn) (terpri s)) (format s "[...]~%") (values :done))))))) (is (string= (format nil "Hello!~%[...]~%Bye!~%~%") output)))) (defmacro does-leva-output (content (&rest leva-args)) (let ((s (gensym))) `(is (string= ,content (with-output-to-string (,s) (let ((*standard-output* ,s)) (la:leva ,@leva-args))))))) (test inst-display (does-leva-output (format nil "Hello ~S!~%" :world) ((:printf "Hello ~S!~%" :world))) (does-leva-output (format nil "Hello world!~%") ((:println "Hello world!"))) (does-leva-output (format nil "~S~%" "Hello world!") ((:pn "Hello world!"))))
5,573
Common Lisp
.lisp
138
27.942029
79
0.434237
dzangfan/lineva
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
cdf03101ab7ceb46891b21b2720b77d4b43d627e1e8c96774590e85b46226143
41,689
[ -1 ]
41,690
instruction-docstring.lisp
dzangfan_lineva/instruction-docstring.lisp
(ql:quickload :str) (defparameter *docstring-seperator* (make-string 2 :initial-element #\Newline)) (defparameter *docstring-example-tag* " >>> ") (defparameter *docstring-example-tag-length* 6) (defun split-docstring (docstring) (la:leva (:bind (lambda-list detail example) (str:split *docstring-seperator* docstring)) (:let (example-lines (str:split #\Newline example))) (:let (first-line (first example-lines))) (let ((tag (str:substring 0 *docstring-example-tag-length* first-line))) (assert (string-equal *docstring-example-tag* tag))) (:defvar example-lines* (mapcar (lambda (line) (str:substring *docstring-example-tag-length* nil line)) example-lines)) (:let (example* (str:join #\Newline example-lines*))) (values lambda-list detail example*))) (defun docstring->org-block (instruction &optional (title-level 4)) (with-output-to-string (output) (let ((title (str:repeat title-level "*"))) (format output "~A ~(~S~)~%~%" title instruction)) (let ((docstring (documentation instruction 'la:instruction))) (assert docstring) (multiple-value-bind (lambda-list detail example) (split-docstring docstring) (format output "*lambda-list*: ~~~A~~~%~%" lambda-list) (format output "~A~%~%" detail) (format output "#+begin_src lisp~%") (format output "~A~%" example) (format output "#+end_src~%~%"))))) (defun docstring->org-block+group (group-name instruction-list &optional (title-level 3)) (with-output-to-string (output) (let ((title (str:repeat title-level "*"))) (format output "~A ~A~%~%" title group-name)) (loop :for inst :in instruction-list :do (format output "~A~%" (docstring->org-block inst (+ 1 title-level)))))) (defun output-docstring->org (stream title-level body-list) (loop :for group :in body-list :do (destructuring-bind (group &rest instructions) group (princ (docstring->org-block+group group instructions title-level) stream)))) (defmacro with-docstring->org (title-level &body body) `(output-docstring->org *standard-output* ,title-level ',body)) (with-docstring->org 3 ("Local Variables" :let :let-assert :flet :labels :macrolet :symbol-macrolet :defun :defvar :bind :setf) ("Debug" :break :inspect :assert :check-type) ("Contro Flow" :return :try :defer) ("Display" :printf :println :pn))
2,494
Common Lisp
.lisp
57
37.877193
77
0.653213
dzangfan/lineva
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
2a27a8cccb8baa3eb7b080df2b56cf9564a5a1518bf8c1451b2fda542d156a16
41,690
[ -1 ]
41,691
lineva.asd
dzangfan_lineva/lineva.asd
(in-package :asdf-user) (defsystem :lineva :description "Linear evaluation macro system" :version "0.0.1" :author "Li Dzangfan <[email protected]>" :licence "GPLv3" :depends-on () :components ((:file "lineva")) :in-order-to ((test-op (test-op :lineva/test)))) (defsystem :lineva/test :description "lineva's test suite" :author "Li Dzangfan <[email protected]>" :license "GPLv3" :depends-on (:fiveam :lineva) :components ((:file "lineva-test")) :perform (test-op (o c) (symbol-call :fiveam :run!)))
526
Common Lisp
.asd
16
30.125
55
0.687008
dzangfan/lineva
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
1169c072e218aed20e50a5bcb2676a7af36db3f87848000d0996294a5b8e95b6
41,691
[ -1 ]
41,711
buildrofli.lisp
slamko_rolfi/buildrofli.lisp
(ql:quickload :ltk) (load "rolfi.asd") (asdf:load-system :rolfi) (sb-ext:save-lisp-and-die "rolfi" :toplevel #'rolfi:main :executable t) (quit)
147
Common Lisp
.lisp
5
27.8
71
0.726619
slamko/rolfi
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
d4dbdc2360a46ac04aa291fee3ba085d2b4799929010b5fb124d8dfcad51831b
41,711
[ -1 ]
41,712
rolfi.lisp
slamko_rolfi/src/rolfi.lisp
(defpackage rolfi (:use :cl :ltk) (:export #:run)) (in-package :rolfi) (defvar app-list nil) (defun get-menu-selection (menu) (car (listbox-get-selection menu))) (defun get-bin-directories () (let ((path-var (uiop:getenv "PATH"))) (when path-var (mapcar (lambda (var) (concatenate 'string var "/")) (uiop:split-string path-var :separator ":"))))) (defun all-bins (bin-directories) (let (all-bin-names) (dolist (bin-path bin-directories all-bin-names) (if t (setq all-bin-names (append (mapcar 'pathname-name (uiop:directory-files bin-path)) all-bin-names)))))) (defun unique-bins (bins) (let (unique-bin-names) (dolist (bin-name bins unique-bin-names) (if (not (member bin-name unique-bin-names :test 'string=)) (setq unique-bin-names (cons bin-name unique-bin-names)))))) (defun get-best-matches (str match-list) (mapcan (lambda (list-str) (when (and (<= (length str) (length list-str)) (string= str (subseq list-str 0 (length str))) str) (list list-str))) match-list)) (defun sort-best-match (str match-list) (let ((best-match-list (get-best-matches str match-list))) (append (reverse best-match-list) (reverse (mapcan (lambda (list-str) (when (and (not (member list-str best-match-list)) (search str list-str)) (list list-str))) match-list))))) (defun entry-update-list (menu entry initial-app-list) (progn (listbox-clear menu) (listbox-append menu (setq app-list (if (= (length (text entry)) 0) initial-app-list (sort-best-match (text entry) initial-app-list)))) (listbox-select menu 0))) (defun bind-entry-events (menu entry initial-app-list eval-fun) (bind entry "<KeyPress>" (lambda (evt) (entry-update-list menu entry initial-app-list))) (bind entry "<KeyPress-Down>" (lambda (evt) (focus menu) (listbox-select menu 0))) (bind entry "<KeyPress-Return>" (lambda (evt) (funcall eval-fun (uiop:split-string (nth (get-menu-selection) app-list))) (uiop:quit)))) (defun autocomplete-selected-entry (menu entry f initial-app-list eval-fun) (progn (ltk:pack-forget entry) (listbox-select menu 0) (ltk:pack-forget menu) (setq entry (make-instance 'entry :master f :text (nth (get-menu-selection menu) app-list) :width 60)) (pack entry) (pack menu) (entry-update-list menu entry initial-app-list) (ltk:configure f :borderwidth 3 :height 50 :relief :sunken) (bind-entry-events menu entry initial-app-list eval-fun) (focus entry))) (defun choose-from-list (entry menu f entry-list treater) (let (initial-app-list) (setq app-list entry-list) (setq initial-app-list app-list) (listbox-append menu app-list) (listbox-select menu 0) (bind-entry-events menu entry initial-app-list treater) (bind menu "<space>" (lambda (evt) (autocomplete-selected-entry menu entry f initial-app-list treater))) (bind menu "<KeyPress-Up>" (lambda (evt) (when (= (get-menu-selection menu) 0) (focus entry)))) (bind menu "<KeyPress-Return>" (lambda (evt) (funcall treater (uiop:split-string (nth (get-menu-selection) app-list))) (uiop:quit))))) (defun run-entry (entry) (uiop:launch-program entry)) (defun app-launcher (entry menu f) (choose-from-list entry menu f (unique-bins (all-bins (get-bin-directories))) 'run-entry)) (defun lisp-eval (entry menu) (eval (read-from-string (text entry)))) (defun run (command) (with-ltk () (let* ((f (make-instance 'frame)) (entry (make-instance 'entry :master f :width 60 :takefocus t)) (menu (make-instance 'listbox :master f :width 60))) (pack f) (pack entry) (pack menu) (focus entry) (configure menu :background 'gray) (configure entry :background 'gray) (ltk:configure f :borderwidth 3 :height 50 :relief :sunken) (funcall (intern command) entry menu f)))) (run (car uiop:*command-line-arguments*))
4,803
Common Lisp
.lisp
145
23.937931
77
0.564309
slamko/rolfi
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
c9ae2139a40736471033a0293825569513b96147c40a343cd85ff3d4ac8f503b
41,712
[ -1 ]
41,713
powerctl.lisp
slamko_rolfi/srcs/powerctl.lisp
(in-package :rolfi) (defun powerctl (ent menu f) (choose-list-entry ent menu f '("sleep" "shutdown" "reboot") (lambda (entry &rest args) (cond ((string= entry "sleep") (uiop:launch-program "loginctl suspend")) ((string= entry "shutdown") (uiop:launch-program "loginctl poweroff")) ((string= entry "reboot") (uiop:launch-program "loginctl reboot"))) (uiop:quit)))) (defparameter *all-commands* (cons (string 'powerctl) *all-commands*))
523
Common Lisp
.lisp
16
26.1875
70
0.611111
slamko/rolfi
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
2aa37da54061753721421a25675b02dc569ee9552555c2c41da50d9b420a81ef
41,713
[ -1 ]
41,714
rolfi.lisp
slamko_rolfi/srcs/rolfi.lisp
(defpackage rolfi (:use :cl :ltk) (:export #:main #:choose-list-entry)) (in-package :rolfi) (defvar app-list nil) (defparameter *all-commands* (list(string 'lisp-eval))) (defun get-menu-selection (menu) (car (listbox-get-selection menu))) (defun get-best-matches (str match-list) (mapcan (lambda (list-str) (when (and (<= (length str) (length list-str)) (string-equal str (subseq list-str 0 (length str))) str) (list list-str))) match-list)) (defun sort-best-match (str match-list) (let ((best-match-list (get-best-matches str match-list))) (append best-match-list (mapcan (lambda (list-str) (when (and (not (member list-str best-match-list)) (search str list-str :test #'char-equal)) (list list-str))) match-list)))) (defun entry-update-list (menu entry initial-app-list) (progn (listbox-clear menu) (listbox-append menu (setq app-list (if (= (length (text entry)) 0) initial-app-list (sort-best-match (text entry) initial-app-list)))) (listbox-select menu 0))) (defun run-entry-fun (fun entry-id entry-widget fun-args) (progn (apply fun (append (if entry-id (nth entry-id app-list) (text entry-widget)) fun-args)))) (defun bind-entry-events (menu entry f initial-app-list eval-fun fun-args) (bind entry "<KeyPress>" (lambda (evt) (entry-update-list menu entry initial-app-list))) (bind entry "<KeyPress-Tab>" (lambda (evt) (autocomplete-selected-entry menu entry f initial-app-list eval-fun fun-args))) (bind entry "<KeyPress-Escape>" (lambda (evt) (uiop:quit))) (bind entry "<KeyPress-Down>" (lambda (evt) (listbox-select menu 0) (focus menu))) (bind entry "<KeyPress-Return>" (lambda (evt) (run-entry-fun eval-fun (get-menu-selection menu) entry fun-args)))) (defun autocomplete-selected-entry (menu entry f initial-app-list eval-fun fun-args) (progn (ltk:pack-forget entry) (listbox-select menu 0) (ltk:pack-forget menu) (setq entry (make-instance 'entry :master f :text (nth (get-menu-selection menu) app-list) :width 60)) (pack entry) (pack menu) (entry-update-list menu entry initial-app-list) (ltk:configure f :borderwidth 3 :height 50 :relief :sunken) (bind-entry-events menu entry f initial-app-list eval-fun fun-args) (focus entry))) (defun choose-list-entry (entry menu f entry-list eval-fun &rest fun-args) (let (initial-app-list) (setq app-list entry-list) (setq initial-app-list app-list) (listbox-append menu app-list) (listbox-select menu 0) (bind-entry-events menu entry f initial-app-list eval-fun args) (bind menu "<space>" (lambda (evt) (autocomplete-selected-entry menu entry f initial-app-list eval-fun fun-args))) (bind menu "<KeyPress-Escape>" (lambda (evt) (uiop:quit))) (bind menu "<KeyPress-K>" (lambda (evt) (listbox-select menu (+ (get-menu-selection menu) 1)))) (bind menu "<KeyPress-J>" (lambda (evt) (listbox-select menu (- (get-menu-selection menu) 1)))) (bind menu "<KeyPress-Up>" (lambda (evt) (when (= (get-menu-selection menu) 0) (focus entry)))) (bind menu "<KeyPress-Down>" (lambda (evt) (when (= (get-menu-selection menu) (- (length app-list) 1)) (focus entry)))) (bind menu "<KeyPress-Return>" (lambda (evt) (run-entry-fun eval-fun (get-menu-selection menu) entry fun-args))))) (defun lisp-eval (entry menu f &rest args) (bind menu "<KeyPress-Return>" (lambda (evt) (eval (read-from-string (text entry)))))) (defun get-rolfi-fun (fun) (concatenate 'string "rolfi::" fun)) (defun run-choose-command (ent menu f) (choose-list-entry ent menu f *all-commands* (lambda (entry) (funcall (read-from-string (get-rolfi-fun entry)) ent menu f)))) (defun run (command) (with-ltk () (let* ((f (make-instance 'frame)) (entry (make-instance 'entry :master f :width 60)) (menu (make-instance 'listbox :master f :width 60))) (pack f) (pack entry) (pack menu) (focus entry) (configure menu :background 'gray) (configure entry :background 'gray) (funcall command entry menu f)))) (defun main () (run (read-from-string (let ((command (or (car (uiop:command-line-arguments)) "run-choose-command"))) (get-rolfi-fun command)))))
5,151
Common Lisp
.lisp
155
24.483871
85
0.572301
slamko/rolfi
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
c2888b7fd09adefa47847ba81a9f80c5aa36cd377bc32a3b27908fe7dcbec906
41,714
[ -1 ]
41,715
applauncher.lisp
slamko_rolfi/srcs/applauncher.lisp
(in-package :rolfi) (defun get-bin-directories () (let ((path-var (uiop:getenv "PATH"))) (when path-var (mapcar (lambda (var) (concatenate 'string var "/")) (uiop:split-string path-var :separator ":"))))) (defun all-bins (bin-directories) (let (all-bin-names) (dolist (bin-path bin-directories all-bin-names) (if t (setq all-bin-names (append all-bin-names (mapcar 'pathname-name (uiop:directory-files bin-path)))))))) (defun unique-bins (bins) (let (unique-bin-names) (dolist (bin-name bins unique-bin-names) (if (not (member bin-name unique-bin-names :test 'string=)) (setq unique-bin-names (cons bin-name unique-bin-names)))))) (defun run-entry (entry &rest args) (uiop:launch-program entry) (uiop:quit)) (defun app-launcher (entry menu f) (choose-list-entry entry menu f (remove-duplicates (all-bins (get-bin-directories)) :test #'string=) 'run-entry)) (defparameter *all-commands* (cons (string 'app-launcher) *all-commands*))
1,090
Common Lisp
.lisp
33
27.242424
74
0.632731
slamko/rolfi
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
f8895942d7f906f1914e4a7f32c1a4d1229f382ea41cffea04febc984ef0e1c4
41,715
[ -1 ]
41,716
rolfi.asd
slamko_rolfi/rolfi.asd
(asdf:defsystem "rolfi" :author "Viacheslav Chepelyk-Kozhin" :description "Lisp driven apllication launcher and more" :version "0.1.2" :license "GPLv3" :depends-on (:ltk :uiop) :components ((:module "srcs" :components ((:file "rolfi") (:file "powerctl") (:file "pass") (:file "applauncher")))))
390
Common Lisp
.asd
12
23.583333
58
0.547619
slamko/rolfi
0
0
0
GPL-3.0
9/19/2024, 11:50:42 AM (Europe/Amsterdam)
71dde3ecb3c28a8a4fd42605697740286f2bf137c35be64aecf2919b0b263181
41,716
[ -1 ]
41,738
copier.lisp
dzangfan_copier_lisp/copier.lisp
(defconstant layer-inactive-state :inactive) (defconstant layer-active-state :active) (defparameter *no-available-function* nil) (eval-when (:compile-toplevel :load-toplevel :execute) (defun activeness-descriptor-p (thing) (or (handler-case (destructuring-bind (operation layer-name) thing (and (or (eq layer-active-state operation) (eq layer-inactive-state operation)) (symbolp layer-name) thing)) (t () nil)) (and (symbolp thing) `(,layer-active-state ,thing)))) (defun standardize-activeness-descriptors (activeness-descriptors) (cond ((symbolp activeness-descriptors) `((,layer-active-state ,activeness-descriptors))) ((activeness-descriptor-p activeness-descriptors) (list activeness-descriptors)) (t (let ((maybe-standardized-descriptors (mapcar #'activeness-descriptor-p activeness-descriptors))) (if (every #'identity maybe-standardized-descriptors) maybe-standardized-descriptors (error "Unacceptable activeness-descriptors ~A" activeness-descriptors))))))) (defparameter *active-layers* '(t) "Active layer names") (defun next-active-layers (std-activeness-desc &optional (active-layers *active-layers*)) "Compute next active layers based on `*active-layers*' and STD-ACTIVENESS-DESC. See `standardize-activeness-descriptors' for more information about the parameter." (loop :with next-layers := (reverse active-layers) :for desc :in std-activeness-desc :do (destructuring-bind (operation layer-name) desc (let ((clean-layers (remove layer-name next-layers))) (cond ((eq layer-active-state operation) (push layer-name clean-layers)) ((not (eq layer-inactive-state operation)) (error "Unstandardized activeness descriptors: ~S" std-activeness-desc))) (setf next-layers clean-layers))) :finally (return (reverse next-layers)))) (defmacro with (activeness-descriptors &body body) "Activate or inactivate layers described by ACTIVENESS-DESCRIPTORS, which is in one of following forms: - a layer-descriptor ;; Equal to a list which has only one ;; layer-descriptor - a list of layer-descriptor where layer-descriptor is one of following form: - symbol ;; Equal to (:active symbol) - (:active symbol) - (:inactive symbol) Macro `with' will standardize ACTIVENESS-DESCRIPTORS to a list of list like ((:active L1) (:active L2) (:inactive B1)) then activate or inactivate particular layers from left to right. Specifically, for element (:active <layer>) <layer> will be activated and for (:inactive <layer>) <layer> will be inactivate. As for example above, the executive sequence is 1. activate L1 2. activate L2 3. inactivate B1 BODY will be executed under the activeness specified by ACTIVENESS-DESCRIPTORS." (let ((descs (standardize-activeness-descriptors activeness-descriptors))) `(let ((*active-layers* (next-active-layers ',descs))) ,@body))) (defun resolve-functions (available-functions &optional (active-layers *active-layers*)) "Given ACTIVE-LAYERS, trim unrelated functions and sort functions by order of its corresponding layer in ACTIVE-LAYERS. AVAILABLE-FUNCTIONS is a `alist' whose first element is a name of layer and second element is a function object. Return a `alist' in the same form with AVAILABLE-FUNCTIONS." (let ((order-table (make-hash-table :test #'eq))) (loop :for layer :in active-layers :for i :from 0 :do (setf (gethash layer order-table) i)) (sort (loop :for cell :in available-functions :if (gethash (car cell) order-table) :collecting cell) #'< :key (lambda (cell) (gethash (car cell) order-table))))) (defun apply-with-context (function-symbol &rest arguments) "Apply functions restored in property `layered-functions' of FUNCTION-SYMBOL by ARGUMENTS, in context of `*active-layers*'." (let* ((args (and arguments (apply #'list* arguments))) (available-functions (get function-symbol 'layered-functions)) (function-cells (resolve-functions available-functions)) (functions (mapcar #'cdr function-cells))) (loop :with cur-proceed := (lambda (default) default) :for cur-function :in functions :do (let ((proceed cur-proceed) (function cur-function)) (setf cur-proceed (lambda (default) (declare (ignore default)) (apply function proceed args)))) :finally (return (funcall cur-proceed *no-available-function*))))) (defun remove* (element list &key (key #'identity) (test #'eql)) "Like standard function `remove' except only operating on `list' and returning second value to indicate whether the invocation removed item actually." (loop :with removed-p := nil :for e :in list :if (funcall test element (funcall key e)) :do (setf removed-p t) :else :collecting e :into clean-list :finally (return (values clean-list removed-p)))) (defun install-layered-function (function-symbol layer function &optional force-p) "Install a layered function named FUNCTION-SYMBOL in LAYER with FUNCTION. A warning will be raised if there is a function in LAYER called FUNCTION-SYMBOL. Pass FORCE-P as `t' to prevent it." (let ((current-functions (get function-symbol 'layered-functions))) (multiple-value-bind (clean-functions removed-p) (remove* layer current-functions :key #'car :test #'eq) (when (and (not force-p) removed-p) (warn "Function ~A in layer ~A has been defined" function-symbol layer)) (setf (get function-symbol 'layered-functions) (cons (cons layer function) clean-functions))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun tagged-list-p (lst) "If LST is a `list' which has at least one element, return the first element. `nil' otherwise." (handler-case (destructuring-bind (tag &rest _) lst (declare (ignore _)) tag) (t () nil))) (defun extract-variables-from-lambda-list (lambda-list) "Extract variables from LAMBDA-LIST, which is a ordinary lambda list. Return a property list, which has four properties: 1. :required Positional arguments (List of symbol) 2. :key Keyword arguments (Property list) 3. :rest Rest argument (Symbol) 4. :optional Optional argument (Symbol)" (macrolet ((assert* (pred) `(assert ,pred (lambda-list) "~S is not a ordinary lambda list" lambda-list)) (field (name) `(getf result ,name))) (loop :with cur-ctx := :required :and result := () :for elt :in lambda-list :if (eq '&aux elt) :return result :else :do (ecase cur-ctx (:required (assert* (symbolp cur-ctx)) (if (member elt '(&optional &rest &key) :test #'eq) (setf cur-ctx elt) (push elt (field :required)))) (&optional (cond ((symbolp elt) (setf (field :optional) elt)) (t (assert* (and elt (listp elt))) (setf (field :optional) (car elt)))) (setf cur-ctx 'optional-end)) (optional-end (assert* (member elt '(&rest &key) :test #'eq)) (setf cur-ctx elt)) (&rest (assert* (symbolp elt)) (setf (field :rest) elt cur-ctx 'rest-end)) (rest-end (assert* (eq '&key elt)) (setf cur-ctx elt)) (&key (multiple-value-bind (keyword-name variable-name) (cond ((eq '&allow-other-keys elt) (return-from extract-variables-from-lambda-list result)) ((symbolp elt) (values (intern (symbol-name elt) :keyword) elt)) (t (assert* (and elt (listp elt))) (let ((first (car elt))) (cond ((symbolp first) (values (intern (symbol-name first) :keyword) first)) (t (assert* (and (list first) (= 2 (length first)))) (apply #'values first)))))) (let ((kwd-args (field :key))) (setf (getf kwd-args keyword-name) variable-name) (setf (field :key) kwd-args))))) :end :finally (progn (when (field :required) (setf (field :required) (reverse (field :required)))) (return result))))) (defun reform-argument-list (lambda-list) "Return a invocation except the operator. For example, for following lambda lists () (a b c) (a b &optional c) (a b &rest c) (a b &key c) following applicable lists will be returned correspondingly. (nil) (a b c nil) (a b c nil) (a b c) (a b (:c c))" (let* ((variables (extract-variables-from-lambda-list lambda-list)) (required (getf variables :required)) (optional (getf variables :optional)) (rest (getf variables :rest)) (key (getf variables :key)) (required* (append required (and optional (list optional))))) (if (null rest) (append required* (list key)) (append required* key (list rest))))) (defun create-layered-lambda (name lambda-list) "Create source code of layered function." (let ((args (reform-argument-list lambda-list))) `(lambda ,lambda-list (apply-with-context ',name ,@args)))) (defun deflun-aux (name lambda-list clauses) "Define layered functions named NAME with LAMBDA-LIST. CLAUSES is any number of forms which has one of following structures: 1. (in-layer <layer-name> <function-body>) 2. (note-that <doc-string>) every clause (1.) defines a function in layer <layer-name>, and all of them in CLAUSES has the same signature (NAME . LAMBDA-LIST). Although `deflun-aux' can be called in several times, clause two and three should only appear once, or otherwise a warning will be signaled. (2.) clause define a combinator of the layered function. Since a single invocation of a layered function may yield many returning value corresponding to activated layers, the default is every returning value will be returned as a `list'. You can modify this behavior by adding a combinator or collector in the second type of clause: <variable-name> will be bound to the resulting list and <result-producer> yield the real result. The third documentation clause is a equivalent of docstring of `defun'." (loop :with lambda-list* := (cons 'proceed lambda-list) :and declaration := () :and declaration-end := nil :for clause :in clauses :for tag := (tagged-list-p clause) :if (not tag) :do (error "Invalid clause for `deflun': ~S" clause) :else :collecting (ecase tag (in-layer (setf declaration-end t) (destructuring-bind (_ layer &body body) clause (declare (ignore _)) `(install-layered-function ',name ',layer (lambda ,lambda-list* ,@declaration (flet ((proceed (&optional default) (funcall proceed default))) ,@body))))) (note-that (destructuring-bind (_ docstring) clause (declare (ignore _)) `(progn (when (documentation ',name 'function) (warn "Redefined documentation of ~A" ',name)) (setf (documentation ',name 'function) ,docstring)))) (declare (if declaration-end (warn "Declaration after layered function will be ignored") (push clause declaration)) nil)) :into transformed-clauses :finally (return `(progn ,@transformed-clauses (unless (get ',name 'layered-function-p) (setf (symbol-function ',name) ,(create-layered-lambda name lambda-list) (get ',name 'layered-function-p) t))))))) (defun layered-fmakunbound (symbol) "Clean properties created by `deflun'." (when (get symbol 'layered-function-p) (fmakunbound symbol)) (macrolet ((discard (indicator) `(remf (symbol-plist symbol) ,indicator))) (discard 'layered-function-p) (discard 'layered-functions))) (defmacro deflun (name lambda-list &body clauses) "Define a layered function named NAME. NAME and LAMBDA-LIST have the same meaning with `defun'. Note that LAMBDA-LIST must be an ordinary lambda list, like what `defun' is using. CLAUSES are several forms which has one of following form: 1. (declare &rest declare-descriptors) 2. (note-that docstring) 3. (in-layer layer-name &body body) `declare' has the same meaning with `defun', and note that ALL declarations must be placed before `in-layer' clause. `note-that' specifies docstring of the function, which should be called only once. `in-layer' defines a new function in specific layer. A local function `proceed' is available in body of layered function: (proceed &optional default) to invoke functions before current layer. A default value will be returned if no more functions. For example: (deflun greeting (&optional (name \"friend\")) (declare (ignorable name)) (in-layer t (format nil \"Hello, ~A\" name)) (in-layer emphasis (format nil \"~A!!!\" (proceed))) (note-that \"Give a greeting\")) Following properties will be used on symbol NAME: 1. `layered-function-p' a flag indicating whether `symbol-function' is set 2. `layered-functions' a list of defined functions in separate layers Use `layered-fmakunbound' to clean up this properties." (deflun-aux name lambda-list clauses)) (defmacro in-layer (name &body body) "Create a function in layer NAME. This macro must be invoked in context of `deflun'." (declare (ignore name body)) (error "`in-layer' must be called in context of `deflun'")) (defmacro note-that (string) "Specify usage of a layered function. This macro must be invoked in context of `deflun', or nothing will happen." (declare (ignore string)) nil)
15,446
Common Lisp
.lisp
324
36.83642
80
0.603438
dzangfan/copier.lisp
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
2a781a8e9c6d49362cae2a284fbc5514bb4cb776b76418bc4a6614ffadc66fd6
41,738
[ -1 ]
41,755
rsa.lisp
joelcanepa_lisp-rsa/rsa.lisp
(in-package :rsa) ;; definition of rsa parameters (setq p nil) (setq q nil) (setq n nil) (setq phi-n nil) (setq e nil) (setq d nil) ;; Generates a pseudo random number of n bits (between zero and 2^n bits) (defun random-n-bits (bits) (random (expt 2 bits) (make-random-state t))) ;; returns (with an error probability of 2^-100) a prime number ;; by NIST FIPS 186-5 Digital Signature Standard (defun generate-prime (bits) ;; k = number of miller rabin test rounds to perform (setq k 0) (cond ((eq bits 512) (setq k 7)) ((eq bits 1024) (setq k 4)) ((eq bits 1536) (setq k 3)) ((eq bits 2048) (setq k 2)) ;; ! rsa 4096 not defined in NIST FIPS 186-5 ((eq bits 4096) (setq k 1)) ;; invalid key length (t (progn (format t "Invalid key length. Choose one of the following: 512 - 1024 - 1036 - 2048 - 4096~%") (sb-ext:quit))) ) ;; loops until a number passes the miller rabin primality test (loop (setq num (random-n-bits bits)) (when (eq (miller-rabin num k) num) (return num)))) ;; calculates parameter n (defun calc-n (p q) (* p q)) ;; calculates parameter phi-n using carmichael's function ;; assuming that p and q are prime numbers, then the function can be ;; calculated as the least common multiple between p-1 and q-1 (defun fun-carmichael (p q) (lcm (- p 1) (- q 1))) ;; calculates parameter e (the public key) ;; seeks a random number that satisfies: ;; 1<e<phi-n where e and phi-n are coprime numbers (defun calc-e (phi-n) (loop (setq e (+ (random (- phi-n 1) (make-random-state t)) 1)) (when (eq (coprime phi-n e) t) (return e)))) ;; calculates parameter d (the private key) ;; finds the modular inverse 'd' of e = 1 mod phi-n (defun calc-d (phi-n e) (inverse e phi-n)) ;; Calculates all rsa parameters (defun generate-keys (bits) (format t "Generating rsa keys...~%") (setq p (generate-prime bits)) (setq q (generate-prime bits)) (setq n (calc-n p q)) (setq phi-n (fun-carmichael p q)) (setq e (calc-e phi-n)) (setq d (calc-d phi-n e)) (format t "Key generation completed.~%")) ;; rsa encryption (defun encrypt (m e n) (expt-mod m e n)) ;; rsa decryption (defun decrypt (c d n) (expt-mod c d n)) ;; outputs all rsa parameters (defun print-rsa () (format t "p: ~A~%" p) (format t "q: ~A~%" q) (format t "n: ~A~%" n) (format t "phi-n: ~A~%" phi-n) (format t "e: ~A~%" e) (format t "d: ~A~%" d))
2,537
Common Lisp
.lisp
75
29.693333
106
0.629218
joelcanepa/lisp-rsa
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
b078891f76fef95b89bb859cf315823f40e040121b4fa3472630b9453845a40d
41,755
[ -1 ]
41,756
cl-primality.lisp
joelcanepa_lisp-rsa/cl-primality.lisp
(in-package :cl-primality) ;; @\section{Introduction} ;; @CL-Primality is a small library that can test whether integers are prime or ;; not, and perform common actions that require that knowledge. As of now, the ;; implementation is based on the Miller-Rabin probabilistic primality ;; algorithm. It is written with some speed considerations in mind. ;; @\section{Utilities} ;; The sort of number theoretical calculations involved in primality testing ;; typically need some support for modular arithmetic. We introduce the ;; functions <<*-mod>> and <<expt-mod>>, which perform multiplication and ;; exponentiation modulo some number. ;;<<>>= (defun *-mod (n m md) "Multiply N by M, modulo MD." (mod (* n m) md)) (defun expt-mod-ref (b e md) "A reference implementation, do not use except for testing purposes." (mod (expt b e) md)) ;;<<>>= (defun expt-mod (b e md &optional (tot 1)) "Raise B to the power of E, modulo MD \(leave TOT as 1)." (declare (type integer e)) (cond ((= e 0) tot) ((oddp e) (expt-mod (mod (* b b) md) (ash e -1) md (mod (* tot b) md))) (t (expt-mod (mod (* b b) md) (ash e -1) md tot)))) ;; @According to Euler's theorem, $a^b \mod m = a^{b \mod \phi(m)} \mod m$, ;; where $phi(m)$ is Euler's totient function equal to the number of integers ;; coprime to $m$ in the range ;; $[1,m]$.\footnote{https://stackoverflow.com/questions/11448658/modular-exponentiation} ;; For a prime number, $\phi(m) = m$. Euler's totient product formula says ;; that\footnote{https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler.27s_product_formula}: ;; \[ ;; \phi(n) = n \prod_{p|n}\left(1 - \frac 1 p \right) ;; \] ;; ... where the product is over all integers that divide $n$ including $1$ and $p$. This requires ;; (defun eulers-totient (n) ;; (if (and nil (primep n)) ;; n ;; ;; Fall back to a slow method of calculating ;; (let ((tot 0)) ;; (iter (for i :below n) ;; (unless (> (gcd i (mod n (if (> i 0) i n))) 1) ;; (incf tot)) ;; (finally (return tot)))))) ;; (defun %expt-mod (b e md) ;; "Raise B to the power of E, modulo MD \(leave TOT as 1)." ;; (declare (type integer e)) ;; (let ((e (mod e (eulers-totient md)))) ;; (expt-mod b e md))) ;; @\section{Primality Algorithms} ;; @\subsection{The Miller-Rabin Algorithm} ;; The Miller-Rabin algorithm is a common implementation for primality testing. ;; It performs a probabilistic check for primality that gives guarantees on the ;; maximum likelihood of a false positive (a number identified as prime when it ;; is actually composite) and never gives false negatives (a number identified ;; as composite whin it is in fact prime). This value is set via the optional ;; parameter <chance-of-error>. By default, <chance-of-error> is set to a very ;; small number which can slow things down if you don't need that strong of a ;; guarantee. ;;<<,2>>= ;; the original cl-primality function was modified to receive the number of rounds to ;; perform the miller rabbin test, instead of the error probability (defun miller-rabin (n &optional (iterations 10)) "Miller-Rabin probabilistic primality test: Checks if N is prime with the chance of a false positive less than CHANCE-OF-ERROR. This algorithm never gives false negatives." ;; the probability of error (false positive) is (ceiling (log chance-of-error 1/4)) (declare (optimize (speed 3) (debug 0))) (cond ((= n 1) nil) ((= n 2) n) ;; n-iter defines the number of iterations or passes of miller rabin test to perform (t (let ((n-iter iterations)) (labels ((rec (n n-iter) (cond ((= n-iter 0) n) (t (and (miller-rabin-pass n (1+ (random (- n 1)))) (rec n (- n-iter 1))))))) (rec n n-iter)))))) (defun miller-rabin-pass (n a) "Performs one 'pass' of the Miller-Rabin primality algorithm." (declare (optimize (speed 3) (debug 0)) (inline miller-rabin-pass)) (labels ((decompose-val (n s) (cond ((or (= n 0) (oddp n)) (values n s)) (t (decompose-val (/ n 2) (1+ s)))))) (multiple-value-bind (d s) (decompose-val (- n 1) 0) (cond ((= 1 (expt-mod a d n)) n) ((do* ((a-loc (expt-mod a d n) (expt-mod a-loc 2 n)) (i 0 (1+ i)) (ret (= (- n 1) a-loc) (= (- n 1) a-loc))) ((or ret (= i s)) (if (/= i s) t))) n) (t nil))))) ;; added coprime.lisp function form the LisPrime package ;; from D. Radisavljević (defun coprime (firstnum secondnum) (SETQ numcheck 0) (if (eq (gcd firstnum secondnum) 1) (setQ numcheck 1) (setQ numcheck 0)) (if (eq numcheck 1) (return-from coprime t) (return-from coprime nil) ) )
4,992
Common Lisp
.lisp
105
41.847619
101
0.613851
joelcanepa/lisp-rsa
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
cf1a1f504061d7bed3b591f7d636068128f5e19cea13be9686ef841ec3d06262
41,756
[ -1 ]
41,757
rsa-test.lisp
joelcanepa_lisp-rsa/rsa-test.lisp
(defpackage :rsa-test (:use :cl :rsa)) (in-package :rsa-test) ;; para la longitud de la clave puede elegir entre ;; 512 - 1024 - 1536 - 2048 ;(rsa::generar-claves 2048) ;(rsa::print-rsa) ;(generar-claves 2048) ;(print-rsa) ;(setq nro #x097aed9dad0fe4f60ca0c02d80782908175bab665e8989601d39cf626a00ca92) ;(format t "~A = ~X" nro nro) ;(setq nroc (encrypt nro e n)) ;(setq nrod (decrypt nroc d n)) ;(format t "original: ~X~%cifrado: ~X~%descifrado: ~X~%" nro nroc nrod) ;(setq firma #x8077E1A14855D33AA866950A1DB4B13A65802C04E83569199D0F0E2B600CD5B53FDDC0ED43A42226BF87C8E8CEE3B8088CAD48B69B8B38A7F450B89233280C61DF2B9A1C80E56A0D1619B797B7075DDA2F8F601C2D966AB06FAEDF626DA5797E988E40192E602CC3CF1110145D83BBA79F6B83C15B26F9B5E9FB9BFA331F762D7D776D1A69B5D76F91283F106D8D4DD15DBCE96D2485A30C440B33513418661AA9992F5457A5EC6ED9AD96EF647DD98D13BAB67E7984DE0E1455EF15F046C697FB2B1B5A8CA307D2F27A0E94A50211D7487098614E6A76C1788C815E2EC5223312356A1DD4606146EDCAD23AB911CE098C65BF8F37A18BECCFD4B5CE97D8070635684D765738C76FAC5C2634E1B6C272EC77EFDFA81BCE81DF1061D292A7BAC957DBA770DC6A1D378B1D589657378B9A4FD933E7EB44EF8639600098DE841AF76ACC4A579DF6410B702579ADED08BDAEFD137A5E42660D940B43B6C965094A2648B9033A66670C728B159D48DEA5C48A8701DEC43CD1D873EA48F41BE60B00E86EFAC8879D2D8897120C5F19E89D5E47BA79D73DEC63CBDC964BD70ABD5BFCC64781E25DD4B5FDC6F7176AC60352A7F4F288925B1399EAFAF917067D6E447C1F60888A6D1C240565BEB10A90892C09FD5D5B1E911E162A982E9D5B92009B44F299020CA164A9B87DE0F41D9345C005F8D23E22431A5E947900735BFF02FD257) ;(setq command (concatenate 'string "echo " (write-to-string firma :base 16) " > hola.firma")) ;(format t "~A~%" command) ;(format t "~X~%" (parse-integer (write-to-string firma :base 16) :radix 16))
1,744
Common Lisp
.lisp
18
93.888889
1,040
0.870251
joelcanepa/lisp-rsa
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
b1d751d2b9fc31d7e251dacd5563e8f7740ccb92041a929e12785c704a9af840
41,757
[ -1 ]
41,758
mod.lisp
joelcanepa_lisp-rsa/mod.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: mod.lisp ;;;; Purpose: Modular arithmetic. ;;;; Author: R. Scott McIntire ;;;; Date Started: Aug 2003 ;;;; ;;;; $Id: mod.lisp,v 1.6 2003/10/21 20:59:44 rscottmcintire Exp $ ;;;; ************************************************************************* (in-package rsm.mod) (defun plus (mod &rest args) "Add <args> in Mod <mod> arithmetic. Example: (rsm.mod:+ 3 3 5) 2" (reduce #'(lambda (x y) (mod (cl:+ (mod x mod) (mod y mod)) mod)) args :initial-value 0)) (defun mult (mod &rest args) "Multiply <args> in Mod <mod> arithmetic. Example: (rsm.mod:* 3 2 5) 1" (reduce #'(lambda (x y) (mod (cl:* (mod x mod) (mod y mod)) mod)) args :initial-value 1)) (defun ppow (b n p) "Raise <b> to the <n>th power in the field Z mod <p>. Here <p> must be prime. Example: (rsm.mod:ppow 12 100 7) 2" (^ b n p :e-phi (1- p))) (declaim (ftype (function (integer integer integer &key (:e-phi integer)) integer) ^)) (defun ^ (b n mod &key (e-phi 0)) "Raise <b> to the <n>th power mod <mod> by repeated squaring. If <e-phi> is non zero, use the generalization of Fermat's little theorem: b^phi(mod) = 1 mod mod, when the gcd of b and mod is 1. The theorem is used to replace b^n with b^r where r = mod(n, phi(mod)) and phi is the Euler Phi function. Example: (rsm.mod:^ 213317 527131763 173) 170 Example: (rsm.mod:^ 7 2134145213317 33 :e-phi 20) 28" (let ((bmod (mod b mod))) (when (= bmod 0) (return-from ^ 0)) (when (= bmod 1) (return-from ^ 1)) (when (and (/= e-phi 0) (= (gcd mod bmod) 1)) (setf n (mod n e-phi))) (loop :with prd = 1 :with pow = bmod :with nn = n :while (> nn 0) :if (oddp nn) :do (setf prd (mod (mult mod prd pow) mod)) (when (= prd 0) (return 0)) (setf nn (/ (1- nn) 2)) (setf pow (mult mod pow pow)) :else :do (setf nn (/ nn 2)) (setf pow (mult mod pow pow)) :finally (return prd)))) (defun euler-phi (n) "Computes the Euler Phi function of <n>. Example: (rsm.mod:euler-phi 15) 8" (let ((factors (factors n))) (reduce #'cl:* (mapcar #'(lambda (p) (- 1 (/ p))) factors) :initial-value n))) (defun %get-powers (k n) "Get the list of the factor <k> that appears in <n>." (loop :with nn = n :with facts = nil :while (= (mod nn k) 0) :do (setf nn (/ nn k)) (push k facts) :finally (return facts))) (defun %get-powers-of-2-3 (n) "Get the list of the primes 2 and 3 that occur in <n>." (let ((2-facts (%get-powers 2 n)) (3-facts (%get-powers 3 n))) (nconc 2-facts 3-facts))) (defun factors (n &key (no-dups t)) "Computes and returns a list of the primes factors of <n>. If <no-dups> is true, then no multiple entries of a factor are returned. Example: (rsm.mod:factors 100) (2 5) Example: (rsm.mod:factors 100 :no-dups nil) (2 2 5 5)" (let ((2-3-facts (%get-powers-of-2-3 n))) (let ((other-facts (loop :with nn = (/ n (apply #'cl:* 2-3-facts)) :with m = (isqrt nn) :with k = 5 :with factors = nil :with skip fixnum = 2 :while (<= k m) :do (if (= (mod nn k) 0) (progn (setf nn (do ((n1 nn (/ n1 k))) ((> (mod n1 k) 0) n1) (push k factors))) (setf m (isqrt nn))) (progn (incf k skip) (if (= skip 2) (setf skip 4) (setf skip 2)))) :finally (return (nreverse (if (> nn 1) (cons nn factors) factors)))))) (if no-dups (delete-duplicates (nconc 2-3-facts other-facts)) (nconc 2-3-facts other-facts))))) (defun %get-gcd-pair (ms flip) (let ((u 1) (v (- (pop ms)))) (loop :until (null ms) :do (psetq u v v (cl:- u (cl:* (pop ms) v)))) (if flip (list v u) (list u v)))) (defun gcd-with-pair (n m) "Returns two values: The gcd of <n> and <m>, and the list (r s) such that r * n + s * m = gcd(n,m). Example: (rsm.mod:gcd-with-pair 15 21) 3 (3 -2)" (let* ((max (max n m)) (min (min n m)) (flip (when (= min n) t))) (let (ms (qs (list min max))) (loop :with p = max :with q = min :with r = 1 :do (multiple-value-bind (m1 r1) (truncate p q) (setf p q) (setf q r1) (setf r r1) (if (= r 0) (return) (progn (push r qs) (push m1 ms))))) (if (null ms) (values min (if flip (list 1 0) (list 0 1))) (values (pop qs) (%get-gcd-pair ms flip)))))) (defun has-inverse-p (a n) "Does <a> have an inverse in Z mod <n>? Example: (rsm.mod:has-inverse-p 10 100) nil" (= (gcd a n) 1)) (defun inverse (a n &optional (error nil) (not-invert-return 0)) "Finds the inverse of <a> in Z mod <n>. If <a> inverse does not exist, an error is thrown if <error> is non nil. If <error> is nil, then <not-invert-return> is returned. Example: (rsm.mod:inverse 21 100) 81" (let ((gcd (gcd a n))) (if (= gcd 1) (multiple-value-bind (r pairs) (gcd-with-pair a n) (declare (ignore r)) (mod (car pairs) n)) (if error (error "rsm.mod:inverse: First arg, ~s, is not invertible in Z mod ~s." a n) not-invert-return)))) (defun solve-congruence-system (as ms) "Use the Chinese remainder theorem to solve for x, the system of congruences: x = as_i mod ms_i. The moduli, <ms>, must all be pairwise relatively prime. x will be unique in Z mod (product of <ms>'s). Example: (rsm.mod:solve-congruence-system '(1 2 3) '(2 3 5)) 23" (unless (= (length as) (length ms)) (error "rsm.mod:solve-congruence-system: Congruence values, ~s, are not the same length as the moduli, ~s~%" as ms)) (loop for (mod . mod-rest) on ms do (loop for modi in mod-rest do (unless (= (gcd mod modi) 1) (error "rsm.mod:solve-congruence-system: Modulus ~s and ~s are not relatively prime.~%" mod modi)))) (let ((M (reduce #'cl:* ms)) (x 0)) (loop for m in ms as a in as do (let* ((Mi (/ M m)) (Ni (inverse Mi m))) (setf x (plus M x (mult M (mod a m) Mi Ni))))) x)) (defun rational-approx (number &optional (epsilon nil)) "Find a simple rational approximation to <number> within <epsilon>. Example: (rsm.mod:rational-approx pi 0.0000003) 355/113" (let ((last-approx (rational number))) (flet ((rat-approx (rat) (let ((num (numerator rat)) (den (denominator rat))) (if (or (= num 1) (= den 1)) rat (multiple-value-bind (gcd pair) (gcd-with-pair num den) (declare (ignore gcd)) (/ (cadr pair) (- (car pair)))))))) (let ((approx (if (rationalp number) (rat-approx number) (rat-approx (rational number))))) (if epsilon (progn (loop :until (or (= approx last-approx) (>= (abs (- approx number)) epsilon)) :do (setf last-approx approx) (setf approx (rat-approx approx))) last-approx) (progn (setf approx (rat-approx approx)) (loop :until (= approx last-approx) :do (setf last-approx approx) (setf approx (rat-approx approx))) approx))))))
8,526
Common Lisp
.lisp
241
25.738589
79
0.483347
joelcanepa/lisp-rsa
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
746c072315e232bd8d02acea940880e3be77a917c0c6f9c64b35a17776f954b0
41,758
[ -1 ]
41,759
packages.lisp
joelcanepa_lisp-rsa/packages.lisp
(in-package :cl) (defpackage rsm.mod (:use :cl) (:export :inverse) (:documentation "This package contains functions to do modular arithmetic")) (defpackage :cl-primality (:use :cl) (:export :primep :miller-rabin :expt-mod :coprime) (:documentation "This package contains functions to do the miller rabin primality test and modular exponentiation")) (defpackage :rsa (:use :cl :rsm.mod :cl-primality) (:export :generar-claves :print-rsa :p :q :n :phi-n :e :d :encrypt :decrypt) (:documentation "This package contains an implementation of asymmetric rsa encryption."))
719
Common Lisp
.lisp
23
23.695652
92
0.616279
joelcanepa/lisp-rsa
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
2e19ea91d0c35b297be886c1932b6ba6eb1bcbf8dd61e5f414814c74565c96ca
41,759
[ -1 ]
41,780
conditions.lisp
DrBluefall_warfare/src/conditions.lisp
(defpackage :warfare.conditions (:use :cl) (:export :warfare-error)) (in-package :warfare.conditions) (define-condition warfare-error (error) ((what :initarg :what :initform "An unspecified error has occurred" :reader warfare-error-what)) (:documentation "An error signaled from Warfare.") (:report (lambda (c stream) (format stream "WARFARE-ERROR: ~a" (warfare-error-what c))))) (define-condition warfare-error-http (warfare-error) ((body :initarg :body :reader warfare-error-http-body :documentation "The body of the response returned") (status :initarg :status :reader warfare-error-http-status :documentation "The status code of the response.") (uri :initarg :uri :reader warfare-error-http-uri :documentation "The request the URI was sent to.")) (:documentation "An error involving making an HTTP request to discord has occurred."))
893
Common Lisp
.lisp
22
37.090909
88
0.733026
DrBluefall/warfare
0
0
0
LGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
2939e061265512d0e8abd1ec45e999befdacaabb2a0fdb01ee3565a51defe231
41,780
[ -1 ]
41,781
lib.lisp
DrBluefall_warfare/src/lib.lisp
(defpackage :warfare (:use :cl :warfare.constants :warfare.gateway :warfare.classes.gateway :warfare.classes.bot) (:export :begin-event-loop)) (in-package :warfare) (define-condition connection-broken (serious-condition) () (:documentation "A warning signaling a broken websocket connection.")) (defun begin-event-loop (bot &optional (callback #'(lambda (_) #|no-op|#))) "Begin recieving events from Discord, using the token from `BOT'. This function does a few things: - It first waits for `WARFARE.CLASSES.GATEWAY:<EVENT-HELLO>' to be recieved. `WARFARE.CLASSES.GATEWAY:<EVENT-HELLO>' provides the `HELLO-HEARTBEAT-INTERVAL', which we need to... - ...spin up a heartbeat thread, which sends continuous `WARFARE.CLASSES.GATEWAY:<EVENT-HEARTBEAT>'s over the gateway. - After heartbeating is set up, it sends `WARFARE.CLASSES.GATEWAY:<EVENT-IDENTIFY>' over the gateway. NOTE: `CALLBACK' should block for as little as possible. Ideally, you'd use it to spin up another thread that does actual event processing." (declare (type <bot> bot)) ;; FIRST: Set up the websocket info & connect to discord. (set-websocket-info bot) (connect-to-discord bot) ;; SECOND: Set up a constant LOOP, based on continuously calling `QUEUES:QPOP' continuously. (loop with wsinfo = (bot-ws-info bot) with event-queue = (bot-ws-event-queue wsinfo) with conn = (bot-ws-connection wsinfo) with waiting-for-heartbeat-ack = nil for event = (queues:qpop event-queue :empty) when (and (not (eq event :empty)) (not (eq (wsd:ready-state conn) :closed))) do (progn (typecase event (<event-hello> (bt:make-thread #'(lambda (&rest args) (loop with interval = (hello-heartbeat-interval event) for first-beat = (* interval (random 1.0d0 #|The required 'jitter' for the first heartbeat|#)) then nil when waiting-for-heartbeat-ack ;; This connection is dead and/or "zombified". ;; Signal a condition to close & attempt reconnect. ;; ;; TODO: Actually *implement* reconnection. do (progn (wsd:close-connection conn) (error 'connection-broken)) until (eq (wsd:ready-state conn) :closed) do (progn (sleep (if (null first-beat) interval first-beat)) (log:trace "Sending heartbeat...") (wsd:send-text conn (serialize-gateway-event (make-instance 'warfare.classes.gateway:<event-heartbeat> :seq-number (bot-ws-sequence-number wsinfo)))) (setf waiting-for-heartbeat-ack t)))) :name "warfare heartbeat thread") ;; Now that the heartbeat thread is running, let's IDENTIFY! (log:trace "Sending IDENTIFY event...") (let ((identify (make-instance 'warfare.classes.gateway:<event-identify> :token (bot-token bot) :intent-int (bot-intents bot)))) (wsd:send-text conn (serialize-gateway-event identify)) (log:trace "IDENTIFY sent!"))) (<event-heartbeat-ack> (setf waiting-for-heartbeat-ack nil) (log:trace "Heartbeat ack recieved!")) (t (log:warn "Recieved unknown event: ~S (event name: '~A')" event (warfare.classes.gateway::event-type event)))) (funcall callback event)) else do (bt:thread-yield))) ; DO NOT hold the thread if we don't have an ; event to process. We'll have to rely on ; good faith that users also yield so that ; the LOOP can continue processing, but in ; threaded implementations, yielding threads ; is a necessity. Reason No. INF that CL ; needs coroutines & continuations.
4,549
Common Lisp
.lisp
77
41.103896
128
0.540928
DrBluefall/warfare
0
0
0
LGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
0cdac1dbc93e5f582e5b2dc773e9ac3d0230066bdab265ac20f971c9aa4caa8f
41,781
[ -1 ]
41,782
constants.lisp
DrBluefall_warfare/src/constants.lisp
(defpackage :warfare.constants (:documentation "Warfare constants.") (:use :cl) (:import-from :alexandria :define-constant) (:export :+base-url+ :+discord-api-version+)) (in-package :warfare.constants) (define-constant +base-url+ "https://discord.com/api" :documentation "The base url for accessing the Discord API." :test #'string=) (defparameter +discord-api-version+ 10 "The version of the Discord API that Warfare is currently targeting.")
461
Common Lisp
.lisp
11
39.363636
72
0.744966
DrBluefall/warfare
0
0
0
LGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
aa5e21549eae9724abb0b74f6b7eaba17326ce9b642e0cf7995c57037a2768bd
41,782
[ -1 ]
41,783
http.lisp
DrBluefall_warfare/src/http/http.lisp
(defpackage :warfare.http (:documentation "Tools for interacting with the Discord HTTP API.") (:use :cl) (:import-from :drakma :http-request) (:import-from :warfare.constants :+base-url+ :+discord-api-version+) (:import-from :alexandria :define-constant) (:import-from :warfare.classes.bot :<bot> :bot-token) (:import-from :warfare.conditions :warfare-error-http) (:export :send-request)) (in-package :warfare.http) (define-constant +user-agent+ "DiscordBot (http://github.com/DrBluefall/warfare, 0.0.1)" :documentation "The user-agent header used to authenticate with the Discord API." :test #'string=) (defun discord-api-url () "Build the url for interacting with the API." (format nil "~a/v~d" +base-url+ +discord-api-version+)) (defun send-request (rq-type endpoint bot &aux (url (format nil "~a/~a" (discord-api-url) endpoint))) "Make an HTTP request to the Discord API. `rq-type` is the type of request to fire. `endpoint` is the endpoint to target. `bot` is an instance of `warfare.classes.bot:<bot>`." (declare (type (or <bot> nil) bot) (type string endpoint) (type keyword rq-type) (optimize (safety 3) (speed 0) (debug 3))) (multiple-value-bind (body status headers uri stream must-close reason-phrase) (drakma:http-request url :user-agent (if bot +user-agent+ :drakma) :method rq-type :additional-headers (if bot `(("Authorization" . ,(format nil "Bot ~a" (bot-token bot)))))) (declare (ignore headers stream must-close)) (flet ((val-in-range (val min max) (and (>= val min) (<= val max)))) ;; Signal an error on 4XX or 5XX status codes. (if (or (val-in-range status 400 499) (val-in-range status 500 599)) (error 'warfare-error-http :what (format nil "Failed to send request to Discord: ~d ~a" status reason-phrase) :status status :uri uri :body body))) (let* ((json-str (flexi-streams:octets-to-string body)) (json (shasht:read-json json-str))) json)))
2,059
Common Lisp
.lisp
47
38.702128
88
0.666667
DrBluefall/warfare
0
0
0
LGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
e27d2f096d1a3e83db9459477dda564a5787a93228cb9b267b77b7d874649c28
41,783
[ -1 ]
41,784
gateway.lisp
DrBluefall_warfare/src/gateway/gateway.lisp
(defpackage :warfare.gateway (:use :cl :warfare.classes.gateway :warfare.classes.bot) (:import-from :warfare.http :send-request) (:export :set-websocket-info :connect-to-discord) (:documentation "Interacting with the Discord Websocket.")) (in-package :warfare.gateway) (defun set-websocket-info (bot) "Request the info needed for bot to interact with the gateway." (declare (optimize (speed 0) (safety 3) (debug 3)) (type <bot> bot)) (let* ((json (send-request :get "gateway/bot" bot)) (sstart-limits (gethash "session_start_limit" json))) (setf (bot-ws-info bot) (make-instance '<bot-websocket-info> :url (gethash "url" json) :cap (gethash "total" sstart-limits) :left (gethash "remaining" sstart-limits) :reset-after (gethash "reset_after" sstart-limits) :max-concurrents (gethash "max_concurrency" sstart-limits))))) (defun connect-to-discord (bot) "Open a gateway connection to Discord." (declare (optimize (speed 0) (safety 3) (debug 3)) (type <bot> bot)) (let* ((wsinfo (bot-ws-info bot)) (client (setf (bot-ws-connection wsinfo) (wsd:make-client (format nil "~a/?v=~d&encoding=json" (bot-ws-url wsinfo) warfare.constants:+discord-api-version+)))) (event-queue (bot-ws-event-queue wsinfo))) (wsd:on :message client (lambda (ev) (log:debug "Event recieved!~%") (let* ((parsed (shasht:read-json ev)) (event (deserialize-gateway-event parsed))) (log:debug "Event: ~s~%json: ~s~%" event parsed) ;; Did a dumb thing here: ;; ;; When I was originally planning this library, I had gotten ;; annoyed that websocket-driver's read operations were handled ;; on a separate thread, and likely would've conflicted with my ;; desire to use cl-async for something like heartbeating. ;; ;; Then I completely forgot about that. ;; ;; I wrote much of the initial event processing code here, where ;; this comment is. ;; ;; Apparently, my initial idea should have been the one I went ;; for. ;; ;; For some godforsaken reason, cl-async's event loop isn't ;; available in websocket-driver's thread. I can only surmise ;; that something about cl-async's event loop is thread-local. (queues:qpush event-queue event)))) (wsd:on :close client (lambda (&key code reason) (log:warn "Connection closed (~d): ~a" code reason) (setf (bot-ws-close-code wsinfo) code))) (wsd:start-connection client :verify nil)))
2,966
Common Lisp
.lisp
61
36.52459
80
0.571822
DrBluefall/warfare
0
0
0
LGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
42f4af9986254fa83fd45fefc41affbe870b435461ea375f82ec1763ab332435
41,784
[ -1 ]
41,785
user.lisp
DrBluefall_warfare/src/classes/user.lisp
(defpackage :warfare.classes.user (:use :cl)) (in-package :warfare.classes.user) (defclass <user> () ((username :initarg :name :reader username) (discriminator :initarg :discriminator :reader discriminator) (id :initarg :id :reader snowflake) (accent-color :initarg :accent-color :reader accent-color) (avatar :initarg :avatar :reader avatar) (avatar-decoration :initarg :avatar-decoration :reader avatar-decoration) (banner :initarg :banner :reader banner) (banner-color :initarg :banner-color :reader banner-color) (public-flags :initarg :public-flags :reader public-flags) (bot :initarg :is-bot :reader is-bot)))
705
Common Lisp
.lisp
24
24.666667
49
0.691176
DrBluefall/warfare
0
0
0
LGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
2e1045d22eecaab4135c3191d8e462c73ce342ca07488624d606163b9e74d599
41,785
[ -1 ]
41,786
gateway.lisp
DrBluefall_warfare/src/classes/gateway.lisp
(defpackage :warfare.classes.gateway (:use :cl) (:export :<gateway-event> :<event-heartbeat> :<event-heartbeat-ack> :<event-identify> :<event-hello> :hello-heartbeat-interval :deserialize-gateway-event :serialize-gateway-event)) (in-package :warfare.classes.gateway) (defclass <gateway-event> () ((opcode :accessor event-opcode :initarg :opcode :documentation "The opcode of the event.") (type :accessor event-type :initarg :type :documentation "The name of the event.") (data :accessor event-data :initarg :data :documentation "The JSON recieved from an event, encoded as a hash table.") (sequence-number :accessor event-seq-number :initarg :seq-number :documentation "Sequence number used for resuming sessions & heartbeating."))) (defclass <event-hello> (<gateway-event>) ((heartbeat-interval :accessor hello-heartbeat-interval :initarg :heartbeat-interval :documentation "The delay to wait between sending heartbeat events."))) (defclass <event-heartbeat> (<gateway-event>) ((seq-number :initarg :seq-number :accessor heartbeat-sequence-number :documentation "Sent to Discord in order to maintain a gateway connection. If Discord sends this event to us, immediately respond with our own heartbeat."))) (defclass <event-heartbeat-ack> (<gateway-event>) () (:documentation "A heartbeat acknowledgement from Discord. If this event isn't recieved between heartbeats, close the gateway & reconnect.")) (defclass <event-identify> (<gateway-event>) ((token :type string :initarg :token :initform (error "A token must be set to IDENTIFY with Discord.") :accessor identify-token :documentation "A bot's authentication token.") (properties :type list :initform `(("os" . ,(format nil "~a ~a" (software-type) (software-version))) ("browser" . "warfare") ("device" . "warfare")) :accessor identify-properties :documentation "Properties of the connecting client.") (compress :type boolean :initform nil :reader identify-compress :documentation "Whether the library supports packet compression or not.") (large-threshold :type (integer 50 250) :initarg :large-threshold :initform 50 :accessor identify-large-threshold :documentation "The cap at which Discord will stop sending offline members in large guilds.") (shard :type (cons unsigned-byte unsigned-byte) :initarg :shard-info :accessor identify-shard-info :initform nil :documentation "Used for sharding. See <https://discord.com/developers/docs/topics/gateway#sharding>.") (intents :type integer :initarg :intent-int :accessor identify-intent-int :initform 0 :documentation "Intents to request from the Gateway."))) (defgeneric serialize-gateway-event (ev) (:documentation "Serialize a gateway event into JSON.") (:method ((ev <event-heartbeat>)) (shasht:write-json* `(("op" . 1) ("d" . ,(heartbeat-sequence-number ev))) :stream nil :alist-as-object t :false-values '(nil :null))) (:method ((ev <event-identify>)) (let ((alist nil)) (push '("op" . 2) alist) ; Opcode (let ((data-alist nil)) (push `("token" . ,(identify-token ev)) data-alist) (push `("properties" . ,(identify-properties ev)) data-alist) (push `("compress" . ,(identify-compress ev)) data-alist) (push `("large_threshold" . ,(identify-large-threshold ev)) data-alist) (unless (null (identify-shard-info ev)) (push `("shard" . ,(identify-shard-info ev)) data-alist)) (push `("intents" . ,(identify-intent-int ev)) data-alist) (push `("d" . ,data-alist) alist)) (shasht:write-json* alist :alist-as-object t :false-values '(nil :null) :stream nil)))) (defun deserialize-gateway-event (ev) "Parse a gateway event into a proper class." (declare (optimize (speed 3)) (type hash-table ev)) (log:trace "Parsing event...") ;; Get the opcode & data. That'll inform the rest of the process. (let* ((opcode (gethash "op" ev)) (data (gethash "d" ev)) (seq-num (if (not (= opcode 0)) nil (gethash "s" ev))) (type (if (not (= opcode 0)) nil (gethash "t" ev)))) (macrolet ((make-event (sym &rest args) `(make-instance ,sym :type type :seq-number seq-num :data data :opcode opcode ,@args))) (log:trace "Event parsed with " opcode) (alexandria:switch (opcode :test #'=) ;; Used to maintain a gateway connection. ;; We may recieve this event from Discord, so we have to include it here. (1 (make-event '<event-heartbeat> :seq-number data)) ;; Initial event sent when connecting. (10 (make-event '<event-hello> :heartbeat-interval (gethash "heartbeat_interval" data))) ;; Recognition of a heartbeat. (11 (make-event '<event-heartbeat-ack>)) (t (make-event '<gateway-event>))))))
5,558
Common Lisp
.lisp
117
37.282051
172
0.601583
DrBluefall/warfare
0
0
0
LGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
d27509e094b0455ed4553be489a2f6e77ccbdf039d03fab4a87d225d31b2c8bc
41,786
[ -1 ]
41,787
bot.lisp
DrBluefall_warfare/src/classes/bot.lisp
(defpackage :warfare.classes.bot (:use :cl) (:export :<bot> :bot-token :bot-intents :<bot-websocket-info> :bot-ws-info :bot-ws-event-queue :bot-ws-connection :bot-ws-url :bot-ws-close-code)) (in-package :warfare.classes.bot) (defclass <bot-websocket-info> () ((conn :accessor bot-ws-connection :documentation "The current websocket connection to Discord.") (close-code :accessor bot-ws-close-code :initform nil :documentation "The close code for this websocket connection.") (url :accessor bot-ws-url :initarg :url :documentation "The url required to connect to the gateway.") (cap :accessor bot-ws-connection-cap :initarg :cap :documentation "The maximum number of times we can connect to the gateway.") (left :accessor bot-ws-connections-remaining :initarg :left :documentation "How many times we can connect to the gateway again.") (reset-after :accessor bot-ws-conncap-reset-after :initarg :reset-after :documentation "A timestamp representing how long until the the limit on gateway connections resets.") (max-concurrents :accessor bot-ws-max-concurrents :initarg :max-concurrents :documentation "The maximum number of IDENTIFY requests that can be sent every 5 seconds.") (queue :accessor bot-ws-event-queue :initform (queues:make-queue :simple-cqueue) :documentation "The queue where events recieved over the websocket are placed.") (seq-number :accessor bot-ws-sequence-number :initform nil :documentation "The last sequence number sent to us by Discord.") (heartbeat-thread :accessor bot-ws-heartbeat-thread :initform nil :documentation "The thread that sends heartbeats through this websocket connection."))) (defclass <bot> () ((token :initarg :token :initform (error "A bot needs a token to authorize with Discord.") :reader bot-token) (ws-info :type (or <bot-websocket-info> nil) :accessor bot-ws-info) (intents :accessor bot-intents :initform 0 :documentation "A set of bitflags for describing what events should be recieved from Discord.")) (:documentation "A discord bot.")) (defmethod (setf bot-intents) ((intent symbol) bot) (let ((intent-mask (alexandria:switch ((if (keywordp intent) intent (alexandria:make-keyword (string intent)))) (:guilds (ash 1 0)) (:guild-members (ash 1 1)) (:guild-bans (ash 1 2)) (:guild-emojis-and-stickers (ash 1 3)) (:guild-integrations (ash 1 4)) (:guild-webhooks (ash 1 5)) (:guild-invites (ash 1 6)) (:guild-voice-states (ash 1 7)) (:guild-presences (ash 1 8)) (:guild-messages (ash 1 9)) (:guild-message-reactions (ash 1 10)) (:guild-message-typing (ash 1 11)) (:direct-messages (ash 1 12)) (:direct-message-reactions (ash 1 13)) (:direct-message-typing (ash 1 14)) (:message-content (ash 1 15)) (:guild-scheduled-events (ash 1 16)) (:auto-moderation-configuration (ash 1 20))))) (setf (slot-value bot 'intents) (logior (slot-value bot 'intents) intent-mask))))
3,761
Common Lisp
.lisp
75
39.293333
108
0.571273
DrBluefall/warfare
0
0
0
LGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
bbc1cc810c1869fe14681d68e17ce263d983f3569e0b15e70388a8d4c937287d
41,787
[ -1 ]
41,788
warfare.asd
DrBluefall_warfare/warfare.asd
(asdf:defsystem :warfare :description "A Discord API library for Common Lisp." :version "0.0.1" :author "Alexander \"Dr. Bluefall\" Bisono <[email protected]>" :license "LGPL-3.0-or-later" :depends-on (:flexi-streams :drakma :websocket-driver :shasht :alexandria :queues.simple-cqueue :log4cl) :components ((:module "src" :serial t :components ((:file "constants") (:file "conditions") (:module "classes" :serial t :components ((:file "user") (:file "bot") (:file "gateway"))) (:module "http" :serial t :components ((:file "http"))) (:module "gateway" :serial t :components ((:file "gateway"))) (:file "lib")))))
891
Common Lisp
.asd
29
20.172414
66
0.490719
DrBluefall/warfare
0
0
0
LGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
728f05cbe672c1ea5d84c516ac1b2d6facce285e76070c2249c7b724c00d1341
41,788
[ -1 ]
41,812
setup.lisp
b-steger_adventofcode2021/example/setup.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ;;Copy the code base folder to $HOME/quicklisp/local-projects/ and evalute this form: (ql:quickload "adventofcode2021") ;;You are now able to read the code with everything loaded. Use C-M-x (slime-eval-defun) to see the evaluation result or use C-I (slime-inspect) if you want to inspect the results. ;;src/report.lisp contains code which computes all solutions.
1,130
Common Lisp
.lisp
12
92.5
251
0.769991
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
64cff244d0e12b117403fc1912aa69d65a959acb4a2b1be622490314c1ba0e69
41,812
[ -1 ]
41,813
11.lisp
b-steger_adventofcode2021/src/11.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defmethod input ((day (eql 11)) source) "Multidimensional array representing the energy level of the octopuses [0..9]. No zero is read in. Ever." (let* ((nested-lists (parse '09-file (read-file day source))) (height (length nested-lists)) (width (length (first nested-lists)))) (make-array (list height width) :initial-contents nested-lists))) (input 11 T) (input 11 'toy-example) (input 11 'full) ;;;; Solution (defparameter *8direction-vectors* '((0 (0 . 1)) (45 (1 . 1)) (90 (1 . 0)) (135 (1 . -1)) (180 (0 . -1)) (225 (-1 . -1)) (270 (-1 . 0)) (315 (-1 . 1))) "Mathematical vectors for horizontal/vertical/diagonal movement on a 2d grid. Realized as association lists, car is easting, cdr northing.") (defun flash-count (map location) "Propagate flashes from octopuses in a cavern and count the number of flashes. MAP is closed over." ;;Need to reset values >9 to 0 as the last action during a step. (incf (row-major-aref map location)) ;;10: 9 when entering this function. (cond ((= 10 (map-lookup map location)) ;;1+: current octopus just flashed. (1+ (loop for (dir . (vector)) in *8direction-vectors* summing (let ((neighbour (clip-move map location vector))) (if neighbour (flash-count map neighbour) 0))))) (T 0))) (defun step-octopuses! (map &key (steps 100) part2? return-map?) "Simulate a step in the octopus cavern and return the number of flashes after STEPS steps if PART2? is nil. PART2? has precedence over STEPS. RETURN-MAP? is for internal use only." (loop with flashes = 0 with step = 0 while (if part2? (not (loop for i from 0 below (array-total-size map) always (= 0 (row-major-aref map i)))) (< step steps)) do (progn ;;1. Propagate flashes. (incf flashes (loop for i from 0 below (array-total-size map) summing (flash-count map i ))) ;;2. Set values >9 to 0. (loop for i from 0 below (array-total-size map) do (when (< 9 (row-major-aref map i)) (setf (row-major-aref map i) 0))) (incf step)) finally (return (cond (return-map? map) (part2? step) (T flashes))))) (step-octopuses! (input 11 'toy-example) :steps 2 :return-map? T) (step-octopuses! (input 11 T)) (step-octopuses! (input 11 'full)) (step-octopuses! (input 11 T) :part2? T) (defmethod solution ((day (eql 11)) (variant (eql 'part1)) source) "The number of flashes after 100 steps." (step-octopuses! (input day source) :steps 100)) (is 11 'part1 1656) (defmethod solution ((day (eql 11)) (variant (eql 'part2)) source) "The step when all octopuses flash simultaneously." (step-octopuses! (input day source) :part2? T)) (is 11 'part2 195)
3,890
Common Lisp
.lisp
80
40.6875
251
0.622006
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
89696ee2ad85f87a160bfb87f084745977e8a6e2c580cf6225be45f7ead0505b
41,813
[ -1 ]
41,814
08.lisp
b-steger_adventofcode2021/src/08.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defun segment2symbol (segment) "In: #\a .. #\g Out: :a .. :g Reasoning: easier handling expected." (cond ((char= #\a segment) :a) ((char= #\b segment) :b) ((char= #\c segment) :c) ((char= #\d segment) :d) ((char= #\e segment) :e) ((char= #\f segment) :f) ((char= #\g segment) :g))) (segment2symbol #\f) (defun sort-signal-pattern (signal-pattern) "Sort the SIGNAL-PATTERN (list of keywords) alphabetically." (sort signal-pattern (lambda (x y) (string< (format nil "~A" x) (format nil "~A" y))))) (defrule 08-signal-pattern (+ (character-ranges (#\a #\g))) ;;#'sort: transposition is not important as the focus is on substitution, ordered lists are easier to debug. ;;#'deduce-one relies on sorted input. (:lambda (input) (sort-signal-pattern (mapcar #'segment2symbol input)))) (parse '08-signal-pattern "cdfbe") (defrule 08-output-value 08-signal-pattern) (defrule 08-line (and (+ (and 08-signal-pattern (? " "))) ;;Will already be eaten, but nevertheless. (? " ") "| " (+ (and 08-output-value (? " ")))) (:lambda (input) (let ((signal-patterns (elt input 0)) (output-values (elt input 3))) (list (mapcar #'first signal-patterns) (mapcar #'first output-values))))) (parse '08-line "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf") (defrule 08-file (and (+ (and 08-line (? new))) (? new)) (:lambda (input) (let ((entries (elt input 0))) (mapcar #'first entries)))) (defmethod input ((day (eql 8)) source) "List of isolated puzzles, each consisting of a list of signal patterns and a list of output-values." (parse '08-file (read-file day source))) (input 8 T) (input 8 'toy-example) (input 8 'full) ;;;; Solution #| 0 is abc efg → 6 segments 1 is c f → 2 segments 2 is a cde g → 5 segments 3 is a cd fg → 5 segments 4 is bcd f → 4 segments 5 is ab d fg → 5 segments 6 is ab defg → 6 segments 7 is a c f → 3 segments 8 is abcdefg → 7 segments 9 is abcd fg → 6 segments → GROUP BY segment (count) → 2 segments: 1 3 segments: 7 4 segments: 4 5 segments: 2 3 5 6 segments: 0 6 9 7 segments: 8 1 7 4 8 are determined by the length of input. On to part 2. Overall segment analysis: a 0 2 3 5 6 7 8 9 → a has 8 candidates b 0 4 5 6 8 9 → b has 6 candidates c 0 1 2 3 4 7 8 9 → c has 8 candidates d 2 3 4 5 6 8 9 → d has 7 candidates e 0 2 6 8 → e has 4 candidates f 0 1 3 4 5 6 7 8 9 → f has 9 candidates g 0 2 3 5 6 8 9 → g has 7 candidates Part1 for completeness: 2 segments for 1 4 segments for 4 3 segments for 7 7 segments for 8 → b e f can be identified through the histogram of the input. |# (defun frequency-analysis (signal-patterns) "Returns a property list which lists the segment counts." (let* ((population (loop for x in signal-patterns append x)) (tally (make-hash-table))) (loop for x in population do (setf (gethash x tally) (incf (gethash x tally 0)))) (loop for k being the hash-keys of tally for v being the hash-value of tally append (list k v)))) ;;=> (:A 8 :B 9 :C 7 :D 8 :E 6 :F 7 :G 4) (frequency-analysis (first (first (input 8 'toy-example)))) (defun fresh-key () "Returns a fresh key. Values are cleartext, use (getf key crypted) to get the cleartext." '(:a nil :b nil :c nil :d nil :e nil :f nil :g nil)) (defun register-key-entry (crypted clear &key (key (fresh-key))) "Register an identified segment. KEY maps crypted to clear." (loop for (a . d) on key by #'cddr append (list a (if (eql a crypted) clear (car d)))) #| (setf (getf key crypted) clear) key|#) ;;=> (:A NIL :B NIL :C NIL :D NIL :E NIL :F NIL :G :E) (register-key-entry :g :e) (defun reverse-lookup (frequency-table count) "Returns the (first) key of a certain value in a property list, with naming fitted to the context of #'frequency-analysis." (loop for (a . d) on frequency-table by #'cddr when (= count (car d)) do (return a))) ;;=> :E (reverse-lookup (frequency-analysis (first (first (input 8 'toy-example)))) 6) (defun deduce-bef (frequency-table &key (key (fresh-key))) "Deduce b e f segments: b is the only one which has 6 candidates. e is the only one which has 4 candidates. f is the only one which has 9 candidates." (register-key-entry (reverse-lookup frequency-table 6) :b :key (register-key-entry (reverse-lookup frequency-table 4) :e :key (register-key-entry (reverse-lookup frequency-table 9) :f :key key)))) ;;=> (:A NIL :B :F :C NIL :D NIL :E :B :F NIL :G :E) (deduce-bef (frequency-analysis (first (first (input 8 'toy-example))))) #| Next, partially decrypted numbers can be used. For example, the other entry of 1 must be c. |# (defun segments-of-number (signal-patterns number) "Return the (encrypted) segments belonging to a number. Sufficient information is only available for 1 4 7 8." (flet ((find-by-length (wished-length signal-patterns) "Pick the list with WISHED-LENGTH." (find-if (lambda (x) (= wished-length (length x))) signal-patterns))) (cond ((= 1 number) (find-by-length 2 signal-patterns)) ((= 4 number) (find-by-length 4 signal-patterns)) ((= 7 number) (find-by-length 3 signal-patterns)) ((= 8 number) (find-by-length 7 signal-patterns)) (T (error "Insufficient information."))))) (segments-of-number (first (first (input 8 'toy-example))) 1) (handler-case (segments-of-number (first (first (input 8 'toy-example))) 5) (error () "Failed as expected.")) (defun deduce-one (&key helper-segment helper-number signal-patterns (key (error "Call (at least) #'deduce-bef for a valid key."))) "Deduce a ciphertext→cleartext mapping for HELPER-SEGMENT with the help from HELPER-NUMBER. Needs a partial KEY recovered by (at least) #'deduce-bef. Only works for helpers which will know all but one ciphertext segment." (let* ((segments (segments-of-number signal-patterns helper-number)) ;;Contract: only one nil in list. (decrypted-segments (mapcar (lambda (x) (getf key x)) segments)) ;;This ciphertext segment has the same index as the nil. (encrypted-a (loop for i = 0 then (incf i) for entry in decrypted-segments unless entry do (return (elt segments i))))) ;;It is known that HELPER-SEGMENT is the missing information. (register-key-entry encrypted-a helper-segment :key key))) (deduce-one :helper-segment :c :helper-number 1 :signal-patterns (first (first (input 8 'toy-example))) :key (deduce-bef (frequency-analysis (first (first (input 8 'toy-example)))))) #| Now b c e f are known. a d g are left. Next helper is 7 (a c f) which will give the cleartext of a. |# ;;=> (:A :C :B :F :C NIL :D :A :E :B :F NIL :G :E) (deduce-one :helper-segment :a :helper-number 7 :signal-patterns (first (elt (input 8 T) 0)) :key (deduce-one :helper-segment :c :helper-number 1 :signal-patterns (first (first (input 8 'toy-example))) :key (deduce-bef (frequency-analysis (first (first (input 8 'toy-example))))))) #| Now a b c e f are known. d g are left. Next helper is 4 (b c d f) which will give the cleartext of a. |# ;;=> (:A :C :B :F :C NIL :D :A :E :B :F :D :G :E) (deduce-one :helper-segment :d :helper-number 4 :signal-patterns (first (first (input 8 'toy-example))) :key (deduce-one :helper-segment :a :helper-number 7 :signal-patterns (first (first (input 8 'toy-example))) :key (deduce-one :helper-segment :c :helper-number 1 :signal-patterns (first (first (input 8 'toy-example))) :key (deduce-bef (frequency-analysis (first (first (input 8 'toy-example)))))))) #| Now a b c d e f are known. g is left. Next helper is 8 (a b c d e f g) which will give the cleartext of g. |# (defun deduce-segments (signal-patterns) "The key needed to decrypt the ciphertext segments." (deduce-one :helper-segment :g :helper-number 8 :signal-patterns signal-patterns :key (deduce-one :helper-segment :d :helper-number 4 :signal-patterns signal-patterns :key (deduce-one :helper-segment :a :helper-number 7 :signal-patterns signal-patterns :key (deduce-one :helper-segment :c :helper-number 1 :signal-patterns signal-patterns :key (deduce-bef (frequency-analysis signal-patterns))))))) ;;=> (:A :C :B :F :C :G :D :A :E :B :F :D :G :E) (deduce-segments (first (first (input 8 'toy-example)))) (defun decrypt-signal-pattern (signal-pattern key) "Return the cleartext segments of a SIGNAL-PATTERN with the help of KEY." (sort-signal-pattern (mapcar (lambda (x) (getf key x)) signal-pattern))) ;;Encrypted: 7 is (:A :B :D). (first (elt (input 8 'toy-example) 0)) ;;Decrypted: 7 is (:A :C :F) (correct). (let ((key (deduce-segments (first (first (input 8 'toy-example)))))) (mapcar (lambda (x) (decrypt-signal-pattern x key)) (first (first (input 8 'toy-example))))) (defun number-lookup (cleartext-signal-pattern) "Return the number which will need all segments listed in CLEARTEXT-SIGNAL-PATTERN." (flet ((pattern-match? (pattern) (and ;;Special case '(:a) would determine the list length for #'every. (= (length pattern) (length cleartext-signal-pattern)) (every #'eql ;;Better be safe than sorry. (sort-signal-pattern cleartext-signal-pattern) pattern)))) (cond ((pattern-match? '(:a :b :c :e :f :g)) 0) ((pattern-match? '(:c :f)) 1) ((pattern-match? '(:a :c :d :e :g)) 2) ((pattern-match? '(:a :c :d :f :g)) 3) ((pattern-match? '(:b :c :d :f)) 4) ((pattern-match? '(:a :b :d :f :g)) 5) ((pattern-match? '(:a :b :d :e :f :g)) 6) ((pattern-match? '(:a :c :f)) 7) ((pattern-match? '(:a :b :c :d :e :f :g)) 8) ((pattern-match? '(:a :b :c :d :f :g)) 9) (T nil)))) (number-lookup '(:a)) (defun output-value-of-entry (input-line) "Returns the number an INPUT-LINE represents. Format of INPUT-LINE: see parser rule '08-line ." (let ((key (deduce-segments (first input-line)))) (parse-integer (format nil "~{~A~}" (loop for x in (second input-line) collect (number-lookup (decrypt-signal-pattern (sort-signal-pattern x) key))))))) ;;5353 (output-value-of-entry (first (input 8 'toy-example))) (loop for line in (input 8 T) collect (output-value-of-entry line)) (defun digit-1-4-7-8? (signal-pattern) "Returns T if SIGNAL-PATTERN is 1 or 4 or 7 or 8. SIGNAL-PATTERN may be a ciphertext or a cleartext - does not matter." (let ((length (length signal-pattern))) (or ;;number 1 (= length 2) ;;number 4 (= length 4) ;;number 7 (= length 3) ;;number 8 (= length 7)))) (defmethod solution ((day (eql 8)) (variant (eql 'part1)) source) "Sum all occurences of numbers 1 or 4 or 7 or 8" (loop for line in (input day source) summing (loop for signal-pattern in (second line) summing (if (digit-1-4-7-8? signal-pattern) 1 0)))) (is 8 'part1 26) (defmethod solution ((day (eql 8)) (variant (eql 'part2)) source) "Sum all output values of all entries." (loop for line in (input day source) summing (output-value-of-entry line))) (is 8 'part2 61229)
13,067
Common Lisp
.lisp
309
35.644013
251
0.615063
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
9025ee93cacf0cc27b5c35aa42975ec1be1de42d27edf33431d25407082a0d1b
41,814
[ -1 ]
41,815
06.lisp
b-steger_adventofcode2021/src/06.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule 06-file (and (+ (and integer (? ","))) (? new)) (:lambda (input) (let ((entries (elt input 0))) (mapcar #'first entries)))) (defmethod input ((day (eql 6)) source) "List of fish timers." (parse '06-file (read-file day source))) (input 6 T) (input 6 'full) ;;;; Solution #| There seems no need to represent each fish in an instance because all fishes with the same timer have the same state change. As the part2 task hints, there will be very deep recursions if the suggested approach (returning a sum with doubly called descending steps for all fishes in question) is taken. A giant array may work (as of 2022), even though space use would be superlinear. As already said, since state changes can be aggregated, a histogram seems to be the most scalable approach. |# (defun timer-histogram (input &optional (histogram (list 0 0 0 0 0 0 0 0 0))) "Returns a histogram of the numbers in INPUT, represented as (zero-indexed) list." (cond (input (incf (elt histogram (car input))) (timer-histogram (rest input) histogram)) (T histogram))) (timer-histogram (input 6 T)) #| Next, following observation: the number of children is exactly the number of parents. Which leads to thought reversal: at the modulo border, new adult fishes (of timer 6) are introduced, not children. During a step, the population pyramid shifts by one. Slice 6 sees the introduction of new members. |# (defun 06-step (days-left histogram &optional (pointer 0)) "Shift HISTOGRAM (achieved though the recursive increase of POINTER) until DAYS-LEFT equals to zero, returning the sum of the population pyramid." (cond ((zerop days-left) (reduce #'+ histogram)) (T (06-step (1- days-left) (progn ;;7: timer 6 zero-indexed (incf (elt histogram (mod (+ pointer 7) (length histogram))) (elt histogram pointer)) histogram) (mod (1+ pointer) (length histogram)))))) ;;26 (06-step 18 (timer-histogram (input 6 T))) ;;5934 (06-step 80 (timer-histogram (input 6 T))) ;;26984457539 (06-step 256 (timer-histogram (input 6 T))) #|After around 7036 years, the decimal number needs 97236 digits to represent the population size. (with-open-file (f "/dev/shm/06-fishes.txt" :if-exists :supersede :if-does-not-exist :create :direction :output) (format f "~A" (06-step 2569999 (timer-histogram (input 6 T))))) After 25699999 days (approx. 70363 years), the number has 972348 digits.|# (defmethod solution ((day (eql 6)) (variant (eql 'part1)) source) "Population size of lanternfish after 80 days." (06-step 80 (timer-histogram (input day source)))) (is 6 'part1 5934) (defmethod solution ((day (eql 6)) (variant (eql 'part2)) source) "Population size of lanternfish after 256 days." (06-step 256 (timer-histogram (input day source)))) (is 6 'part2 26984457539)
3,759
Common Lisp
.lisp
67
51.537313
251
0.705194
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
3b6bccce5bfe9a4f28ecb39c27286ce8ac59305e8bdefa8c9453303c2b15a4e4
41,815
[ -1 ]
41,816
18.lisp
b-steger_adventofcode2021/src/18.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule 18-pair (and "[" (or integer 18-pair) "," (or integer 18-pair) "]") (:lambda (input) (let ((x (elt input 1)) (y (elt input 3))) (list x y)))) (parse '18-pair "[1,2]") (parse '18-pair "[[1,2],3]") (parse '18-pair "[9,[8,7]]") (parse '18-pair "[[1,9],[8,5]]") (parse '18-pair "[[[[1,2],[3,4]],[[5,6],[7,8]]],9]") (parse '18-pair "[[[9,[3,8]],[[0,9],6]],[[[3,7],[4,9]],3]]") (parse '18-pair "[[[[1,3],[5,3]],[[1,3],[8,7]]],[[[4,9],[6,9]],[[8,2],[7,3]]]]") (defrule 18-file (+ (and 18-pair (? new))) (:lambda (input) (mapcar #'first input))) (defmethod input ((day (eql 18)) source) "List of binary trees with leaves being integers [0..9]." (parse '18-file (read-file day source))) (input 18 T) (input 18 'full) ;;;; Solution #| The reduce operation profits from a binary tree with a doubly linked list at the leaves. This solution converts the tree to a flat representation which is suited for the operations required by the spec. |# (defun flat-tree (nested-tree &key (height 0)) "Serialize NESTED-TREE. Returns a list of preorder-traversed leaves of binary NESTED-TREE enriched with tree height information." (if (listp nested-tree) (append (flat-tree (first nested-tree) :height (1+ height)) (flat-tree (second nested-tree) :height (1+ height))) ;;Two #'list: #'append operation in the recursive case. (list (list :value nested-tree :height height)))) ;;Heights 5 5 4 3 2 1. (flat-tree (parse '18-pair "[[[[[9,8],1],2],3],4]")) ;;Heights 1 2 3 4 5 5. (flat-tree (parse '18-pair "[7,[6,[5,[4,[3,2]]]]]")) ;;Heights 2 3 4 5 5 1. (flat-tree (parse '18-pair "[[6,[5,[4,[3,2]]]],1]")) ;;Heights 2 3 4 5 5 2 3 4 5 5. (flat-tree (parse '18-pair "[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]")) #|Heights 2 3 4 4 2 3 4 5 5. Flat trees look like this: => ((:value 3 :height 2) (:value 2 :height 3) (:value 8 :height 4) (:value 0 :height 4) (:value 9 :height 2) (:value 5 :height 3) (:value 4 :height 4) (:value 3 :height 5) (:value 2 :height 5))|# (flat-tree (parse '18-pair "[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]")) (defun nested-tree (flat-tree) "Unserialize FLAT-TREE. Returns the binary tree represented by the leaves list in FLAT-TREE, as produced by #'flat-tree." ;;There must always be at least one pair with equal height. Replace them by an entry with a list of their :value slots in its value slot. (labels ((n (flat-tree-rest) "Group the deepest (and first) nested pair with equal height." (if (cdr flat-tree-rest) (let ((max-height (loop for item in flat-tree-rest maximize (getf item :height)))) (if (and (= (getf (car flat-tree-rest) :height) (getf (cadr flat-tree-rest) :height)) ;;Go for the deepest pair first. (>= (getf (car flat-tree-rest) :height) max-height)) (append (list (list :value (list (getf (car flat-tree-rest) :value) (getf (cadr flat-tree-rest) :value)) :height (1- (getf (car flat-tree-rest) :height)))) (cddr flat-tree-rest)) (append (list (car flat-tree-rest)) (n (cdr flat-tree-rest))))) flat-tree-rest))) (let ((grouped (n flat-tree))) ;;#'cddr: more than two elements in FLAT-TREE (i.e. not a tree yet). (if (cddr flat-tree) (nested-tree grouped) (getf (first grouped) :value))))) ;;Target ((3 (2 (8 (7 6)))) ((((1 2) (3 4)) 2) 2)) (nested-tree (flat-tree (parse '18-pair "[[3,[2,[8,[7,6]]]],[[[[1,2],[3,4]],2],2]]"))) (nested-tree (flat-tree (parse '18-pair "[1,[2,[3,[4,[5,[6,7]]]]]]"))) (nested-tree (flat-tree (parse '18-pair "[[[[0,7],4],[15,[0,13]]],[1,1]]"))) (nested-tree (flat-tree (parse '18-pair "[[[[4,2],2],6],[8,7]]"))) (defun redistribute-height-5 (flat-tree-rest &key (first-time? T)) "If a pair is inside four pairs (tree height = 5), add its left component to its previous pre-order neighbour and its right component to its next pre-order neighbour (if possible) and leave a 0 in place. Operates on a flat tree representation, see #'flat-tree." (if (cdr flat-tree-rest) ;;Recursive case. (cond ;;Special recursive case: the first two entries are both of height 5. ((and first-time? (= 5 (getf (car flat-tree-rest) :height)) (= 5 (getf (cadr flat-tree-rest) :height))) ;;Ignore the left value and dissolve the cadr into the caddr. (append (list (list :value 0 :height (1- (getf (cadr flat-tree-rest) :height))) (list :value (+ (getf (cadr flat-tree-rest) :value) (getf (caddr flat-tree-rest) :value)) :height (getf (caddr flat-tree-rest) :height))) (redistribute-height-5 (subseq flat-tree-rest (min 3 (length flat-tree-rest))) :first-time? nil))) ;;Normal recursive case: 5 5 found somewhere else in the list. ((and first-time? (= 5 (getf (cadr flat-tree-rest) :height)) ;;Actually redundant; there must be/will be a cddr with height 5. (= 5 (getf (caddr flat-tree-rest) :height))) (remove nil (append (list ;;The current is the left one; add the value of the cadr. (list :value (+ (getf (car flat-tree-rest) :value) (getf (cadr flat-tree-rest) :value)) :height (getf (car flat-tree-rest) :height)) (list :value 0 :height (1- (getf (cadr flat-tree-rest) :height))) ;;Also move the value of the caddr to the cadddr. (when (cadddr flat-tree-rest) (list :value (+ (getf (caddr flat-tree-rest) :value) (getf (cadddr flat-tree-rest) :value)) :height (getf (cadddr flat-tree-rest) :height)))) (redistribute-height-5 (subseq flat-tree-rest ;;4: The next and next after the next disappeared, and even the entry after this is already processed, too. ;;There may or may not be elements left. (min 4 (length flat-tree-rest))) :first-time? nil)))) ;;No 5 5 found. (T (append (list (car flat-tree-rest)) (redistribute-height-5 (rest flat-tree-rest) :first-time? first-time?)))) ;;Base case. flat-tree-rest)) (redistribute-height-5 nil) ;;Target ((((0 9) 2) 3) 4) (nested-tree (redistribute-height-5 (flat-tree (parse '18-pair "[[[[[9,8],1],2],3],4]")))) ;;Target (7 (6 (5 (7 0)))) (nested-tree (redistribute-height-5 (flat-tree (parse '18-pair "[7,[6,[5,[4,[3,2]]]]]")))) ;;Target ((6 (5 (7 0))) 3) (nested-tree (redistribute-height-5 (flat-tree (parse '18-pair "[[6,[5,[4,[3,2]]]],1]")))) ;;Target ((3 (2 (8 0))) (9 (5 (4 (3 2))))) (nested-tree (redistribute-height-5 (flat-tree (parse '18-pair "[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]")))) ;;Target ((3 (2 (8 0))) (9 (5 (7 0)))) (nested-tree (redistribute-height-5 (flat-tree (parse '18-pair "[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]")))) (nested-tree (redistribute-height-5 (redistribute-height-5 (flat-tree (parse '18-pair "[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]"))))) (defun split-on-10-or-greater (flat-tree-rest &key (first-time? T)) "Replace each element having a value >= 10 in FLAT-TREE-REST with a list of two items. New values are the old number divided by two, rounded down and up, respectively." (if flat-tree-rest (if (and first-time? (< 9 (getf (car flat-tree-rest) :value))) (let ((value (getf (car flat-tree-rest) :value)) (height (getf (car flat-tree-rest) :height))) (append (list (list :value (floor (/ value 2)) :height (1+ height)) (list :value (ceiling (/ value 2)) :height (1+ height))) (split-on-10-or-greater (rest flat-tree-rest) :first-time? nil))) (cons (car flat-tree-rest) (split-on-10-or-greater (rest flat-tree-rest) :first-time? first-time?))) flat-tree-rest)) ;;Target ((((0 7) 4) ((7 8) (0 13))) (1 1)) (nested-tree (split-on-10-or-greater (flat-tree (parse '18-pair "[[[[0,7],4],[15,[0,13]]],[1,1]]")))) ;;Nothing should happen. → Target ((((0 7) 4) (5 (0 3))) (1 1)) (nested-tree (split-on-10-or-greater (flat-tree (parse '18-pair "[[[[0,7],4],[5,[0,3]]],[1,1]]")))) ;;The last element, too. (nested-tree (split-on-10-or-greater '((:value 0 :height 4) (:value 10 :height 4)))) (defun every-height-less-than-5? (flat-tree) "Whether every leaf in FLAT-TREE has a height less than 5." (every (lambda (x) (< (getf x :height) 5)) flat-tree)) (defun every-value-less-than-10? (flat-tree) "Whether every leaf in FLAT-TREE has a value less than 10." (every (lambda (x) (< (getf x :value) 10)) flat-tree)) (defun reduce-tree (flat-tree) "Alternately redistribute leaves with height 5 and split on leaves with value 10 or greater until FLAT-TREE is reduced." (cond ((not (every-height-less-than-5? flat-tree)) (reduce-tree (redistribute-height-5 flat-tree))) ((not (every-value-less-than-10? flat-tree)) (reduce-tree (split-on-10-or-greater flat-tree))) (T flat-tree))) (nested-tree (reduce-tree (flat-tree (parse '18-pair "[[[[[4,3],4],4],[7,[[8,4],9]]],[1,1]]")))) (defun add-sn (&optional left right) "Adds two snailfish numbers (nested lists)." ;;Conversion round trip actually not needed: can increase the heights and append both flat trees. (nested-tree (reduce-tree (flat-tree ;;(cons left (cons right nil)) (list left right))))) ;;Target ((((0 7) 4) ((7 8) (6 0))) (8 1)) (add-sn (parse '18-pair "[[[[4,3],4],4],[7,[[8,4],9]]]") (parse '18-pair "[1,1]")) ;;Target (((1 1) (2 2)) (3 3)) (4 4)) (reduce #'add-sn (parse '18-file "[1,1] [2,2] [3,3] [4,4] ")) ;;Target ((((3 0) (5 3)) (4 4)) (5 5)) (reduce #'add-sn (parse '18-file "[1,1] [2,2] [3,3] [4,4] [5,5] ")) ;;Target ((((5 0) (7 4)) (5 5)) (6 6)) (reduce #'add-sn (parse '18-file "[1,1] [2,2] [3,3] [4,4] [5,5] [6,6] ")) ;;Target (((8 7) (7 7)) ((8 6) (7 7))) (((0 7) (6 6)) (8 7))) (reduce #'add-sn (input 18 T)) (defun magnitude (nested-tree) "The recursive and weighted sum of NESTED-TREE." (+ (* 3 (if (listp (first nested-tree)) (magnitude (first nested-tree)) (first nested-tree))) (* 2 (if (listp (second nested-tree)) (magnitude (second nested-tree)) (second nested-tree))))) (list ;;29 (magnitude (parse '18-pair "[9,1]")) ;;21 (magnitude (parse '18-pair "[1,9]")) ;;129 (magnitude (parse '18-pair "[[9,1],[1,9]]")) ;;143 (magnitude (parse '18-pair "[[1,2],[[3,4],5]]")) ;;1384 (magnitude (parse '18-pair "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]")) ;;445 (magnitude (parse '18-pair "[[[[1,1],[2,2]],[3,3]],[4,4]]")) ;;791 (magnitude (parse '18-pair "[[[[3,0],[5,3]],[4,4]],[5,5]]")) ;;1137 (magnitude (parse '18-pair "[[[[5,0],[7,4]],[5,5]],[6,6]]")) ;;3488 (magnitude (parse '18-pair "[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]")) ;;4140 (magnitude (reduce #'add-sn (parse '18-file "[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]] [[[5,[2,8]],4],[5,[[9,9],0]]] [6,[[[6,2],[5,6]],[[7,6],[4,7]]]] [[[6,[0,7]],[0,9]],[4,[9,[9,0]]]] [[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]] [[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]] [[[[5,4],[7,7]],8],[[8,3],8]] [[9,3],[[9,9],[6,[4,9]]]] [[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]] [[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]] ")))) (defmethod solution ((day (eql 18)) (variant (eql 'part1)) source) "The weighted sum of the reduced snailfish numbers." (magnitude (reduce #'add-sn (input day source)))) (is 18 'part1 3488) #| Solution for part2: cross join. |# (defmethod solution ((day (eql 18)) (variant (eql 'part2)) source) "The largest weighted sum between each possible input line combination in SOURCE. Excludes comparisons of each line with itself." (let ((source (input day source))) (loop for outer in source maximize (loop for inner in source unless (equal outer inner) maximize (magnitude (reduce #'add-sn (list outer inner))))))) ;;3993 (solution 18 'part2 'middle-example) (is 18 'part2 3805)
13,601
Common Lisp
.lisp
271
42.542435
251
0.55963
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
72726c812d0e1d4ae4cab15ac9131278b49a10ecf1fd4fd2acab62e578ff02fc
41,816
[ -1 ]
41,817
package.lisp
b-steger_adventofcode2021/src/package.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :cl-user) (defpackage #:adventofcode2021 (:use #:common-lisp #:esrap)) (in-package :adventofcode2021) ;;This is for Nikodemus Siivola's HYPERDOC, see <http://common-lisp.net/project/hyperdoc/> and <http://www.cliki.net/hyperdoc>. (let ((exported-symbols-alist (loop for symbol being the external-symbols of :adventofcode2021 collect (cons symbol (concatenate 'string "#" (string-downcase symbol)))))) (defun hyperdoc-lookup (symbol type) (declare (ignore type)) (cdr (assoc symbol exported-symbols-alist :test #'eq))))
1,399
Common Lisp
.lisp
21
60.428571
251
0.707939
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
067f8cb5d107ba60fe1e969c19803641bc8c5626a5d37e8f140ab4b66bfa2ae7
41,817
[ -1 ]
41,818
12.lisp
b-steger_adventofcode2021/src/12.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule 12-node (+ (character-ranges (#\a #\z) (#\A #\Z))) (:lambda (input) ;;List with a name (a symbol) and boolean small?. (list (read-from-string (text input)) (every #'lower-case-p input)))) (parse '12-node "start") (eql (first (parse '12-node "ABC")) (first (parse '12-node "ABC"))) (defrule 12-line (and 12-node "-" 12-node) (:lambda (input) (list (elt input 0) (elt input 2)))) (parse '12-line "start-end") (defrule 12-file (+ (and 12-line (? new))) (:lambda (input) (mapcar #'first input))) (parse '12-file (read-file 12 'toy-example)) (defmethod input ((day (eql 12)) source) "A cave system. A cave system seems to have no circles of big caves (in fact, there are no links between big caves obviously)." (parse '12-file (read-file 12 source))) (input 12 'toy-example) (input 12 'middle-example) (input 12 T) ;;;; Solution #| "Number of ..." in recursive functions: return 1 in the base case. Only descending if next cave does not form a loop (i.e. a repeated sequence) in visited-list (this seems to be guaranteed). Given the insights from parsing, it is obviously possible to just exhaustively traverse the graph. Part1 puzzle: only descending if next cave is not (and small? in-visited-list). Transport state through VISITED-list in a recursive function. |# (defun once-in-path? (node path) "Whether NODE only appears once in PATH." (= 1 (count (car node) path :key #'car))) (defun small-cave? (node) "Whether NODE is a small cave." (second node)) (defun abides-part2-cave-visiting-rule? (visited) "Whether only one node is visited maximally twice in VISITED." (let ((tally (make-hash-table))) (loop for node in visited do (cond ((and (gethash (car node) tally) (small-cave? node)) (incf (gethash (car node) tally))) (T (setf (gethash (car node) tally) 1)))) ;;Only one element can occur twice. (>= 1 (loop for v being the hash-value of tally summing ;;The score. (cond ;;Occuring once is not interesting. ((= v 1) 0) ;;Occuring twice should only happen once. ((= v 2) 1) ;;Violation, register violation by contributing to score more than 1. (T 2)))))) ;;1 1 1 ok since no number is greater than 1. (abides-part2-cave-visiting-rule? '((a T) (start T) (b nil))) ;;2 1 ok since only one number is greater than 1. (abides-part2-cave-visiting-rule? '((a T) (start T) (a T))) ;;3 1 not ok since one number is greater than 2. (abides-part2-cave-visiting-rule? '((a T) (start T) (a T) (a T))) ;;2 1 2 not ok since more than one number is = 2. (abides-part2-cave-visiting-rule? '((a T) (start T) (a T) (start T))) (defun neighbours-of-node (cave-system node-name) "The neighbouring nodes of the node with NODE-NAME in a CAVE-SYSTEM." (loop for node in cave-system when (eql node-name (car (first node))) collect (second node) when (eql node-name (car (second node))) collect (first node))) (neighbours-of-node (input 12 'toy-example) 'start) (input 12 'toy-example) (defun submarine-explore (cave-system start-from-node visited &optional part2-rules?) "Follow all possible connected caves. Recursively add 1 once node \"end\" is reached. CAVE-SYSTEM is determined by #'input for this day." (cond ((eql 'end (caar visited)) 1) ((or (and (small-cave? (car visited)) ;;Not: we're in a termination condition. (not (if part2-rules? (abides-part2-cave-visiting-rule? visited) (once-in-path? (car visited) visited)))) (eql 'start (caar visited))) 0) (T (loop for n in (neighbours-of-node cave-system start-from-node) sum (submarine-explore cave-system (car n) (cons n visited) part2-rules?))))) ;;10 (submarine-explore (input 12 'toy-example) 'start nil) ;;19 (submarine-explore (input 12 'middle-example) 'start nil) ;;226 (submarine-explore (input 12 'example) 'start nil) ;;3802 (submarine-explore (input 12 'full) 'start nil) ;;36 (submarine-explore (input 12 'toy-example) 'start nil T) ;;103 (submarine-explore (input 12 'middle-example) 'start nil T) ;;3509 (submarine-explore (input 12 'example) 'start nil T) (defmethod solution ((day (eql 12)) (variant (eql 'part1)) source) "The number of paths through the cave system (each small cave is visited at most once)." (submarine-explore (input day source) 'start nil)) (is 12 'part1 226) (defmethod solution ((day (eql 12)) (variant (eql 'part2)) source) "The number of paths through the cave system (allowing a single small cave to be visited twice)." (submarine-explore (input day source) 'start nil T)) (is 12 'part2 3509)
5,706
Common Lisp
.lisp
118
42.915254
251
0.663016
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
c1db64bc18c0020729592a7387942d330f4e390474762476865d8b8faf76bee5
41,818
[ -1 ]
41,819
23.lisp
b-steger_adventofcode2021/src/23.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule amphipod (or "A" "B" "C" "D") (:lambda (input) (cond ((string= "A" input) 'a) ((string= "B" input) 'b) ((string= "C" input) 'c) ((string= "D" input) 'd)))) (parse 'amphipod "A") (defrule ignorable-painting (* (or " " "#" "." new))) (defrule room-slice (and ignorable-painting amphipod ignorable-painting amphipod ignorable-painting amphipod ignorable-painting amphipod ignorable-painting) (:lambda (input) (let ((rooma (elt input 1)) (roomb (elt input 3)) (roomc (elt input 5)) (roomd (elt input 7))) (list rooma roomb roomc roomd)))) (defrule burrow (+ room-slice) (:lambda (input) (list (mapcar #'first input) (mapcar #'second input) (mapcar #'third input) (mapcar #'fourth input)))) (defmethod input ((day (eql 23)) source) "A burrow listing sorted side rooms with unorganized amphipods (symbols 'A 'B 'C 'D). The side rooms are lists which behave like stacks, i.e. the first entry is the nearest to the hallway." (parse 'burrow (read-file 23 source))) (input 23 'example) ;;;; Solution #| Reminds of day 7, but sounds more like a job for Prolog this time. → Screamer. (Edit: I stumbled over the solution while I prepared the rule explanations - I did not follow the Screamer path further. Still, I use Screamer in #'simple-path and #'shortest-graph-path.) |# #| World representation: A---B---C---D---E---F---G hallway (edge weights 1 2 2 2 2 1) \ / \ / \ / \ / (edge weights 2 2 2 2 2 2 2 2) H L P U level 0 (T is not allowed in ordinary lambda lists) | | | | (edge weights 1 1 1 1) I M Q V level 1 (ignored in part1) | | | | (edge weights 1 1 1 1) J N R W level 2 (ignored in part1) | | | | (edge weights 1 1 1 1) K O S X level 3 As an array: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 A B C D E F G H I J K L M N O P Q R S U V W X Input positions: part1: ((7 10) (11 14) (15 18) (19 22)) part2: ((7 8 9 10) (11 12 13 14) (15 16 17 18) (19 20 21 22)) Animal type mapping: A→1 B→2 C→3 D→4. (0 is used for the empty space in the world array.) Only the animal type is recorded, not the identity. |# (defparameter *animal-map* '(reserved a b c d) "The map of animals for puzzle 23.") (defparameter *node-map* '(a b c d e f g h i j k l m n o p q r s u v w x) "The nodes of the world graph of puzzle 23.") (defun edges (part2?) "All edges of the world of puzzle 23 with the PART2? modification if wished." (append ;;The edges of the hallway. '((a b 1) (b c 2) (c d 2) (d e 2) (e f 2) (f g 1) (b h 2) (h c 2) (c l 2) (l d 2) (d p 2) (p e 2) (e u 2) (u f 2)) ;;The edges of the side rooms. (if part2? '((h i 1) (i j 1) (j k 1) (l m 1) (m n 1) (n o 1) (p q 1) (q r 1) (r s 1) (u v 1) (v w 1) (w x 1)) '((h k 1) (l o 1) (p s 1) (u x 1))))) (defun 23-input (source &key part2? array?) "Input of day 23 with customizations. If PART2? is non-nil, enlarge the world and add the extra animals as required by the spec. If ARRAY? is non-nil, return the initial world state as an array." (let* ((animals-part1 (input 23 source)) (animals-in-rooms (if (or part2? array?) (mapcar (lambda (x a b) (list (first x) a b (second x))) animals-part1 (if part2? '(D C B A) '(nil nil nil nil)) (if part2? '(D B A C) '(nil nil nil nil))) animals-part1)) (animals-mapped-to-numbers (loop for room in animals-in-rooms collect (mapcar (lambda (x) (case x (a 1) (b 2) (c 3) (d 4) (T 0))) room)))) (if array? (make-array (length *node-map*) :element-type 'fixnum :initial-contents (apply #'concatenate 'cons (cons '(0 0 0 0 0 0 0) animals-mapped-to-numbers))) animals-in-rooms))) (23-input 'example :part2? nil :array? T) (23-input 'example :part2? T :array? T) (defun quick-world (a b c d e f g h i j k l m n o p q r s u v w x) "Quickly represent world states (and get convenient argument highlights by the editor)." (make-array (length *node-map*) :element-type 'fixnum :initial-contents (list a b c d e f g h i j k l m n o p q r s u v w x))) (defun world-with-room-configuration (&key animal-type (level0 0) (level1 0) (level2 0) (level3 0)) "Return a world where the room for ANIMAl-TYPE is filled with LEVEL0 LEVEL1 LEVEL2 LEVEL3." (cond ((= 1 animal-type) (quick-world 0 0 0 0 0 0 0 level0 level1 level2 level3 0 0 0 0 0 0 0 0 0 0 0 0)) ((= 2 animal-type) (quick-world 0 0 0 0 0 0 0 0 0 0 0 level0 level1 level2 level3 0 0 0 0 0 0 0 0)) ((= 3 animal-type) (quick-world 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 level0 level1 level2 level3 0 0 0 0)) ((= 4 animal-type) (quick-world 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 level0 level1 level2 level3)) (T (error "Wrong animal type.")))) (defun diashow (worlds) "Render each world in WORLDS in the debugger." (when worlds (break "~A" ;;Prevents #n= and #n# syntax (^= manually shadow *print-circle* T). (apply #'format nil "~%############# #~A~A ~A ~A ~A ~A~A# ###~A ~A ~A ~A### #~A ~A ~A ~A# #~A ~A ~A ~A# #~A ~A ~A ~A# #########" (let ((rotate-rooms (list 0 1 2 3 4 5 6 7 11 15 19 8 12 16 20 9 13 17 21 10 14 18 22))) (mapcar (lambda (x) (let ((value (aref (car worlds) x))) (if (= 0 value) " " value))) rotate-rooms)))) (diashow (rest worlds)))) #|(diashow (list (quick-world 4 3 2 1 2 3 4 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2) (quick-world 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1)))|# #| World animation: routing. |# (defun neighbouring-nodes (edges node-name) "The neighbouring nodes of NODE-NAME. Also see #'neighbours-of-node." (loop for edge in edges when (eql node-name (first edge)) collect (second edge) when (eql node-name (second edge)) collect (first edge))) (neighbouring-nodes (edges T) 'l) (defclass graph-node () ((name :initform nil :initarg :name :accessor name) (visited? :initform nil :initarg :visited? :accessor visited?) (neighbours :initform nil :initarg :neighbours :accessor neighbours))) (defun 23-world (part2?) "A hash table containing instances of graph-node." (let ((edges (edges part2?)) (world (make-hash-table))) (loop for node in *node-map* do (setf (gethash node world) (make-instance 'graph-node :name node :neighbours (neighbouring-nodes edges node)))) world)) (screamer::defun simple-path (world from to) "Non-deterministic function which finds a path whose node list is unique. (Adapted from the example 3 of the Screamer manual / screams.lisp of the Quicklisp package.)" (when (visited? (gethash from world)) (screamer:fail)) ;;This will be undone upon backtracking. (screamer:local (setf (visited? (gethash from world)) T)) (screamer:either (progn (unless (eq from to) (screamer:fail)) (list from)) (cons from (simple-path world (screamer:a-member-of (neighbours (gethash from world))) to)))) (screamer:all-values (simple-path (23-world T) 'a 'c)) (defun shortest-graph-path (world edges from to &key array-index-representation?) "Shortest path between the two nodes FROM and TO in WORLD graph (use #'23-world), applying the cost information from EDGES (use #'edges). Uses a non-deterministic approach internally. ARRAY-REPRESENTATION? returns world indices instead of letters/symbols and removes the initial starting node." (flet ((path-cost (path) "The sum of the edge costs of PATH." (loop for (a . d) on path when d sum (third (find-if (lambda (x) (or (and (equal a (first x)) (equal (car d) (second x))) (and (equal a (second x)) (equal (car d) (first x))))) edges))))) (let* ((paths (screamer:all-values (simple-path world from to))) (shortest-path (first (sort paths (lambda (x y) (< (path-cost x) (path-cost y))))))) (values (if array-index-representation? (when shortest-path (make-array (1- (length shortest-path)) :element-type 'fixnum :initial-contents (rest (mapcar (lambda (x) (position x *node-map*)) shortest-path)))) shortest-path) (path-cost shortest-path))))) (shortest-graph-path (23-world T) (edges T) 'a 'x :array-index-representation? nil) (defun routing-lut (world edges &key array-index-representation?) "A lookup table which contains the cross join of all nodes (a list with the shortest path and its cost). Realized as a two-dimensional array with the mapping from *node-map*. WORLD and EDGES must match the wished puzzle part. As *node-map* is used for both puzzle parts, part 1 is free to ignore unused indices. ARRAY-INDEX-REPRESENTATION? is passed to #'shortest-graph-path unchanged." (make-array (list (length *node-map*) (length *node-map*)) :initial-contents (loop for from in *node-map* collect (loop for to in *node-map* collect (multiple-value-list (shortest-graph-path world edges from to :array-index-representation? array-index-representation?)))))) (routing-lut (23-world nil) (edges nil) :array-index-representation? T) #| World rules. |# (defun animals-sorted? (world part2?) "Whether all animals are in their respective room (termination condition)." (and ;;Empty hallway (cl:and is a macro → fast failure). (= 0 (aref world 0)) (= 0 (aref world 1)) (= 0 (aref world 2)) (= 0 (aref world 3)) (= 0 (aref world 4)) (= 0 (aref world 5)) (= 0 (aref world 6)) ;;Each room (written on one line each) has only its respective animal type. (= 1 (aref world 7)) (= 1 (aref world 10)) (= 2 (aref world 11)) (= 2 (aref world 14)) (= 3 (aref world 15)) (= 3 (aref world 18)) (= 4 (aref world 19)) (= 4 (aref world 22)) (if part2? (and (= 1 (aref world 8)) (= 1 (aref world 9)) (= 2 (aref world 12)) (= 2 (aref world 13)) (= 3 (aref world 16)) (= 3 (aref world 17)) (= 4 (aref world 20)) (= 4 (aref world 21))) T))) (animals-sorted? (quick-world 0 0 0 0 0 0 0 1 0 0 1 2 0 0 2 3 0 0 3 4 0 0 4) nil) (animals-sorted? (quick-world 0 0 0 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4) T) (defun free-room-node (&key animal-type world part2? (level 0) last-empty-node) "Helper for moving into a room. Return the next free room node (as index) or nil. The non-full room must be empty or only inhabitated by animals of the same ANIMAL-TYPE. Assumption: all other animals in the room have moved to level 3 if possible. (Given since this function itself is used for movements of others.) LEVEL: room nodes nearest to the hallway are level 0. Part 1 will jump from level 0 to 3. Only ANIMAL-TYPE WORLD PART2? are part of the public interface." ;;7: skip the hallway; 4: size of room; 1-: first room node is zero-indexed (let* ((new-node (+ 7 level (* 4 (1- animal-type)))) (new-empty? (= 0 (aref world new-node))) (new-empty-node (if new-empty? new-node last-empty-node)) (correct-animal-type? (= animal-type (aref world new-node)))) (when (or new-empty? correct-animal-type?) ;;3: The node farthest from the hallway is at level 3, irrespective of part1/part2. (if (< level 3) (free-room-node :animal-type animal-type :world world :part2? part2? ;;3: there is only one recursive call for part1. :level (if part2? (1+ level) 3) :last-empty-node new-empty-node) new-empty-node)))) (free-room-node :animal-type 1 :world (quick-world 0 0 0 0 0 0 0 0 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4) :part2? T) (free-room-node :animal-type 4 :world (quick-world 0 0 0 0 0 0 0 0 1 1 2 2 2 2 2 0 0 0 0 0 0 1 2) :part2? T) (defun outgoing-animal-node (&key animal-type world part2? (level 0) first-nonempty-node found-wrong-in-room?) "Helper for moving out of a room. Returns the node in an ANIMAL-TYPE-side-room of the animal nearest to the hallway. NIL if the room is empty, or if the existing animals are all of the same, correct type in the room in question. Only ANIMAL-TYPE WORLD PART2? are part of the public interface." ;;Magic numbers see #'free-room-node. (let* ((new-node (+ 7 level (* 4 (1- animal-type)))) (matching-animal-type? (= animal-type (aref world new-node))) (new-empty? (= 0 (aref world new-node))) (new-first-nonempty-node (or first-nonempty-node (unless new-empty? new-node))) (new-found-wrong-in-room? (or found-wrong-in-room? (and (not new-empty?) (not matching-animal-type?))))) (cond ((< level 3) (outgoing-animal-node :animal-type animal-type :world world :part2? part2? :level (if part2? (1+ level) 3) :first-nonempty-node new-first-nonempty-node :found-wrong-in-room? new-found-wrong-in-room?)) (new-found-wrong-in-room? new-first-nonempty-node)))) (outgoing-animal-node :animal-type 4 :world (quick-world 0 0 0 0 0 0 0 0 1 1 1 2 2 2 2 0 0 0 0 0 4 4 3) :part2? T) (defun room-movement-lut (&key part2? in?) "Calculate all performed calls to #'free-room-node (if IN? is non-nil) or to #'outgoing-animal-node (if IN? is nil). Returns a multidimensional array with the dimensions animal-type level0 [level1 level2] level3. (Actually calculates illogical calls, too. This is not a problem; see the discussion in the docstring of #'free-room-node.)" (let ((animal-types '(0 1 2 3 4)) (rooms '(1 2 3 4))) (make-array (if part2? (list (length rooms) (length animal-types) (length animal-types) (length animal-types) (length animal-types)) (list (length rooms) (length animal-types) (length animal-types))) :element-type '(or null fixnum) :initial-contents (if part2? (loop for room in rooms collect (loop for level0 in animal-types collect (loop for level1 in animal-types collect (loop for level2 in animal-types collect (loop for level3 in animal-types collect (funcall (if in? #'free-room-node #'outgoing-animal-node) :animal-type room :part2? part2? :world (world-with-room-configuration :animal-type room :level0 level0 :level1 level1 :level2 level2 :level3 level3))))))) (loop for room in rooms collect (loop for level0 in animal-types collect (loop for level3 in animal-types collect (funcall (if in? #'free-room-node #'outgoing-animal-node) :animal-type room :part2? part2? :world (world-with-room-configuration :animal-type room :level0 level0 :level3 level3))))))))) (room-movement-lut :in? T :part2? T) (defun can-move? (&key world from to routing-lut) "Whether the animal at node FROM can move unhindered to node TO in WORLD." (declare (optimize speed)) (every (lambda (x) (= 0 (aref (the (simple-array fixnum *) world) x))) (the (simple-array fixnum *) (first (aref (the (simple-array T (23 23)) routing-lut) from to))))) (can-move? :world (quick-world 0 4 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0) :from 1 :to 22 :routing-lut (routing-lut (23-world T) (edges T) :array-index-representation? T)) (defun valid-moves (&key world part2? routing-lut in-lut out-lut) "Return possible moves in a WORLD. Result format: list of (list start end). This function returns a single move if an animal can reach its room unhindered. This is ok since the animals must cover their distances one day anyway. → Choice points are only introduced when there are real decisions." ;;THINK: possibly optimize the solution by sorting the return value by cost. (declare (optimize speed) (type (simple-array fixnum *) world)) ;;1. Get the next free (and legal) nodes per room for hallway animals. (let* ((room1-node (if part2? (locally (declare (type (simple-array (or null fixnum) (4 5 5 5 5)) in-lut)) (aref in-lut 0 (aref world 7) (aref world 8) (aref world 9) (aref world 10))) (locally (declare (type (simple-array (or null fixnum) (4 5 5)) in-lut)) (aref in-lut 0 (aref world 7) (aref world 10))))) (room2-node (if part2? (locally (declare (type (simple-array (or null fixnum) (4 5 5 5 5)) in-lut)) (aref in-lut 1 (aref world 11) (aref world 12) (aref world 13) (aref world 14))) (locally (declare (type (simple-array (or null fixnum) (4 5 5)) in-lut)) (aref in-lut 1 (aref world 11) (aref world 14))))) (room3-node (if part2? (locally (declare (type (simple-array (or null fixnum) (4 5 5 5 5)) in-lut)) (aref in-lut 2 (aref world 15) (aref world 16) (aref world 17) (aref world 18))) (locally (declare (type (simple-array (or null fixnum) (4 5 5)) in-lut)) (aref in-lut 2 (aref world 15) (aref world 18))))) (room4-node (if part2? (locally (declare (type (simple-array (or null fixnum) (4 5 5 5 5)) in-lut)) (aref in-lut 3 (aref world 19) (aref world 20) (aref world 21) (aref world 22))) (locally (declare (type (simple-array (or null fixnum) (4 5 5)) in-lut)) (aref in-lut 3 (aref world 19) (aref world 22)))))) ;;2. All animals in the hallway should check whether the path is free to those next free nodes. If there is such a possibility, return it. (or (loop for i from 0 below 7 do (let* ((animal (aref world i)) (to (cond ((= 1 animal) room1-node) ((= 2 animal) room2-node) ((= 3 animal) room3-node) ((= 4 animal) room4-node) (T 0)))) (when (and (< 0 animal) to (can-move? :world world :from i :to to :routing-lut routing-lut)) ;;Move instantly. (return (list (list i to)))))) ;;3. The animals nearest to the hallway of each room must move out to the hallway. Collect all free paths. ;;THINK: optimize with heuristics? → Certain types do not have to move to A or G etc. → True? (let* ((room1-launch-node (if part2? (locally (declare (type (simple-array (or null fixnum) (4 5 5 5 5)) out-lut)) (aref out-lut 0 (aref world 7) (aref world 8) (aref world 9) (aref world 10))) (locally (declare (type (simple-array (or null fixnum) (4 5 5)) out-lut)) (aref out-lut 0 (aref world 7) (aref world 10))))) (room2-launch-node (if part2? (locally (declare (type (simple-array (or null fixnum) (4 5 5 5 5)) out-lut)) (aref out-lut 1 (aref world 11) (aref world 12) (aref world 13) (aref world 14))) (locally (declare (type (simple-array (or null fixnum) (4 5 5)) out-lut)) (aref out-lut 1 (aref world 11) (aref world 14))))) (room3-launch-node (if part2? (locally (declare (type (simple-array (or null fixnum) (4 5 5 5 5)) out-lut)) (aref out-lut 2 (aref world 15) (aref world 16) (aref world 17) (aref world 18))) (locally (declare (type (simple-array (or null fixnum) (4 5 5)) out-lut)) (aref out-lut 2 (aref world 15) (aref world 18))))) (room4-launch-node (if part2? (locally (declare (type (simple-array (or null fixnum) (4 5 5 5 5)) out-lut)) (aref out-lut 3 (aref world 19) (aref world 20) (aref world 21) (aref world 22))) (locally (declare (type (simple-array (or null fixnum) (4 5 5)) out-lut)) (aref out-lut 3 (aref world 19) (aref world 22)))))) (loop for node in (list room1-launch-node room2-launch-node room3-launch-node room4-launch-node) when node append (loop for i from 0 below 7 when (can-move? :world world :from node :to i :routing-lut routing-lut) collect (list node i))))))) (let ((routing-lut (routing-lut (23-world T) (edges T) :array-index-representation? T)) (in-lut (room-movement-lut :in? T :part2? T)) (out-lut (room-movement-lut :in? nil :part2? T))) (loop for world in (list (quick-world 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0) (23-input T :part2? T :array? T) ;;This is the example, but the animal at 11 (L) has moved to 3 (D). (quick-world 0 0 0 3 0 0 0 2 4 4 1 0 3 2 4 2 2 1 3 4 1 3 1) (quick-world 2 0 0 0 0 0 0 0 0 0 1 3 0 0 4 2 0 0 3 4 0 0 1) (quick-world 2 1 0 0 0 0 0 0 0 0 0 3 0 0 4 2 0 0 3 4 0 0 1)) collect (valid-moves :world world :part2? T :routing-lut routing-lut :in-lut in-lut :out-lut out-lut))) (defun move-animal (&key world from to destructively?) "Move animal at FROM to TO without any checks." (let ((result-world (if destructively? world (copy-seq world)))) (setf (aref result-world to) (aref result-world from) (aref result-world from) 0) result-world)) (let ((world (23-input T :part2? T :array? T))) (move-animal :world world :from 7 :to 1 :destructively? T) world) (defun organize-animals (&key routing-lut in-lut out-lut part2? (running-score 0)) "Try out each valid move and recursively continue until all animals are sorted. Prunes the search tree by stopping as soon as the internal RUNNING-SCORE is higher than the score of a previously found solution. Needs additional context such as the one provided by #'23-solution." (declare (special *minimal-score* *world*)) ;;(diashow (list *world*)) (when (< running-score *minimal-score*) (if (animals-sorted? *world* part2?) ;;The new score is lower than *minimal-score*, i.e. a better solution is found. (setf *minimal-score* running-score) (loop for move in (valid-moves :world *world* :part2? part2? :routing-lut routing-lut :in-lut in-lut :out-lut out-lut) do (progn (move-animal :world *world* :from (first move) :to (second move) :destructively? T) (organize-animals :routing-lut routing-lut :in-lut in-lut :out-lut out-lut :part2? part2? :running-score (+ running-score (* (second (aref routing-lut (first move) (second move))) ;;#'second: animal has already moved. (let ((animal-type (aref *world* (second move)))) (cond ((= 1 animal-type) 1) ((= 2 animal-type) 10) ((= 3 animal-type) 100) ((= 4 animal-type) 1000) (T 0)))))) ;;Backtrack for the next valid move. (move-animal :world *world* :from (second move) :to (first move) :destructively? T)))))) (defun 23-solution (&key source part2?) "Call #'organize-animals with the needed context." (let ((*world* (23-input source :part2? part2? :array? T)) ;;Start with something worser than the worst case: Assume a part2 world where each of the 16 animals (of type D) moves from node K to node X. (*minimal-score* (let* ((part2? T) (lut (routing-lut (23-world part2?) (edges part2?))) (k-to-x-cost (second (aref lut 10 22)))) (* 16 1000 k-to-x-cost)))) (declare (special *minimal-score* *world*)) (organize-animals :routing-lut (routing-lut (23-world part2?) (edges part2?) :array-index-representation? T) :in-lut (room-movement-lut :in? T :part2? part2?) :out-lut (room-movement-lut :in? nil :part2? part2?) :part2? part2?) *minimal-score*)) (defmethod solution ((day (eql 23)) (variant (eql 'part1)) source) "The cost of the most economical way to organize amphipods which are mapped according to the folded diagram." (23-solution :source source :part2? nil)) (is 23 'part1 12521) (defmethod solution ((day (eql 23)) (variant (eql 'part2)) source) "The cost of the most economical way to organize amphipods which are mapped according to the unfolded diagram." (23-solution :source source :part2? T)) (defmethod expect ((day (eql 23)) (variant (eql 'part2))) 44169) ;;Takes as long as all other puzzles together (i.e. some seconds). So what. Let's call it a day. ;;(is 23 'part2 44169)
28,825
Common Lisp
.lisp
490
45.093878
251
0.548416
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
43c4452296f37e0281c98e417bac0748dda39471895afda613a335e13c14d944
41,819
[ -1 ]
41,820
14.lisp
b-steger_adventofcode2021/src/14.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) #| This puzzle seems similar in spirit to the one of day 6, which also tried to derivate the input as good as possible. So, how is the problem reduced? What are the "histogrammable" parts? The letters, obviously. Now, what produces a letter? A pair of letters. Thought reversal again: a conversion rule not only produces a letter, it also produces two pairs. "AB -> C" can be read as "AB -> AC,CB" (with the contract that all neighbouring pairs share the same letter, which is explicitly guaranteed). Manual analysis of the pairs produced by the example reveals that all output pairs of the newly introduced conversion rule appear as a pair on the left side in each original conversion rule. Which means that the count of a letter is determined by the histogram of pairs (i.e. count the number of times "B" appears on the left side of a pair). This has to be verified on the input, though. Adapting the parser to this promising situation... |# ;;;; Parser (defrule 14-template (+ (character-ranges (#\A #\Z))) (:lambda (input) (loop for (a . d) on input while d collect (read-from-string (format nil "~A~A" a (first d)))))) ;;The final count needs to include the righmost character, too. But really only the last character which remains the same throughout the whole execution. Which means that it can be conveniently read from the puzzle input. ;;Count: (NN NC CB) → two N (two symbols begin with N), one C (one symbol begins with C) and B, the rightmost character. (parse '14-template "NNCB") (defrule 14-insertion-rule (and (character-ranges (#\A #\Z)) (character-ranges (#\A #\Z)) " -> " (character-ranges (#\A #\Z))) (:lambda (input) ;;List of left pair, right pair and original left side (matching pair). ;;Reasoning for interning as symbols: the input is of manageable size (input is trusted) and SBCL can compare with an #'eq (i.e. a single VOP). (list (read-from-string (format nil "~A~A" (elt input 0) (elt input 3))) (read-from-string (format nil "~A~A" (elt input 3) (elt input 1))) (read-from-string (format nil "~A~A" (elt input 0) (elt input 1)))))) (parse '14-insertion-rule "CH -> B") (defrule 14-file (and 14-template new new (+ (and 14-insertion-rule (? new)))) (:lambda (input) ;;List of template and hashtable mapping matching-pairs to their expansions (a list of size 2). (list (elt input 0) (let ((ht (make-hash-table :test 'eq))) (loop for rule in (mapcar #'first (elt input 3)) do (setf (gethash (third rule) ht) (subseq rule 0 2))) ht)))) (parse '14-file "NNCB CH -> B HH -> N ") (defmethod input ((day (eql 14)) source) "A polymer template (first item) and a hashtable with insertion rules indexed by the matching pair (second item)." (parse '14-file (read-file 14 source))) (input 14 T) (input 14 'full) ;;;; Solution #| First, check whether left and right pairs appear in the list of the matching pairs. |# (defun produced-pairs (input) "List of pairs which are produced by the insertion rules." (remove-duplicates (loop for v being the hash-values of (second input) collect (first v) collect (second v)))) (produced-pairs (input 14 T)) (defun check-assumption-for-14 (input) "Warns if produced pairs do not show up in the list of matching pairs." ;;matching-pairs: length 100 (no duplicates). (let* ((matching-pairs (loop for k being the hash-keys of (second input) collect k)) (produced-pairs (produced-pairs input))) (unless (subsetp produced-pairs matching-pairs :test #'eq) (warn "Assumptions for puzzle 14 do not hold, check the approach of the solution. Continuing nevertheless...")) T)) (check-assumption-for-14 (input 14 'full)) #| The workbench, the histogram. |# (defun initial-histogram (input) "An histogram with pair symbols as key and 0 as the default value, realized as hash table. Initialized with INPUT's polymer template." (let ((ht (make-hash-table :test 'eq))) (loop for matching-pair in (loop for k being the hash-keys of (second input) collect k) do (setf (gethash matching-pair ht) 0)) (loop for produced-pair in (produced-pairs input) do (setf (gethash produced-pair ht) 0)) ;;Initialization (loop for template-pair in (first input) do (incf (gethash template-pair ht))) ht)) (initial-histogram (input 14 T)) (initial-histogram (input 14 'full)) #| What happens during a step? NNCB = NN NC CB NCNBCHB = NC CN NB BC CH HB NBCCNBBBCBHCB = NB BC CC CN NB BB BB BC CB BH HC CB Each pair contributes two new pairs. But all existing pairs are destroyed. Algorithm: 1. Identify all exisiting pairs (i.e. having count > 0). 2. Gather the produced pairs and add them to a fresh histogram (existing-count times). |# (defun polymer-expand (production-lut histogram steps-left) "Expand the polymer: replace each pair with two pairs according to the insertion rules." (if (= 0 steps-left) histogram (polymer-expand production-lut (let* ((fresh-histogram (make-hash-table :test 'eq)) (existing-pairs (loop for k being the hash-key of histogram for v being the hash-value of histogram when (> v 0) collect k)) ;;Gather the produced pairs... (produced-pairs (loop for pair in existing-pairs collect (list (gethash pair production-lut) ;;... and how many times they are introduced. (gethash pair histogram))))) ;;Add the produced pairs to the histogram. (mapcar (lambda (x) (loop for pair in (first x) do (incf (gethash pair fresh-histogram 0) (second x)))) produced-pairs) fresh-histogram) (1- steps-left)))) (defun puzzle-14-result (input steps) "Count the number of letters in the expanded-polymer and subtract the least common element count from the most common element count." (check-assumption-for-14 input) (let* ((expanded-polymer (polymer-expand (second input) (initial-histogram input) steps)) (tally (make-hash-table))) ;;Sum all first elements of pairs (grouped by letter). (loop for k being the hash-key of expanded-polymer for v being the hash-value of expanded-polymer do (incf (gethash (read-from-string (subseq (format nil ":~A" k) 0 2)) tally 0) v)) ;;The rightmost character of the template survived all transformations and is not reachable by the counting method. (incf (gethash (read-from-string (format nil ":~A" (subseq (format nil "~A" (car (last (first input)))) 1))) tally)) (- (loop for k being the hash-key of tally for v being the hash-value of tally maximize v) (loop for k being the hash-key of tally for v being the hash-value of tally minimize v)))) (defmethod solution ((day (eql 14)) (variant (eql 'part1)) source) "The difference between the most common letter count and the least common letter count, for 10 steps." (puzzle-14-result (input 14 source) 10)) (is 14 'part1 1588) (defmethod solution ((day (eql 14)) (variant (eql 'part2)) source) "The difference between the most common letter count and the least common letter count, for 40 steps." (puzzle-14-result (input 14 source) 40)) (is 14 'part2 2188189693529)
8,591
Common Lisp
.lisp
160
46.39375
251
0.663455
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
ff28ec77d538eaee7d8cf05686fc88560c62d39d82b4a986db43f9bb8e9cbc83
41,820
[ -1 ]
41,821
report.lisp
b-steger_adventofcode2021/src/report.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;Verify that all examples are still computed correctly. (eval-when (:execute) (loop for day in ;;No examples for 17 and 24. ;;Attention: value for 21 part2 is effectively cached. '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 25) collect (list :day day :part1 (is day 'part1 (expect day 'part1) :register-expected-value? nil) :part2 (is day 'part2 (expect day 'part2) :register-expected-value? nil)))) ;;; Compute a solution. (eval-when (:execute) (let ((day 25)) (list :day day :part1 (solution day 'part1 'full) :part2 (solution day 'part2 'full)))) ;;; Compute the solutions. #| 39,829,984,311 processor cycles 4,101,255,536 bytes consed C-I gives: #<CONS {1035DB2867}> -------------------- A proper list: 0: (:DAY 1 :PART1 1681 :PART2 1704) 1: (:DAY 2 :PART1 1868935 :PART2 1965970888) 2: (:DAY 3 :PART1 4147524 :PART2 3570354) 3: (:DAY 4 :PART1 41503 :PART2 3178) 4: (:DAY 5 :PART1 5373 :PART2 21514) 5: (:DAY 6 :PART1 386755 :PART2 1732731810807) 6: (:DAY 7 :PART1 349357 :PART2 96708205) 7: (:DAY 8 :PART1 495 :PART2 1055164) 8: (:DAY 9 :PART1 502 :PART2 1330560) 9: (:DAY 10 :PART1 271245 :PART2 1685293086) 10: (:DAY 11 :PART1 1667 :PART2 488) 11: (:DAY 12 :PART1 3802 :PART2 99448) 12: (:DAY 13 :PART1 621 :PART2 "HKUJGAJZ") 13: (:DAY 14 :PART1 5656 :PART2 12271437788530) 14: (:DAY 15 :PART1 462 :PART2 2846) 15: (:DAY 16 :PART1 957 :PART2 744953223228) 16: (:DAY 18 :PART1 3494 :PART2 4712) 17: (:DAY 19 :PART1 320 :PART2 9655) 18: (:DAY 20 :PART1 5339 :PART2 18395) 19: (:DAY 21 :PART1 412344 :PART2 214924284932572) 20: (:DAY 22 :PART1 647062 :PART2 1319618626668022) 21: (:DAY 23 :PART1 13336 :PART2 53308) 22: (:DAY 24 :PART1 95299897999897 :PART2 31111121382151) 23: (:DAY 25 :PART1 492 :PART2 0) |# (eval-when (:execute) (time (loop for day in '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25) collect (list :day day :part1 (solution day 'part1 'full) :part2 (solution day 'part2 'full)))))
2,932
Common Lisp
.lisp
63
42.31746
251
0.672263
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
71e4e170594a0cf2aa9f7298b6e5992f314d5234159b2f2c1b8a2744fc1974fe
41,821
[ -1 ]
41,822
02.lisp
b-steger_adventofcode2021/src/02.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule command-forward (and "forward " integer) (:lambda (input) (let ((amount (elt input 1))) (list 'forward amount)))) (parse 'command-forward "forward 2") (defrule command-down (and "down " integer) (:lambda (input) (let ((amount (elt input 1))) (list 'down amount)))) (parse 'command-down "down 2") (defrule command-up (and "up " integer) (:lambda (input) (let ((amount (elt input 1))) (list 'up amount)))) (parse 'command-up "up 2") (defrule 02-file (+ (and (or command-forward command-down command-up) (? new))) (:lambda (input) (mapcar #'first input))) (defmethod input ((day (eql 2)) source) (parse '02-file (read-file day source))) (input 2 T) ;;;; Solution (defclass part1state () ((h-pos :initarg :h-pos :initform nil :accessor h-pos) (depth :initarg :depth :initform nil :accessor depth))) (defmethod forward! ((state part1state) units) (incf (h-pos state) units)) (defmethod down! ((state part1state) units) (incf (depth state) units)) (defmethod up! ((state part1state) units) (decf (depth state) units)) (defun 02-solution (day source state) "Apply commands to STATE (an instance of part1state or part2state) and return the updated score." (loop for command in (input day source) do (cond ((eq 'forward (car command)) (forward! state (cadr command))) ((eq 'up (car command)) (up! state (cadr command))) ((eq 'down (car command)) (down! state (cadr command))))) (* (h-pos state) (depth state))) (02-solution 2 'example (make-instance 'part1state :h-pos 0 :depth 0)) (defmethod solution ((day (eql 2)) (variant (eql 'part1)) source) "Call #'02-solution with an instance of part1state." (02-solution day source (make-instance 'part1state :h-pos 0 :depth 0))) (is 2 'part1 150) (defclass part2state (part1state) ((aim :initarg :aim :initform nil :accessor aim))) (defmethod forward! ((state part2state) units) (incf (h-pos state) units) (incf (depth state) (* (aim state) units))) (defmethod down! ((state part2state) units) (incf (aim state) units)) (defmethod up! ((state part2state) units) (decf (aim state) units)) (defmethod solution ((day (eql 2)) (variant (eql 'part2)) source) "Call #'02-solution with an instance of part2state." (02-solution day source (make-instance 'part2state :h-pos 0 :depth 0 :aim 0))) (is 2 'part2 900)
3,254
Common Lisp
.lisp
70
42.571429
251
0.686058
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
c4cfa2c5203a1aa28f07379ebb85d2cb3e30d1763f1f139cfa09c660d750c7e8
41,822
[ -1 ]
41,823
10.lisp
b-steger_adventofcode2021/src/10.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser #| Parsing! Parser error handling is the main task, which is why the input parser is kept lenient... |# (defrule 10-line (+ (or #\( #\) #\[ #\] #\{ #\} #\< #\>)) (:lambda (input) (text input))) (parse '10-line "[({(<(())[]>[[{[]{<()<>>") (defrule 10-file (and (+ (and 10-line (? new)))) (:lambda (input) (let ((entries (elt input 0))) (mapcar #'first entries)))) (defmethod input ((day (eql 10)) source) "Lists with text containing (+ (or #\( #\) #\[ #\] #\{ #\} #\< #\>))." (parse '10-file (read-file day source))) (input 10 T) (input 10 'full) ;;;; Solution ;;; These are the parsing rules for the puzzle grammar. ;;The following parsing rule 'chunk is designed to fail at position 0, allowing for a distinction in #'parsing-status. (defrule chunk (* (or chunk-a chunk-b chunk-c chunk-d))) (defrule chunk-a (and #\( chunk #\) )) (defrule chunk-b (and #\[ chunk #\] )) (defrule chunk-c (and #\{ chunk #\} )) (defrule chunk-d (and #\< chunk #\> )) (parse 'chunk "()") (parse 'chunk "[]") (parse 'chunk "([])") (parse 'chunk "{()()()}") (parse 'chunk "<([{}])>") (parse 'chunk "[<>({}){}[([])<>]]") (parse 'chunk "(((((((((())))))))))") (defun parsing-status (text &optional reverse?) "Whether TEXT parsed successfully ('success), is 'incomplete or corrupted, in which case this function returns the score of the unexpected character." (let ((position (handler-case (parse (if reverse? 'reversed-chunk 'chunk) text) (error (condition) (esrap-error-position condition)) (:no-error (production position success?) (declare (ignore production position success?)) 'success)))) (cond ((eql position 'success) position) ;;Incomplete: position of error is at the end. ((= (length text) position) 'incomplete) ;;Corrupted: position of error is before the end; return the score of the unexpected character. (T (let ((unexpected-character (elt text position))) (cond ((char= unexpected-character (if reverse? #\( #\) )) 3) ((char= unexpected-character (if reverse? #\[ #\] )) 57) ((char= unexpected-character (if reverse? #\{ #\} )) 1197) ((char= unexpected-character (if reverse? #\< #\> )) 25137))))))) (parsing-status "()") (parsing-status "(]") (parsing-status "(") ;;Incomplete incomplete corruped incomplete corrupted corrupted incomplete corrupted corrupted incomplete. (mapcar #'parsing-status (input 10 T)) (defmethod solution ((day (eql 10)) (variant (eql 'part1)) source) "Sum all syntax error scores." (reduce #'+ (remove-if-not #'numberp (mapcar #'parsing-status (input day source))))) (is 10 'part1 26397) #| Idea for the part2 task: parsing the reversed string will give the position of the first character that needs to be closed. Prepend/append the corresponding closing character and recurse. Comment: Coming from puzzle 15, I realize that this puzzle is inspired by the book "Data structures & algorithms" by Goodrich et al. which lists the required stack-based algorithm for this puzzle in the chapter 5.1.7 "Matching Parentheses and HTML Tags" (p. 205). |# (defrule reversed-chunk (* (or reversed-chunk-a reversed-chunk-b reversed-chunk-c reversed-chunk-d))) (defrule reversed-chunk-a (and #\) reversed-chunk #\( )) (defrule reversed-chunk-b (and #\] reversed-chunk #\[ )) (defrule reversed-chunk-c (and #\} reversed-chunk #\{ )) (defrule reversed-chunk-d (and #\> reversed-chunk #\< )) #|At >><)(<{][{[[>][))((<({([ ^ (Line 1, Column 6, Position 6) ... ↑|# ;;(parse 'reversed-chunk (reverse "[({(<(())[]>[[{[]{<()<>>")) (defun part1score2part2char (score) "Return the char associated with the syntax error score (for the reversed part2 task)." (cond ((symbolp score) score) ((= score 3) #\) ) ((= score 57) #\] ) ((= score 1197) #\} ) ((= score 25137) #\> ) (T score))) (defun complete (text gathered-chars) "Gather the missing closing parentheses." (let ((next-char (part1score2part2char (parsing-status text T)))) (if (eql 'success next-char) (reverse gathered-chars) (complete (format nil "~A~A" next-char text) (cons next-char gathered-chars))))) (complete (reverse "[({(<(())[]>[[{[]{<()<>>") nil) (defun part2char2part2score (char) "Determine the corresponding char from the (reversed) part1 char code." (cond ((char= char #\) ) 1) ((char= char #\] ) 2) ((char= char #\} ) 3) ((char= char #\> ) 4))) (defun puzzle10-linescore (&key (total 0) chars) "Determine the score of a line in the second task of puzzle 10." (if chars (puzzle10-linescore :total (+ (* 5 total) (part2char2part2score (first chars))) :chars (rest chars)) total)) (puzzle10-linescore :chars (list #\] #\) #\} #\> )) (defmethod solution ((day (eql 10)) (variant (eql 'part2)) source) "The median of the scores in the puzzle input." (let* ((sorted-scores (sort (loop for line in (input day source) when (eql 'incomplete (parsing-status line)) collect (puzzle10-linescore :chars (complete (reverse line) nil))) #'<)) (number-of-scores (length sorted-scores)) ;;Contract: number-of-scores is odd. (middle-position (floor number-of-scores 2))) (elt sorted-scores middle-position))) (is 10 'part2 288957)
6,453
Common Lisp
.lisp
124
45.975806
263
0.621056
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
4c3c2b728f4ccf89682f67eb888d2387cd3fec4232ea7f6124ae3099bcb42b18
41,823
[ -1 ]
41,824
19-detour.lisp
b-steger_adventofcode2021/src/19-detour.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) #| Historical but working code which contributed to the development of the solution for the puzzle 19. The most interesting form is the definition of #'scanner-join-plan. |# (defun scanner-overlap? (scanner-report1 scanner-report2) "NIL if the two scanner reports do not overlap. (Otherwise, the list of intra-beacon distances for each listed beacon - hardly useful.)" (let ((beacons1 (distances-between-beacons scanner-report1)) (beacons2 (distances-between-beacons scanner-report2))) (remove-if (lambda (x) ;;Filter out distances to itself and random coincidences. (< (length x) 10)) (loop for outer in beacons1 append (loop for inner in beacons2 collect (intersection inner outer)))))) (scanner-overlap? (gethash 0 (input 19 T)) (gethash 2 (input 19 T))) (scanner-overlap? (gethash 0 (input 19 T)) (gethash 1 (input 19 T))) (scanner-overlap? (gethash 1 (input 19 T)) (gethash 3 (input 19 T))) (scanner-overlap? (gethash 2 (input 19 T)) (gethash 4 (input 19 T))) (scanner-overlap? (gethash 0 (input 19 'full)) (gethash 7 (input 19 'full))) #| Next: determine the join tree. |# (defun bidirectional-connections (input) "Computes the bidirectional connections between scanner regions." (loop for i from 0 below (hash-table-count input) append (loop for j from 0 below (hash-table-count input) when (and (/= i j) (scanner-overlap? (gethash i input) (gethash j input))) collect (list i j)))) #|=> ((0 1) (1 0) (1 3) (1 4) (2 4) (3 1) (4 1) (4 2)) => 0-1-3 | 4-2|# (bidirectional-connections (input 19 T)) #|(bidirectional-connections (input 19 'full)) ;;All regions are connected: ;;=> (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32) (remove-duplicates (sort (loop for item in (bidirectional-connections (input 19 'full)) append item) #'<))|# (defun scanner-join-plan (scanner-connections unvisited-ids) "Topologically sort UNVISITED-IDS such that a region can be grown by (ad-)joining scanner regions. Returns a list of scanner region pairs that need to join in order grow the existing, growing map. Each entry lists the scanner id belonging to the growing result region first." (when unvisited-ids (let ((next ;;The first pair with an unvisited id which does not link only unvisited ids. (loop for pair in scanner-connections when (and (not (and (member (first pair) unvisited-ids) (member (second pair) unvisited-ids))) (or (member (first pair) unvisited-ids) (member (second pair) unvisited-ids))) ;;The first entry should reference a region which belongs to the growing region. return (if (member (first pair) unvisited-ids) (reverse pair) pair)))) (if next (cons next (scanner-join-plan scanner-connections ;;Sort of (- unvisited-ids next) or (remove next unvisited-ids). (set-difference unvisited-ids next))) ;;Bootstrapping since all IDs are unvisited. ;;Instead of selecting the first pair which contains the bootstrapped scanner id, the recursive call is made instantly since the next one will always select the pair in question first. (scanner-join-plan scanner-connections (rest unvisited-ids)))))) ;;=> ((0 1) (1 3) (1 4) (4 2)) (scanner-join-plan (bidirectional-connections (input 19 T)) (loop for k being the hash-keys of (input 19 T) collect k))
4,701
Common Lisp
.lisp
79
49.544304
251
0.639437
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
fc4cca069e736c0675f63f660f4c21191b5f6b1c3bf2c2451bf8b62b1effda5b
41,824
[ -1 ]
41,825
19.lisp
b-steger_adventofcode2021/src/19.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule integer-z (and (? "-") integer) (:lambda (input) (let ((negativity-sign (elt input 0)) (positive-number (elt input 1))) (parse-integer (format nil "~@[~A~]~A" negativity-sign positive-number))))) (parse 'integer-z "123") (parse 'integer-z "-456") (defrule beacon-pos (and integer-z "," integer-z "," integer-z) (:lambda (input) ;;Actual X/Y/Z orientation is initially unknown, working with A/B/C. (let ((a (elt input 0)) (b (elt input 2)) (c (elt input 4))) (list a b c)))) (parse 'beacon-pos "-1,-2,1") (defrule scanner-report (and "--- scanner " integer " ---" new (+ (and beacon-pos (? new)))) (:lambda (input) (let ((id (elt input 1)) (beacons (elt input 4))) (list :id id :beacons (mapcar #'first beacons))))) (parse 'scanner-report "--- scanner 0 --- 0,2,1 4,1,1 3,-3,1 ") (defrule 19-file (+ (and scanner-report (? new))) (:lambda (input) (let ((scanner-reports (make-hash-table))) (loop for report in (mapcar #'first input) do (setf (gethash (getf report :id) scanner-reports) (getf report :beacons))) scanner-reports))) (defmethod input ((day (eql 19)) source) "Hash table mapping scanner ids → scanner reports. Each scanner report consists of a list of beacons, a vector represented as a list with a b and c values." (parse '19-file (read-file day source))) (input 19 T) (input 19 'full) ;;;; Solution #| Spatial join with join condition "12 points which share the same relative positioning". Naming conventions regarding the relative coordinate systems problem: Any vector in relation to scanner 0, i.e. in relation to 0/0/0 with default rotation is in GLOBAL space. As #'grow-scanner-region at the end of this file shows, this must not be scanner 0, but typically is (depends on the input file actually). Beacon vectors are typically in a rotated, LOCAL coordinate system. Local coordinate systems are numbered. Those numbers are called orientation-id. |# #| Calculate vectors-to-other-beacons for each beacon. Idea: all beacons in an overlapping area have the same distances towards each other. Identical beacons share identical distances. Think of the Voyager golden record cover image depicting the distances to our nearest pulsars, and how the distances remain the same, however this image is rotated. The distances between the beacons within a scanner report are independent of any coordinate system rotation. |# (defun distances-between-beacons (beacons) "Determine the manhattan distance matrix for BEACONS." (loop for b in beacons collect (loop for other-b in beacons collect ;;The manhattan distance of the vectors seems good enough, no need for vectors. (+ (abs (- (first b) (first other-b))) (abs (- (second b) (second other-b))) (abs (- (third b) (third other-b))))))) (distances-between-beacons (gethash 0 (input 19 T))) (equal (distances-between-beacons (getf (parse 'scanner-report "--- scanner 0 --- -618,-824,-621 -537,-823,-458 -447,-329,318 404,-588,-901 544,-627,-890 528,-643,409 -661,-816,-575 390,-675,-793 423,-701,434 -345,-311,381 459,-707,401 -485,-357,347") :beacons)) (distances-between-beacons (getf (parse 'scanner-report "--- scanner 1 --- 686,422,578 605,423,415 515,917,-361 -336,658,858 -476,619,847 -460,603,-452 729,430,532 -322,571,750 -355,545,-477 413,935,-424 -391,539,-444 553,889,-390") :beacons))) #| I made a detour during which I verified some assumptions about the input. See 19-detour.lisp. |# ;;Around 25 / 26 / 27 beacons per scanner. (remove-duplicates (loop for beacons being the hash-values of (input 19 'full) collect (length beacons))) #| Idea: find beacons by their position in the list / distance matrix. |# (defun raw-beacon-coordinates (beacons-left beacons-right) "Returns the twelve overlapping beacons and their vectors from the left and right scanner, respectively. NIL if the two scanner regions do not overlap." (let* ((distances-left (distances-between-beacons beacons-left)) (distances-right (distances-between-beacons beacons-right))) ;;List with list as elements. Elements represent the beacon vector in the left/right scanner coordinate system, respectively. (loop with i = 0 for outer in distances-left append (loop with j = 0 for inner in distances-right unless (< (length (intersection inner outer)) 12) collect (list (elt beacons-left i) (elt beacons-right j)) do (incf j)) do (incf i)))) (raw-beacon-coordinates (gethash 0 (input 19 T)) (gethash 1 (input 19 T))) (defun rotate-vector (vector orientation-id &optional reverse?) "Assuming A B C in a normalized coordinate system, rotate the vector such that it points towards the same direction in the target ORIENTATION-ID coordinate system. REVERSE? returns the original vector which was passed to a previous invocation of this function." (let ((a (first vector)) (b (second vector)) (c (third vector))) ;;(* 2 24): this function is used on raw beacon coordinates, for which the case of counter-rotated scanners must be considered. ;;I go for the full cartesian product in this place. (cond ;;abc ((= 0 orientation-id) (if reverse? (list (* 1 a) (* 1 b) (* 1 c)) (list (* 1 a) (* 1 b) (* 1 c)))) ((= 1 orientation-id) (if reverse? (list (* 1 a) (* 1 b) (* -1 c)) (list (* 1 a) (* 1 b) (* -1 c)))) ((= 2 orientation-id) (if reverse? (list (* 1 a) (* -1 b) (* 1 c)) (list (* 1 a) (* -1 b) (* 1 c)))) ((= 3 orientation-id) (if reverse? (list (* 1 a) (* -1 b) (* -1 c)) (list (* 1 a) (* -1 b) (* -1 c)))) ((= 4 orientation-id) (if reverse? (list (* -1 a) (* 1 b) (* 1 c)) (list (* -1 a) (* 1 b) (* 1 c)))) ((= 5 orientation-id) (if reverse? (list (* -1 a) (* 1 b) (* -1 c)) (list (* -1 a) (* 1 b) (* -1 c)))) ((= 6 orientation-id) (if reverse? (list (* -1 a) (* -1 b) (* 1 c)) (list (* -1 a) (* -1 b) (* 1 c)))) ((= 7 orientation-id) (if reverse? (list (* -1 a) (* -1 b) (* -1 c)) (list (* -1 a) (* -1 b) (* -1 c)))) ;;acb ((= 8 orientation-id) (if reverse? (list (* 1 a) (* 1 c) (* 1 b)) (list (* 1 a) (* 1 c) (* 1 b)))) ((= 9 orientation-id) (if reverse? (list (* 1 a) (* -1 c) (* 1 b)) (list (* 1 a) (* 1 c) (* -1 b)))) ((= 10 orientation-id) (if reverse? (list (* 1 a) (* 1 c) (* -1 b)) (list (* 1 a) (* -1 c) (* 1 b)))) ((= 11 orientation-id) (if reverse? (list (* 1 a) (* -1 c) (* -1 b)) (list (* 1 a) (* -1 c) (* -1 b)))) ((= 12 orientation-id) (if reverse? (list (* -1 a) (* 1 c) (* 1 b)) (list (* -1 a) (* 1 c) (* 1 b)))) ((= 13 orientation-id) (if reverse? (list (* -1 a) (* -1 c) (* 1 b)) (list (* -1 a) (* 1 c) (* -1 b)))) ((= 14 orientation-id) (if reverse? (list (* -1 a) (* 1 c) (* -1 b)) (list (* -1 a) (* -1 c) (* 1 b)))) ((= 15 orientation-id) (if reverse? (list (* -1 a) (* -1 c) (* -1 b)) (list (* -1 a) (* -1 c) (* -1 b)))) ;;bac ((= 16 orientation-id) (if reverse? (list (* 1 b) (* 1 a) (* 1 c)) (list (* 1 b) (* 1 a) (* 1 c)))) ((= 17 orientation-id) (if reverse? (list (* 1 b) (* 1 a) (* -1 c)) (list (* 1 b) (* 1 a) (* -1 c)))) ((= 18 orientation-id) (if reverse? (list (* -1 b) (* 1 a) (* 1 c)) (list (* 1 b) (* -1 a) (* 1 c)))) ((= 19 orientation-id) (if reverse? (list (* -1 b) (* 1 a) (* -1 c)) (list (* 1 b) (* -1 a) (* -1 c)))) ((= 20 orientation-id) (if reverse? (list (* 1 b) (* -1 a) (* 1 c)) (list (* -1 b) (* 1 a) (* 1 c)))) ((= 21 orientation-id) (if reverse? (list (* 1 b) (* -1 a) (* -1 c)) (list (* -1 b) (* 1 a) (* -1 c)))) ((= 22 orientation-id) (if reverse? (list (* -1 b) (* -1 a) (* 1 c)) (list (* -1 b) (* -1 a) (* 1 c)))) ((= 23 orientation-id) (if reverse? (list (* -1 b) (* -1 a) (* -1 c)) (list (* -1 b) (* -1 a) (* -1 c)))) ;;cab ((= 24 orientation-id) (if reverse? (list (* 1 b) (* 1 c) (* 1 a)) (list (* 1 c) (* 1 a) (* 1 b)))) ((= 25 orientation-id) (if reverse? (list (* 1 b) (* -1 c) (* 1 a)) (list (* 1 c) (* 1 a) (* -1 b)))) ((= 26 orientation-id) (if reverse? (list (* -1 b) (* 1 c) (* 1 a)) (list (* 1 c) (* -1 a) (* 1 b)))) ((= 27 orientation-id) (if reverse? (list (* -1 b) (* -1 c) (* 1 a)) (list (* 1 c) (* -1 a) (* -1 b)))) ((= 28 orientation-id) (if reverse? (list (* 1 b) (* 1 c) (* -1 a)) (list (* -1 c) (* 1 a) (* 1 b)))) ((= 29 orientation-id) (if reverse? (list (* 1 b) (* -1 c) (* -1 a)) (list (* -1 c) (* 1 a) (* -1 b)))) ((= 30 orientation-id) (if reverse? (list (* -1 b) (* 1 c) (* -1 a)) (list (* -1 c) (* -1 a) (* 1 b)))) ((= 31 orientation-id) (if reverse? (list (* -1 b) (* -1 c) (* -1 a)) (list (* -1 c) (* -1 a) (* -1 b)))) ;;bca ((= 32 orientation-id) (if reverse? (list (* 1 c) (* 1 a) (* 1 b)) (list (* 1 b) (* 1 c) (* 1 a)))) ((= 33 orientation-id) (if reverse? (list (* -1 c) (* 1 a) (* 1 b)) (list (* 1 b) (* 1 c) (* -1 a)))) ((= 34 orientation-id) (if reverse? (list (* 1 c) (* 1 a) (* -1 b)) (list (* 1 b) (* -1 c) (* 1 a)))) ((= 35 orientation-id) (if reverse? (list (* -1 c) (* 1 a) (* -1 b)) (list (* 1 b) (* -1 c) (* -1 a)))) ((= 36 orientation-id) (if reverse? (list (* 1 c) (* -1 a) (* 1 b)) (list (* -1 b) (* 1 c) (* 1 a)))) ((= 37 orientation-id) (if reverse? (list (* -1 c) (* -1 a) (* 1 b)) (list (* -1 b) (* 1 c) (* -1 a)))) ((= 38 orientation-id) (if reverse? (list (* 1 c) (* -1 a) (* -1 b)) (list (* -1 b) (* -1 c) (* 1 a)))) ((= 39 orientation-id) (if reverse? (list (* -1 c) (* -1 a) (* -1 b)) (list (* -1 b) (* -1 c) (* -1 a)))) ;;cba ((= 40 orientation-id) (if reverse? (list (* 1 c) (* 1 b) (* 1 a)) (list (* 1 c) (* 1 b) (* 1 a)))) ((= 41 orientation-id) (if reverse? (list (* -1 c) (* 1 b) (* 1 a)) (list (* 1 c) (* 1 b) (* -1 a)))) ((= 42 orientation-id) (if reverse? (list (* 1 c) (* -1 b) (* 1 a)) (list (* 1 c) (* -1 b) (* 1 a)))) ((= 43 orientation-id) (if reverse? (list (* -1 c) (* -1 b) (* 1 a)) (list (* 1 c) (* -1 b) (* -1 a)))) ((= 44 orientation-id) (if reverse? (list (* 1 c) (* 1 b) (* -1 a)) (list (* -1 c) (* 1 b) (* 1 a)))) ((= 45 orientation-id) (if reverse? (list (* -1 c) (* 1 b) (* -1 a)) (list (* -1 c) (* 1 b) (* -1 a)))) ((= 46 orientation-id) (if reverse? (list (* 1 c) (* -1 b) (* -1 a)) (list (* -1 c) (* -1 b) (* 1 a)))) ((= 47 orientation-id) (if reverse? (list (* -1 c) (* -1 b) (* -1 a)) (list (* -1 c) (* -1 b) (* -1 a)))) (T (error "Invalid ORIENTATION-ID."))))) (loop for i from 0 below 48 always (equal '(1 -2 3) (rotate-vector (rotate-vector '(1 -2 3) i) i T))) (defun vector- (a b) "The difference between vector A and B." (list (- (first a) (first b)) (- (second a) (second b)) (- (third a) (third b)))) (defun bridge-scanners (beacon-from-left beacon-from-right) "Adds two vectors in order to determine a scanner position. BEACON-FROM-LEFT and BEACON-FROM-RIGHT both are a list that represents a vector towards a beacon, as seen from a scanner." ;;Trick is that the orientations will get rotated later on. (list (+ (first beacon-from-left) (first beacon-from-right)) (+ (second beacon-from-left) (second beacon-from-right)) (+ (third beacon-from-left) (third beacon-from-right)))) (defun joining-scanner-position-and-rotation (raw-beacon-coordinates &optional candidates) "Determine the vector to and the orientation of the right/joining scanner with the help of the vectors to overlapping beacons. Assumes the default orientation and position for the left scanner (0 and 0/0/0)." ;;Base idea: try to get to the same location (bridging from beacon to scanner) by searching in all possible directions (orientations). More and more beacons will hit the scanner position, while most other vectors won't be reached by multiple beacons. Stop as soon as there is only one position left (typically after the second/third beacon). (if (and raw-beacon-coordinates ;;#'cdr: not reduced to one possibility yet. (or (not candidates) (cdr candidates))) (joining-scanner-position-and-rotation (rest raw-beacon-coordinates) (let* ((left-value (first (car raw-beacon-coordinates))) (current-candidates (loop for i from 0 below 48 collect (list (bridge-scanners left-value (rotate-vector (second (car raw-beacon-coordinates)) i)) i)))) (if candidates ;;More and more beacon bridges reduce the problem. (intersection candidates current-candidates :test #'equal) ;;Initialization. current-candidates))) (car candidates))) (joining-scanner-position-and-rotation (raw-beacon-coordinates (gethash 1 (input 19 T)) (gethash 3 (input 19 T)))) #| From #'bidirectional-connections (19-detour.lisp). Plan: ((0 1) (1 3) (1 4) (4 2)) 0-1-3 | 4-2 0→0: ((0 0 0) 0) 0 is at 0 0 0 rot 0 0→1: ((68 -1246 -43) 2) 1 is at 68 -1246 -43 local rot 2 global rot 2 1→4: ((88 113 -1104) 36 local 28 global) 4 is at -20 -1133 1061 local rot 36 global rot 28 4→2: ((168 -1125 72) 22) 2 is at 1105 -1205 1229 local rot 22 1→3: ((160 -1134 -23) 7) 3 is at -92 -2380 -20 local rot 7 |# (defun scanner-global-position (left-scanner-position left-scanner-rotation vector-to-right-scanner) "Determine the global position of the right scanner. VECTOR-TO-RIGHT-SCANNER is calculated by #'joining-scanner-position-and-rotation." (if (equal '(0 0 0) left-scanner-position) ;;Special case which is especially important for the first scanner. vector-to-right-scanner (rotate-vector (vector- ;;Rotate the left scanner into its position when #'joining-scanner-position-and-rotation determined the vector... (rotate-vector left-scanner-position left-scanner-rotation) vector-to-right-scanner) ;;... and rotate back to authoritative scanner 0. left-scanner-rotation T))) (joining-scanner-position-and-rotation (raw-beacon-coordinates (gethash 1 (input 19 T)) (gethash 3 (input 19 T)))) ;;0→1 => (68 -1246 -43) (scanner-global-position '(0 0 0) 0 '(68 -1246 -43)) ;;1→4 => (-20 -1133 1061) (scanner-global-position '(68 -1246 -43) 2 '(88 113 -1104)) ;;4→2 => (1105 -1205 1229) ;;36 is relative to local coordinate system 2, 28 is global (see #'scanner-global-rotation). (scanner-global-position '(-20 -1133 1061) 28 '(168 -1125 72)) ;;1→3 => (-92 -2380 -20) (scanner-global-position '(68 -1246 -43) 2 '(160 -1134 -23)) ;;The key to this puzzle. (defun scanner-global-rotation (scanner-globally first-beacon-globally first-beacon-locally) "Determines the global rotation of the scanner." ;;48: number of orientations. (loop for i from 0 below 48 when (equal (vector- scanner-globally first-beacon-globally) (rotate-vector first-beacon-locally i T)) return i)) (scanner-global-rotation '(-20 -1133 1061) '(-447 -329 318) '(-743 427 -804)) (scanner-global-rotation '(68 -1245 -43) '(404 -588 -901) '(-404 588 901)) #| The circular dependency between #'scanner-global-position and #'scanner-global-rotation is resolved by scanner 0's known position and rotation. |# (defun beacons-global-position (left-scanner-position-global left-scanner-rotation-global left-beacons-local) "With the help of known left scanner position and rotation, rotate the shared beacons between two scanners into global space." (if (equal '(0 0 0) left-scanner-position-global) ;;Special case for the first scanner. left-beacons-local (loop for beacon in left-beacons-local collect (vector- left-scanner-position-global (rotate-vector beacon left-scanner-rotation-global T))))) (beacons-global-position '(0 0 0) 0 (gethash 0 (input 19 T))) (beacons-global-position '(68 -1246 -43) 2 (gethash 1 (input 19 T))) (defun join-scanners (input left-id left-pos left-rot right-id) "Known: (list LEFT-ID LEFT-POS LEFT-ROT). Wanted: (values right-pos right-rot). Returns NIL if LEFT-ID and RIGHT-ID do not overlap." (let ((raw-beacons (raw-beacon-coordinates (gethash left-id input) (gethash right-id input)))) (when (and raw-beacons left-pos left-rot) ;;raw-beacons (let* ((vector-to-right (joining-scanner-position-and-rotation raw-beacons)) (shared-beacons-global (beacons-global-position left-pos left-rot (mapcar #'first raw-beacons))) (right-scanner-position-global (scanner-global-position left-pos left-rot (first vector-to-right))) (right-scanner-rotation-global (scanner-global-rotation right-scanner-position-global (first shared-beacons-global) (first (mapcar #'second raw-beacons))))) (values right-scanner-position-global right-scanner-rotation-global))))) ;;0→1: Scanner 1 is at (68 -1246 -43) with global-rot 2. (join-scanners (input 19 T) 0 '(0 0 0) 0 1) ;;1→4: Scanner 4 is at (-20 -1133 1061) with global-rot 28. (join-scanners (input 19 T) 1 '(68 -1246 -43) 2 4) ;;4→2: Scanner 2 is at (1105 -1205 1229) with global-rot 11. (join-scanners (input 19 T) 4 '(-20 -1133 1061) 28 2) ;;1→3: Scanner 3 is at (-92 -2380 -20) with global-rot 2. (join-scanners (input 19 T) 1 '(68 -1246 -43) 2 3) ;;0 and 3 do not overlap. (join-scanners (input 19 T) 0 '(0 0 0) 0 3) (defun grow-scanner-region (input &key (last-scanner 0)) "Starting with the first scanner region in *UNVISITED-IDS*, recursively attach other overlapping scanner regions. Expects context which is set up by #'19-solution. *BEACON-KNOWLEDGE* accumulates known beacons relative to the first scanner in *UNVISITED-IDS*. Maps (a b c) → T. *SCANNER-KNOWLEDGE* accumulates known scanner positions relative to the first scanner in *UNVISITED-IDS*. Maps id → (list position rotation)." (declare (special *beacon-knowledge* *scanner-knowledge* *unvisited-ids*)) (when *unvisited-ids* (cond ((= 0 (hash-table-count *scanner-knowledge*)) ;;Start. (loop for beacon in (gethash 0 input) do (setf (gethash beacon *beacon-knowledge*) T)) (setf (gethash (car *unvisited-ids*) *scanner-knowledge*) '((0 0 0) 0)) (grow-scanner-region input :last-scanner 0)) (T ;;Identify an overlapping scanner region. (loop for unvisited-id in *unvisited-ids* do (multiple-value-bind (right-pos right-rot) (join-scanners input last-scanner (first (gethash last-scanner *scanner-knowledge*)) (second (gethash last-scanner *scanner-knowledge*)) unvisited-id) (when (and right-pos right-rot) (setf (gethash unvisited-id *scanner-knowledge*) (list right-pos right-rot)) (loop for beacon in (beacons-global-position right-pos right-rot (gethash unvisited-id input)) do (setf (gethash beacon *beacon-knowledge*) T)) (setf *unvisited-ids* (remove unvisited-id *unvisited-ids*)) (grow-scanner-region input :last-scanner unvisited-id)))))))) (defun 19-solution (input &optional part2?) "Set up a context for #'grow-scanner-region and collect informations about scanners and beacons." (let ((*beacon-knowledge* (make-hash-table :test 'equal)) (*scanner-knowledge* (make-hash-table)) (*unvisited-ids* (loop for k being the hash-keys of input collect k))) (declare (special *beacon-knowledge* *scanner-knowledge* *unvisited-ids*)) (grow-scanner-region input) (if part2? (loop for scanner-outer being the hash-values of *scanner-knowledge* maximize (loop for scanner-inner being the hash-values of *scanner-knowledge* maximize (let ((left (first scanner-outer)) (right (first scanner-inner))) (+ (abs (- (first left) (first right))) (abs (- (second left) (second right))) (abs (- (third left) (third right))))))) (hash-table-count *beacon-knowledge*)))) (19-solution (input 19 T)) (19-solution (input 19 T) T) (defmethod solution ((day (eql 19)) (variant (eql 'part1)) source) "The number of beacons detected by all scanners." (19-solution (input day source))) (is 19 'part1 79) (defmethod solution ((day (eql 19)) (variant (eql 'part2)) source) "The largest City Block distance between all scanners." (19-solution (input day source) T)) (is 19 'part2 3621) #| Summary ======= This puzzle had three "plot twists": 1. Identify a similarity in a freely rotatable space through coordinate-oblivious distances (#'distances-between-beacons). 2. The position in a cross join result determines the id of both columns (#'raw-beacon-coordinates). 3. The vector to and the rotation of the right scanner need to be found separately (#'scanner-global-position and #'scanner-global-rotation). |#
23,151
Common Lisp
.lisp
382
52.526178
343
0.585984
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
9be464240fd7a69b157f24f582e43619f82fd3bea90dbd9df61eac3ec91f7181
41,825
[ -1 ]
41,826
24.lisp
b-steger_adventofcode2021/src/24.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) #| A migration of an old software / program / code base without any call to my DSL library lisp-at-work. |# ;;;; Parser ;;; This parser of aoc21-alu intentionally makes convenience shortcuts. (defrule alu-symbol (or "w" "x" "y" "z") (:lambda (input) (cond ((string= "w" input) 'w) ((string= "x" input) 'x) ((string= "y" input) 'y) ((string= "z" input) 'z)))) (parse 'alu-symbol "w") (defrule alu-atom (or integer-z alu-symbol)) (parse 'alu-atom "-123") (parse 'alu-atom "w") (defrule alu-inp (and "inp " alu-symbol) (:lambda (input) (list :this-is 'alu-inp :place (elt input 1)))) (parse 'alu-inp "inp w") (defrule alu-add (and "add " alu-symbol " " alu-atom) (:lambda (input) (let ((place (elt input 1)) (value (elt input 3))) (list :this-is 'alu-add :place place :value value)))) (parse 'alu-add "add w -1") (defrule alu-mul (and "mul " alu-symbol " " alu-atom) (:lambda (input) (let ((place (elt input 1)) (value (elt input 3))) (list :this-is 'alu-mul :place place :value value)))) (parse 'alu-mul "mul x -1") (defrule alu-div (and "div " alu-symbol " " alu-atom) (:lambda (input) (let ((place (elt input 1)) (value (elt input 3))) (list :this-is 'alu-div :place place :value value)))) (parse 'alu-div "div x -1") (defrule alu-mod (and "mod " alu-symbol " " alu-atom) (:lambda (input) (let ((place (elt input 1)) (value (elt input 3))) (list :this-is 'alu-mod :place place :value value)))) (parse 'alu-mod "mod x 3") (defrule alu-eql (and "eql " alu-symbol " " alu-atom) (:lambda (input) (let ((place (elt input 1)) (value (elt input 3))) (list :this-is 'alu-eql :place place :value value)))) (parse 'alu-eql "eql x 3") (defrule 24-file (+ (and (or alu-inp alu-add alu-mul alu-div alu-mod alu-eql) (? new))) (:lambda (input) (mapcar #'first input))) (parse '24-file "inp x mul x -1 ") (defmethod input ((day (eql 24)) source) "AST (or merely an abstract syntax list) with aoc21-alu primitives." (parse '24-file (read-file 24 source))) ;;=> ((:this-is alu-inp :place x) (:this-is alu-mul :place x :value -1)) (input 24 'toy-example) (input 24 'middle-example) (input 24 T) (input 24 'full) ;;;; Solution #| Determine the problem size. |# (loop for i from 0 below 36 collect (format nil "~9,14,'0R" i)) ;;0..22876792454960 → OK, ad fontes... (identity #9R88888888888888) (length (format nil "~9,14R" 22876792454960)) (length (format nil "~9,14R" (1+ 22876792454960))) #| aoc21-alu's operations are supported by Common Lisp, too. Lispify aoc21-alu. |# (defgeneric lispify-aoc21-alu (op place &optional value) (:documentation "Represent the aoc21-alu-operations as Common Lisp forms. Needs additional setup context (registers 'w 'x 'y 'z, which are initialized to 0, and 'arguments).") (:method ((op (eql 'alu-inp)) place &optional value) (declare (ignore value)) ;;`(setf ,place (pop arguments)) `(progn (setf ,place (aref arguments position)) (incf position))) (:method ((op (eql 'alu-add)) place &optional value) `(incf ,place ,value)) (:method ((op (eql 'alu-mul)) place &optional value) `(setf ,place (* ,place ,value))) (:method ((op (eql 'alu-div)) place &optional value) `(setf ,place (truncate ,place ,value))) (:method ((op (eql 'alu-mod)) place &optional value) `(setf ,place (rem ,place ,value))) (:method ((op (eql 'alu-eql)) place &optional value) `(setf ,place (if (= ,place ,value) 1 0)))) (defun lispified-program (input-ast &key compile-form?) "Lispify the aoc21-alu program. Return a callable compiled function if COMPILE-FORM?, the plain form otherwise." (let ((program `(lambda (arguments) (let ((w 0) (x 0) (y 0) (z 0) (position 0)) ,@(loop for operation in input-ast collect (lispify-aoc21-alu (getf operation :this-is) (getf operation :place) ;;NIL for alu-inp, which is ok. (getf operation :value))) (list w x y z))))) (if compile-form? (compile nil program) program))) (lispified-program (input 24 'toy-example)) ;;Target: (0 -1 0 0). (funcall (lispified-program (input 24 'toy-example) :compile-form? T) (make-array (list 1) :element-type 'fixnum :initial-contents '(1))) ;;Target: (0 6 0 1). (funcall (lispified-program (input 24 'middle-example) :compile-form? T) (make-array (list 2) :element-type 'fixnum :initial-contents '(2 6))) ;;Target: (0 7 0 0). (funcall (lispified-program (input 24 'middle-example) :compile-form? T) (make-array (list 2) :element-type 'fixnum :initial-contents '(2 7))) ;;Target: ((0 0 0 1) (0 0 1 0) (0 0 1 1) (0 1 0 0) (0 1 0 1) (0 1 1 0) (0 1 1 1) (1 0 0 0) (1 0 0 1) (1 0 1 0) (1 0 1 1) (1 1 0 0) (1 1 0 1) (1 1 1 0) (1 1 1 1)). (let ((fun (lispified-program (input 24 'example) :compile-form? T))) (loop for i from 0 below 16 collect (funcall fun (make-array (list 1) :element-type 'fixnum :initial-contents (list i))))) #|(with-open-file (f "/dev/shm/aoc" :direction :output :if-does-not-exist :create :if-exists :supersede) (format f "~A" (lispified-program (input 24 'full))))|# #| Analysis of the program code shows a repeating pattern. The puzzle input does something similar digit after digit. This digit-weaver is an inlined function. Verify those assumptions. |# (defun de-expand-list-pattern (input) "Assuming the pattern ,@(loop for i from 0 below 14 collect `(weave-digit i)), return list of `(weave-digit i)." (cond ;;18: manually determined/inferred from INPUT. ((<= 18 (length input)) (cons (subseq input 0 18) (de-expand-list-pattern (subseq input 18)))) (input (error "Expanded program code seemingly does not contain a repeated list of 18 operations.")))) (de-expand-list-pattern (input 24 'full)) (handler-case (de-expand-list-pattern (input 24 'toy-example)) (error () "Failed as expected.")) (defun identify-inlined-funcall (&key expansions ast-so-far arguments (argument-placeholders '(a b c d e f g h i j k l m))) "Grow the list of shared operations (AST-SO-FAR) until items of EXPANSIONS differ laterally. Flag the operation, add a list of all possible inputs to ARGUMENTS, and continue until the whole operation list is covered. Returns a function/macro body stub as the first return value and the list of arguments for each expansion as the second return value." (if (>= (length ast-so-far) (length (first expansions))) (values (reverse ast-so-far) (when arguments ;;Transpose the ARGUMENTS matrix in order to get the parameters of each expansion. (apply #'mapcar #'list (reverse arguments)))) (let ((operations-in-question (loop for expansion in expansions collect (elt expansion (if ast-so-far (length ast-so-far) 0))))) (if (= 1 (length (remove-duplicates operations-in-question :test #'equal))) ;;No variation across expansions. (identify-inlined-funcall :expansions expansions :ast-so-far (cons (first operations-in-question) ast-so-far) :arguments arguments :argument-placeholders argument-placeholders) ;;Variation detected. Flag it and add the variations to ARGUMENTS. ;;Not hunting down the difference within the operation. ;; Input is small enough for the educated guess that it is solely the value which differs. ;; A recursive tree walk would cover this difference on a "real" AST anyway. (identify-inlined-funcall :expansions expansions :ast-so-far (cons (let ((ori-op (first operations-in-question))) (list :this-is (getf ori-op :this-is) :place (getf ori-op :place) :value (or ;;Contract: no other variable name than w x y z. (car argument-placeholders) (gensym "PROBABLY-NOT-SHARING-SIMILARITIES")))) ast-so-far) :arguments (cons (loop for op in operations-in-question collect (getf op :value)) arguments) :argument-placeholders (rest argument-placeholders)))))) ;;Arguments full: ((1 11 7) (1 14 8) (1 10 16) (1 14 8) (26 -8 3) (1 14 12) (26 -11 1) (1 10 8) (26 -6 8) (26 -9 14) (1 12 4) (26 -5 14) (26 -4 15) (26 -9 6)) (multiple-value-list (identify-inlined-funcall :expansions (de-expand-list-pattern (input 24 'full)))) #| Check whether the patterns were correctly abstracted: compare the expansion with the expanded input. |# ;;T (equal (input 24 'full) (multiple-value-bind (ast arguments) (identify-inlined-funcall :expansions (de-expand-list-pattern (input 24 'full))) (loop for (a b c) in arguments append ;;Unquote a b c manually. (loop for op in ast collect (substitute a 'a (substitute b 'b (substitute c 'c op))))))) #| Now that the consistent use of the digit weaver is verified, it is time to analyze it. I dissect the digit weaver by reimplementing it. |# #|Examining the isolation degree of the inlined function: w is used as an argument variable. No writes to w happen after the input operation. x is set to 0 at the beginning of the function. y is not affected by the assignments that occur before y is set to 0. z is not resetted. → Lexical binding for w x y, indefinite scope for z. → z and w are arguments, and x and y are established by the special operator "let". It would make sense to write automated verifiers for those new assumptions if the input were larger. Not this time.|# (format nil "~%~S~%" (mapcar (lambda (x) (lispify-aoc21-alu (getf x :this-is) (getf x :place) (getf x :value))) (identify-inlined-funcall :expansions (de-expand-list-pattern (input 24 'full))))) ;;↓↓↓↓ Copying the printed form to a new function. ↓↓↓↓ (defun weave-digit-imperative (a b c w &optional (z 0)) "A function that is to be reverse engineered and whose sole purpose of existence is puzzling fun." (let ((x 0) (y 0)) ;;See the lambda list of this defun. ;;(setf w w) ;;(let ((x 0))) (setf x (* x 0)) ;;(let ((x z))) (incf x z) ;;(let ((x (rem z 26)))) (setf x (rem x 26)) #+only-because-of-C-c-M-q-identation (let ((x (rem z 26)) (z (truncate z a)))) (setf z (truncate z a)) #+only-because-of-C-c-M-q-identation (let ((x (+ (rem z 26) b)) (z (truncate z a)))) (incf x b) #+only-because-of-C-c-M-q-identation (let ((x (if (= (+ (rem z 26) b) w) 1 0)) (z (truncate z a)))) (setf x (if (= x w) 1 0)) #+only-because-of-C-c-M-q-identation (let ((x (if (= (+ (rem z 26) b) w) 0 1)) (z (truncate z a)))) (setf x (if (= x 0) 1 0)) ;;Next 5 operations: (let ((z (* z (1+ (* 25 x)))))) #+only-because-of-C-c-M-q-identation (let ((x (if (= (+ (rem z 26) b) w) 0 1)) (z (* (truncate z a) (1+ (* 25 x)))))) (setf y (* y 0)) (incf y 25) (setf y (* y x)) (incf y 1) (setf z (* z y)) ;;Next 5 operations: (let ((z (+ z (* (+ w c) x))))) #+only-because-of-C-c-M-q-identation (let ((x (if (= (+ (rem z 26) b) w) 0 1))) (let ((z (+ (* (truncate z a) (1+ (* 25 x))) (* (+ w c) x)))))) (setf y (* y 0)) (incf y w) (incf y c) (setf y (* y x)) (incf z y) ;;(list w x y z) z)) (defun weave-digit (a b c w &optional (z 0)) "#'weave-digit-imperative in functional style." #+only-because-of-C-c-M-q-identation (let ((x (if (= (+ (rem z 26) b) w) 0 1))) (+ (* (truncate z a) (1+ (* 25 x))) (* (+ w c) x))) (if (= (+ (rem z 26) b) w) (truncate z a) (+ (* (truncate z a) 26) w c))) (defun weave-digits (&key abc remaining-digits (z 0) (weaving-function #'weave-digit)) "Execute the program of puzzle 24. The keyword arguments are useful for a stepwise analysis since any point in execution can be adopted at will." (if remaining-digits (weave-digits :abc (rest abc) :remaining-digits (rest remaining-digits) :z (funcall weaving-function (first (first abc)) (second (first abc)) (third (first abc)) (car remaining-digits) z) :weaving-function weaving-function) z)) ;;Gain some level of confidence in the logical equivalence between the original, #'weave-digit-imperative and #'weave-digit. ;;T (let* ((input (input 24 'full)) (compiled-function (lispified-program input :compile-form? T))) (multiple-value-bind (ast arguments) (identify-inlined-funcall :expansions (de-expand-list-pattern input)) (declare (ignore ast)) ;;100: this form is executed during #'ql:quickload. (loop for i from 0 below 100 always (let ((numbers (loop for i from 0 below 14 collect (1+ (random 9))))) (= (fourth (funcall compiled-function (make-array (list 14) :element-type 'fixnum :initial-contents numbers))) (weave-digits :abc arguments :remaining-digits numbers :weaving-function #'weave-digit-imperative) (weave-digits :abc arguments :remaining-digits numbers :weaving-function #'weave-digit)))))) (defmethod real-input ((day (eql 24)) source) "The varying parts of the inlined digit-weaving function (#'weave-digit) in the puzzle input. Returns a list of a/b/c argument values used per invocation of the #'weave-digit function." (multiple-value-bind (ast arguments) (identify-inlined-funcall :expansions (de-expand-list-pattern (input 24 source))) (declare (ignore ast)) arguments)) (real-input 24 'full) ;;Easier to read. (apply #'mapcar #'list (real-input 24 'full)) #| Solve for max/min w (z=0 actually) with the help of a b c. Try to reduce the number/scope of variables and try to find patterns/invariants. |# ;;Can't solve for w in isolation: z has indefinite scope (a b c w → z). ;;NIL (loop for abc in (real-input 24 'full) always (remove-if-not #'zerop (loop for i from 1 below 10 collect (weave-digit (first abc) (second abc) (third abc) i)))) ;;But `a is superfluous (b → a, b c w → z): ;;T (loop for abc in (real-input 24 'full) always (= (first abc) (if (plusp (second abc)) 1 26))) ;;Assumption: b begins with an ascending step and finally returns to 0. ;;T (let ((b-list (mapcar (lambda (x) (signum (second x))) (real-input 24 'full)))) (and (= 1 (car b-list)) (= -1 (car (last b-list))) (= 0 (apply #'+ b-list)))) #| Continuing this line of thinking, b must always be larger than 1..9 if it's positive (well, it is). Why? Because b controls the execution path this way (remainder of z is 0..25 in IF's TEST). It must deterministically control it since the contract says that 0 has to be reached at the end and since #'weave-digit is used repeatedly in the same manner. (if ;;b steers away from z=0 or towards z=0. (= (+ (rem z 26) b) w) ;;b steers towards z=0 (it is negative here). The real form is (truncate z 26). (truncate z (if (plusp b) 1 26)) ;;b steers away from z=0. Since b is positive, the real form is (+ (* z 26) w c). (+ (* (truncate z (if (plusp b) 1 26)) 26) w c)) Since b must be able to steer stepwise towards or away from z=0, (+ w c) in IF's ELSE must be lower than 26 (and they are). Why? Because w and c should not interfere with the THEN part of the IF. ... Aha! ... The modulo operation is used as a way to transport information - it packs a stack in a single integer. The forms with b in the THEN and ELSE part of the special operator "if" cancel each other out. The problem is now reduced to the two crucial forms (= (+ (rem z 26) b) w) and (+ w c). Additional invariants can be found now. c is only relevant for w if b is positive. The value of b is only relevant for w if b is negative. Each step away from z=0 must be matched with a step towards z=0. Now that it is known that a stack is used, the indefinite extent of z is finally reduced to dynamic extent (this is the "scope in time" in Common Lisp's parlance). This means that z will be the same before and after a push and pop of the same level. For the outermost level, this means z=0 at the beginning and z=0 at the end (or any number wanted). The next thing that needs to be tackled is, consequently, the retrieval of push-pop-teams. Let's call the two positions that belong to the same nesting level of stack operations "team members". |# (defun team-member-distance (remaining-bs &key height (counter 0)) "The number of steps towards the other team member. REMAINING-BS should be normalized to 1 or -1 values, respectively." (if (and height (= 0 height)) (1- counter) (team-member-distance (rest remaining-bs) :height (+ (or height 0) (car remaining-bs)) :counter (1+ counter)))) (defun team-member-lut (real-input) "A list which tells at each index at what other index the matching opposite-steering team member is." (let ((b-list (mapcar (lambda (x) (signum (second x))) real-input))) (loop with i = 0 for b on b-list collect (if (plusp (car b)) (+ i (team-member-distance b)) ;;The reverse needs the element which is exactly one out of reach of ":for b-reverse :on (reverse b-list)". (- i (team-member-distance (reverse (subseq b-list 0 (1+ i)))))) do (incf i)))) (team-member-lut (real-input 24 'full)) #| Find out how the arguments determine the w of the left team member and the w of the right team member. |# ;;1. Identify the pairs. (team-member-lut (real-input 24 'full)) ;;2. Go to a pair by filling in nines. Memorize the z value. (weave-digits :abc (real-input 24 'full) :remaining-digits (list 9 9)) ;;3. Identify a correct answer. The correct answer is one which results in the same z value as above. (loop for m from 1 below 10 append (loop for n from 1 below 10 when (= (weave-digits :abc (real-input 24 'full) :remaining-digits (list 9 9)) (weave-digits :abc (real-input 24 'full) :remaining-digits (list 9 9 m n))) collect (list m n))) ;;4. Fetch the arguments of the left team member and of the right team member. (subseq (real-input 24 'full) 2 4) ;;5. Repeat for other pairs until at least three combinations are gathered. (By changing above forms.) ;;6. Manually search for the formula whilst keeping #'weave-digit in mind. (defun biggest-for-team (left-c right-b) "What interplay of LEFT-C, RIGHT-B, left-w and right-w results in the same z after a push-pop-operation pair. Returns left-w and right-w. Maximize the first number. The rules of interplay are determined by #'weave-digit and #'real-input." (let* ((left-w (min 9 (- (+ 9 (* -1 right-b)) left-c))) (right-w (+ left-w left-c right-b))) (list left-w right-w))) (defun smallest-for-team (left-c right-b) "Variant of #'biggest-for-team which reduces left-w. (right-w is irrelevant since left-w → right-w.)" (let* ((left-w (max 1 (- (+ 1 (* -1 right-b)) left-c))) (right-w (+ left-w left-c right-b))) (list left-w right-w))) (defun fill-in-pair (real-input positioned-teams &key part2?) "Search for teams that are not positioned yet, calculate their numbers and recursively continue until all teams are positioned. Destructively modifies POSITIONED-TEAMS." (let ((next-free-index (position nil positioned-teams))) (if next-free-index (let* ((right-team-member-index (elt (team-member-lut real-input) next-free-index)) (left-abc (elt real-input next-free-index)) (right-abc (elt real-input right-team-member-index)) (digits (funcall (if part2? #'smallest-for-team #'biggest-for-team) (third left-abc) (second right-abc)))) (setf (elt positioned-teams next-free-index) (first digits) (elt positioned-teams right-team-member-index) (second digits)) (fill-in-pair real-input positioned-teams :part2? part2?)) positioned-teams))) (fill-in-pair (real-input 24 'full) (loop repeat 14 collect nil)) (fill-in-pair (real-input 24 'full) (loop repeat 14 collect nil) :part2? T) (defun solution-24 (day source &optional part2?) "Prepare the call to #'fill-in-pair for #'solution." (parse-integer (format nil "~{~A~}" (fill-in-pair (real-input day source) (loop repeat 14 collect nil) :part2? part2?)))) (defmethod solution ((day (eql 24)) (variant (eql 'part1)) source) "The largest MONAD number accepted by the submarine's MONAD number checker." (solution-24 day source)) ;;No example for the part1 task. (defmethod solution ((day (eql 24)) (variant (eql 'part2)) source) "The smallest MONAD number accepted by the submarine's MONAD number checker." (solution-24 day source T)) ;;No example for the part2 task. ;;;; Appendix #| If the assumptions about the puzzle input do not hold true, brute force is needed. Apart from the 14 inp instructions, the spec has no contract regarding input program structure after all. |# (defun prepare-number (number) "Represent NUMBER in an array for a #'lispified-program. Destructively modifies NUMBER." (make-array (list 14) :element-type 'fixnum :initial-contents (reverse (loop while (plusp number) collect (1+ (rem number 9)) do (setf number (floor number 9)))))) (prepare-number #9R11111147238447) (let ((compiled-monad-checker (lispified-program (input 24 'full) :compile-form? T))) ;;...08: disabled. (loop for i downfrom #9R88888888888888 downto #9R88888888888808 when (= 0 (fourth (funcall compiled-monad-checker (prepare-number i)))) return i)) #| The completely migrated function. |# (defun 24-push (number stack) "Pushes NUMBER onto STACK (non-destructively). NUMBER is limited to the interval [0,26)." (when (<= 26 number) (error "NUMBER is limited to the interval [0,26).")) (+ (* 26 stack) number)) (24-push 25 1234) (defun 24-pop (stack) "Retrieves the last number which was pushed onto STACK, and returns, as the second return value, the new stack. NIL if the stack is empty." (when (< 0 stack) (values (rem stack 26) (floor stack 26)))) (24-pop 32109) (24-pop 0) #| Just for fun. |# (defun some-valid-monad-numbers (real-input) "By the virtue of the gathered insights, produce valid serial numbers for MONAD submarines. Exploits the fact that the team members can be randomized to a certain degree, since they result in the same z value. For example, each team can randomly select the part1 or the part2 variant." ;;I decided against the implementation of the required algorithm (which is straightforward in this situation). (declare (ignore real-input))) ;;Own recursive interpreter. ;;916660/5030 processor cycles → 182.2 times less efficient than #'lispified-program. ;;Also very unmaintainable. (defun manually-interpret-aoc24-alu (&key remaining-operations remaining-arguments (w 0) (x 0) (y 0) (z 0)) (flet ((my-eval (operation w x y z) (if (symbolp (getf operation :value)) (case (getf operation :value) (w w) (x x) (y y) (z z)) (getf operation :value)))) ;;THINK: program pointer? (if remaining-operations (let ((next (car remaining-operations))) (cond ((eql 'alu-inp (getf next :this-is)) (manually-interpret-aoc24-alu :remaining-operations (rest remaining-operations) :remaining-arguments (rest remaining-arguments) :w (if (eql 'w (getf next :place)) (car remaining-arguments) w) :x (if (eql 'x (getf next :place)) (car remaining-arguments) x) :y (if (eql 'y (getf next :place)) (car remaining-arguments) y) :z (if (eql 'z (getf next :place)) (car remaining-arguments) z))) ((eql 'alu-add (getf next :this-is)) (manually-interpret-aoc24-alu :remaining-operations (rest remaining-operations) :remaining-arguments remaining-arguments :w (if (eql 'w (getf next :place)) (+ w (my-eval next w x y z)) w) :x (if (eql 'x (getf next :place)) (+ x (my-eval next w x y z)) x) :y (if (eql 'y (getf next :place)) (+ y (my-eval next w x y z)) y) :z (if (eql 'z (getf next :place)) (+ z (my-eval next w x y z)) z))) ((eql 'alu-mul (getf next :this-is)) (manually-interpret-aoc24-alu :remaining-operations (rest remaining-operations) :remaining-arguments remaining-arguments :w (if (eql 'w (getf next :place)) (* w (my-eval next w x y z)) w) :x (if (eql 'x (getf next :place)) (* x (my-eval next w x y z)) x) :y (if (eql 'y (getf next :place)) (* y (my-eval next w x y z)) y) :z (if (eql 'z (getf next :place)) (* z (my-eval next w x y z)) z))) ((eql 'alu-div (getf next :this-is)) (manually-interpret-aoc24-alu :remaining-operations (rest remaining-operations) :remaining-arguments remaining-arguments :w (if (eql 'w (getf next :place)) (truncate w (my-eval next w x y z)) w) :x (if (eql 'x (getf next :place)) (truncate x (my-eval next w x y z)) x) :y (if (eql 'y (getf next :place)) (truncate y (my-eval next w x y z)) y) :z (if (eql 'z (getf next :place)) (truncate z (my-eval next w x y z)) z))) ((eql 'alu-mod (getf next :this-is)) (manually-interpret-aoc24-alu :remaining-operations (rest remaining-operations) :remaining-arguments remaining-arguments :w (if (eql 'w (getf next :place)) (rem w (my-eval next w x y z)) w) :x (if (eql 'x (getf next :place)) (rem x (my-eval next w x y z)) x) :y (if (eql 'y (getf next :place)) (rem y (my-eval next w x y z)) y) :z (if (eql 'z (getf next :place)) (rem z (my-eval next w x y z)) z))) ((eql 'alu-eql (getf next :this-is)) (manually-interpret-aoc24-alu :remaining-operations (rest remaining-operations) :remaining-arguments remaining-arguments :w (if (eql 'w (getf next :place)) (if (= w (my-eval next w x y z)) 1 0) w) :x (if (eql 'x (getf next :place)) (if (= x (my-eval next w x y z)) 1 0) x) :y (if (eql 'y (getf next :place)) (if (= y (my-eval next w x y z)) 1 0) y) :z (if (eql 'z (getf next :place)) (if (= z (my-eval next w x y z)) 1 0) z))) (T (error "What is ~A?" (getf next :this-is))))) (list w x y z)))) (manually-interpret-aoc24-alu :remaining-operations (input 24 'toy-example) :remaining-arguments '(1)) (manually-interpret-aoc24-alu :remaining-operations (input 24 'middle-example) :remaining-arguments '(2 6)) (manually-interpret-aoc24-alu :remaining-operations (input 24 'middle-example) :remaining-arguments '(2 7)) (loop for i from 0 below 16 collect (manually-interpret-aoc24-alu :remaining-operations (input 24 'example) :remaining-arguments (list i)))
29,649
Common Lisp
.lisp
581
42.73494
494
0.611687
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
d1c55272a77d1c61763a328f4fcfb2fc058dd478ac9018a0ea3bbe79a9e472e9
41,826
[ -1 ]
41,827
22.lisp
b-steger_adventofcode2021/src/22.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule reboot-step (and (or "on" "off") " " "x=" integer-z ".." integer-z "," "y=" integer-z ".." integer-z "," "z=" integer-z ".." integer-z) (:lambda (input) (let ((set (elt input 0)) (xmin (elt input 3)) (xmax (elt input 5)) (ymin (elt input 8)) (ymax (elt input 10)) (zmin (elt input 13)) (zmax (elt input 15))) (list :set-value (if (string= "on" set) T nil) :xmin xmin :xmax xmax :ymin ymin :ymax ymax :zmin zmin :zmax zmax)))) (defrule 22-file (+ (and reboot-step (? new))) (:lambda (input) (mapcar #'first input))) (defmethod input ((day (eql 22)) source) "Reactor reboot steps, each listing the SET-VALUE and the max/min object axis values which denote the affected reactor core area." (parse '22-file (read-file 22 source))) (input 22 'toy-example) (input 22 'middle-example) (input 22 'example) (input 22 'full) (defun 22-part1-filter (input) "Filter for reboot steps which are fully within the interval [-50..50] on each axis. Also see #'22-input." (remove-if-not (lambda (x) (and (<= -50 (getf x :xmin) (getf x :xmax) 50) (<= -50 (getf x :ymin) (getf x :ymax) 50) (<= -50 (getf x :zmin) (getf x :zmax) 50))) input)) (22-part1-filter (input 22 'toy-example)) (22-part1-filter (input 22 'middle-example)) (22-part1-filter (input 22 'example)) (22-part1-filter (input 22 'full)) ;;;; Solution #| The topic of this puzzle is the rectangle intersection & measure problem, which boils down to the space / object decomposition problem. See "Foundations of Multidimensional and Metric Data Structures. Hanan Samet. 2006. Published by Morgan Kaufmann, an Imprint of Elsevier. San Francisco", section 3.1. "Plane-Sweep Methods and the Rectangle Intersection Problem" (p. 428ff) and section 3.2. "Plane-Sweep Methods and the Measure Problem" (p. 447ff). The closest match is the exercise 4 of the section 3.2. (p. 452). The solution (p. 823) is essentially a reference to "J. van Leeuwen and D. Wood. The measure problem for rectangular ranges in d-space. Journal of Algorithms, 2(3):282-300, September 1981". I do not implement a region quadtree for a sweeping plane, nor do I use segment / interval trees (Bentley's approach). I recombine some of the presented ideas in a puzzle-tailored fashion instead. I will perform an adapted octree insertion whilst pursuing a data-oriented space decomposing strategy. See section 2.1.2.3. "Irregular Grid" (p. 210f) and section 2.1.2.4. "Region Quadtree and Region Octree" (p. 211ff). Naming convention: the "input space" is the unmodified, uniform space of the input. The translated grid space which maps observed axis-projected interval endpoints to the input space is called "irregular space". |# #| The mapping to the input space is governed by a lookup table. |# (defun irregular-grid-lut (input) "Returns all positions of all hyperplanes in INPUT. Includes the position just right to every interval, not the max value itself. Returns a list for each axis (x y z) with an array each. Also known as 'linear scales'." (flet ((axis-values (input min-name max-name) "Returns all hyperplane positions (as an array)." (let* ((unique-and-sorted-positions (remove-duplicates (sort (loop for step in input collect (getf step min-name) ;;Intervals are open ended on the right side. collect (1+ (getf step max-name))) #'<)))) (make-array (length unique-and-sorted-positions) :element-type 'fixnum :initial-contents unique-and-sorted-positions)))) (list (axis-values input :xmin :xmax) (axis-values input :ymin :ymax) (axis-values input :zmin :zmax)))) (length (first (irregular-grid-lut (input 22 'full)))) (defun xyz2irregular (lut x y z) "Input space → irregular space conversion." (list (position x (first lut)) (position y (second lut)) (position z (third lut)))) (xyz2irregular (irregular-grid-lut (input 22 'middle-example)) -54112 41 53682) (defun irregular2xyz (lut x y z) "Irregular space → input space conversion." (list (aref (first lut) x) (aref (second lut) y) (aref (third lut) z))) (irregular2xyz (irregular-grid-lut (input 22 'middle-example)) 0 28 37) (defun 22-input (source &key irregular-space? optimize? part1? reverse-time?) "Input of day 22 in customized configurations. If IRREGULAR-SPACE? is non-nil, the input is returned in irregular space, not in input space (the input space is the default). If OPTIMIZE? is non-nil, the input is retuned as an array (0:xmin 1:xmax ... 5:zmax 6:set-value as 0/1), not like the parsed input format. If PART1? is non-nil, the input is filtered for values that lie within [-50..50] on each axis. If REVERSE-TIME? is non-nil, the order of the steps in the input is reversed." (let* ((input (input 22 source)) (possibly-filtered-input (if part1? (22-part1-filter input) input)) (lut (irregular-grid-lut possibly-filtered-input))) (funcall (if reverse-time? #'reverse #'identity) (loop for step in possibly-filtered-input collect (let ((min (if irregular-space? (xyz2irregular lut (getf step :xmin) (getf step :ymin) (getf step :zmin)) (list (getf step :xmin) (getf step :ymin) (getf step :zmin)))) (max (if irregular-space? (xyz2irregular lut (1+ (getf step :xmax)) (1+ (getf step :ymax)) (1+ (getf step :zmax))) (list (getf step :xmax) (getf step :ymax) (getf step :zmax))))) (if optimize? (make-array (list 7) :element-type 'fixnum :initial-contents (list (first min) (first max) (second min) (second max) (third min) (third max) (if (getf step :set-value) 1 0))) (list :set-value (getf step :set-value) :xmin (first min) :xmax (first max) :ymin (second min) :ymax (second max) :zmin (third min) :zmax (third max)))))))) (22-input 'toy-example :part1? nil :irregular-space? T :optimize? nil :reverse-time? nil) (22-input 'toy-example :irregular-space? nil) (22-input 'toy-example :irregular-space? T) #| Decompose the space in an octree-oriented way, but use the observed endpoints as a performance-increasing guideline. |# (defun object-within-object? (xmin1 xmax1 ymin1 ymax1 zmin1 zmax1 xmin2 xmax2 ymin2 ymax2 zmin2 zmax2) "Whether object 1 shares all its cells with some or all of object 2. (Shared hyperplanes have no influence in any case.)" (declare (optimize speed) (fixnum xmin1 xmax1 ymin1 ymax1 zmin1 zmax1 xmin2 xmax2 ymin2 ymax2 zmin2 zmax2)) ;;Exploiting the fact that objects contain at least 1 cell. (and (<= xmin2 xmin1 xmax1 xmax2) (<= ymin2 ymin1 ymax1 ymax2) (<= zmin2 zmin1 zmax1 zmax2))) (defun object-intersects-object? (xmin1 xmax1 ymin1 ymax1 zmin1 zmax1 xmin2 xmax2 ymin2 ymax2 zmin2 zmax2) "Whether object 1 shares at least one cell with object 2." (declare (optimize speed) (fixnum xmin1 xmax1 ymin1 ymax1 zmin1 zmax1 xmin2 xmax2 ymin2 ymax2 zmin2 zmax2)) ;;Exploiting the fact that objects contain at least 1 cell. (and (not (or (< xmax2 xmin1) (< xmax1 xmin2))) (not (or (< ymax2 ymin1) (< ymax1 ymin2))) (not (or (< zmax2 zmin1) (< zmax1 zmin2))))) (defun block-contribution (&key lut xmin xnext ymin ynext zmin znext intersecting-steps) "Assume a default octree with branching blocks sorted in Morton / bit interleaving order (Z Y X). Now, alter the definition of the branching blocks: roughly divide the space of observed endpoints in two instead of using an uniform 2^height side length. Recursively call all branching blocks as long as the blocks intersect with at least one step in INTERSECTING-STEPS. As soon as a block is completely within all intersecting steps, take the latest set-value operation and return the volume in input space if it is T/1, 0 otherwise. Assumption: passed INTERSECTING-STEPS is already an time-reversed list. XMIN XNEXT YMIN YNEXT ZMIN ZNEXT define the current (irregularly shaped) block. The 'min' values are inclusive, the 'next' values exclusive. LUT is the lookup table which converts between the irregular space and the input space. INTERSECTING-STEPS is the set of currently intersecting steps. (This function is essentially the octree insertion, if adapted to the summing task of the puzzle.) (Also see #'submarine-explore of puzzle 12.)" (declare (optimize speed) (type fixnum xmin xnext ymin ynext zmin znext) (type (cons (simple-array fixnum (*))) lut)) (if intersecting-steps (cond ;;Base case: the block is within all intersecting steps. ((loop for step in intersecting-steps always (locally (declare (type (simple-array fixnum (*)) step)) (object-within-object? xmin (1- xnext) ymin (1- ynext) zmin (1- znext) (aref step 0) (1- (aref step 1)) (aref step 2) (1- (aref step 3)) (aref step 4) (1- (aref step 5))))) ;;If activated, return the volume of the current block in input space. (if (= 1 (the (integer 0 1) (aref (locally (declare (type (cons (simple-array fixnum (*))) intersecting-steps)) (car intersecting-steps)) 6))) (let* ((x-lut (the (simple-array fixnum (*)) (first lut))) (y-lut (the (simple-array fixnum (*)) (second lut))) (z-lut (the (simple-array fixnum (*)) (third lut)))) (* (the (integer -262144 262144) (- (aref x-lut xnext) (aref x-lut xmin))) (the (integer -262144 262144) (- (aref y-lut ynext) (aref y-lut ymin))) (the (integer -262144 262144) (- (aref z-lut znext) (aref z-lut zmin))))) 0)) ;;Recursive case if there are intersecting steps: divide the space in the middle of the span of observed values (per axis). (T (let ((x-divisible? (< 1 (- xnext xmin))) (y-divisible? (< 1 (- ynext ymin))) (z-divisible? (< 1 (- znext zmin))) (sum 0) (xhalfsize (floor (- xnext xmin) 2)) (yhalfsize (floor (- ynext ymin) 2)) (zhalfsize (floor (- znext zmin) 2))) (locally (declare (type fixnum sum)) ;;The branching block hyperrectangles are not of equal side length (even though the endpoints are strictly monotonically increasing when this function is called with irregular space) and may split along certain axes only (mainly because of unit-sized block sides). (loop for x? in (if x-divisible? '(nil T) '(nil)) do (loop for y? in (if y-divisible? '(nil T) '(nil)) do (loop for z? in (if z-divisible? '(nil T) '(nil)) do (let ((new-xmin (if x? (the fixnum (+ xmin xhalfsize)) xmin)) (new-xnext (if (or x? (not x-divisible?)) xnext (the fixnum (+ xmin xhalfsize)))) (new-ymin (if y? (the fixnum (+ ymin yhalfsize)) ymin)) (new-ynext (if (or y? (not y-divisible?)) ynext (the fixnum (+ ymin yhalfsize)))) (new-zmin (if z? (the fixnum (+ zmin zhalfsize)) zmin)) (new-znext (if (or z? (not z-divisible?)) znext (the fixnum (+ zmin zhalfsize))))) (incf sum (block-contribution ;;The intersecting steps of any branching block are a subset of the intersecting steps of the current block. :intersecting-steps (loop for step in intersecting-steps when (locally (declare (type (simple-array fixnum (*)) step)) (object-intersects-object? new-xmin (1- new-xnext) new-ymin (1- new-ynext) new-zmin (1- new-znext) (aref step 0) (1- (aref step 1)) (aref step 2) (1- (aref step 3)) (aref step 4) (1- (aref step 5)))) collect step) :lut lut :xmin new-xmin :xnext new-xnext :ymin new-ymin :ynext new-ynext :zmin new-zmin :znext new-znext)))))) sum)))) ;;No intersecting step. 0)) (defun 22-solution (&key (source T) (part1? T)) "Call #'block-contribution with the correct parameter values." (let* ((input (22-input source :optimize? nil :irregular-space? nil :part1? part1? :reverse-time? T)) (input-optimized (22-input source :optimize? T :irregular-space? T :part1? part1? :reverse-time? T)) (lut (irregular-grid-lut input))) (block-contribution :intersecting-steps input-optimized :lut lut :xmin 0 ;;The octree operations are done in irregular space (except the volume calculations, for which the lut is needed). :xnext (1- (array-total-size (first lut))) :ymin 0 :ynext (1- (array-total-size (second lut))) :zmin 0 :znext (1- (array-total-size (third lut)))))) ;;Target: 39. (22-solution :source 'toy-example :part1? T) ;;Target: 590784. (22-solution :source 'middle-example :part1? T) (defmethod solution ((day (eql 22)) (variant (eql 'part1)) source) "The number of activated reactor cells when reboot steps with interval endpoints in [-50,50] are considered." (22-solution :source source :part1? T)) (is 22 'part1 474140) (defmethod solution ((day (eql 22)) (variant (eql 'part2)) source) "The number of activated reactor cells when all reboot steps are considered." (22-solution :source source :part1? nil)) (is 22 'part2 2758514936282235)
17,371
Common Lisp
.lisp
278
45.543165
449
0.548487
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
3c3a51103209c934f34554364396e8a8bba7cabd88106f8a516feb668a4a4360
41,827
[ -1 ]
41,828
25.lisp
b-steger_adventofcode2021/src/25.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule sea-cucumber (or #\> #\v #\.) (:lambda (input) (cond ((string= ">" input) '>) ((string= "v" input) 'v) (T '+)))) (defrule 25-line (+ sea-cucumber) (:lambda (input) input)) (parse '25-line "...>>>>>...") (defrule 25-file (and (+ (and 25-line (? new)))) (:lambda (input) (let ((entries (elt input 0))) ;;#'reverse: northing, see puzzle 9. (reverse (mapcar #'first entries))))) (defmethod input ((day (eql 25)) source) "Multidimensional array representing the sea floor of the Mariana trench. Values are '> for horizontally-moving sea cucumbers and 'v for vertically-moving ones, '+ for the empty sea floor." (let* ((nested-lists (parse '25-file (read-file day source))) (height (length nested-lists)) (width (length (first nested-lists)))) (make-array (list height width) :initial-contents nested-lists))) (input 25 'toy-example) (input 25 'middle-example) (input 25 T) (input 25 'full) ;;;; Solution #| Additional data structures such as ... interweaved skip lists won't help a lot here. |# ;;See #'wrapping-move which has to be placed before #'neighbour-lut in 15.lisp. (defun draw-map (map &optional (stream *standard-output*)) "Draw the MAP onto STREAM. Returns a string if the STREAM is nil." (with-output-to-string (out) (format (or stream out) "~%") (loop for northing downfrom (1- (array-dimension map 0)) downto 0 do (loop for easting from 0 below (array-dimension map 1) do (format (or stream out) "~A" (aref map northing easting)) finally (format (or stream out) "~%"))))) (draw-map (input 25 'toy-example) nil) (defun forage (map neighbours &key (steps nil) (counter 1) (wished-result 'counter)) "Simulates two herds of sea cucumbers and returns - as the default - the number of steps before all animals stop moving. If STEPS is set, only simulate STEPS steps. Valid values for WISHED-RESULT: 'counter or 'map. COUNTER is for internal use only. (Reasoning for the initialization to 1: the first call is the first step.)" (if (and steps (= 0 steps)) ;;1+: the current invocation itself. (if (eql wished-result 'counter) counter map) (let ( ;;The next two map the current-index → T. An entry means that an animal has reached this place. (>-moved (make-hash-table)) (v-moved (make-hash-table)) ;;The next two map the current-index → T. An entry means that an animal was at this place. Is only relevant in the respective group loop. (>-occupied (make-hash-table)) (v-occupied (make-hash-table))) (flet ((animal-move (own-index next-index group) (when (and (eql '+ (row-major-aref map next-index)) (not (gethash next-index (if (eql '> group) >-occupied v-occupied)))) (setf ;;Remember where the animal was. (gethash own-index (if (eql '> group) >-occupied v-occupied)) T ;;Block the place the animal has moved to. (gethash next-index (if (eql '> group) >-moved v-moved)) T (row-major-aref map own-index) '+ (row-major-aref map next-index) group)))) (loop for i from 0 below (array-total-size map) when (and (eql '> (row-major-aref map i)) (not (gethash i >-moved))) do (animal-move i (second (row-major-aref neighbours i)) '>)) (loop for i from 0 below (array-total-size map) when (and (eql 'v (row-major-aref map i)) (not (gethash i v-moved))) do (animal-move i (third (row-major-aref neighbours i)) 'v)) (forage map neighbours :steps ;;Check whether any animal can move in the next step. (if (loop for i from 0 below (array-total-size map) when (and (eql '> (row-major-aref map i)) (eql '+ (row-major-aref map (second (row-major-aref neighbours i))))) return T when (and (eql 'v (row-major-aref map i)) (eql '+ (row-major-aref map (third (row-major-aref neighbours i))))) return T) (and steps (1- steps)) 0) :counter (1+ counter) :wished-result wished-result))))) (draw-map (forage (input 25 'toy-example) (neighbour-lut (input 25 'toy-example) :wrapping-is-allowed? T) :steps 1 :wished-result 'map) nil) (draw-map (forage (input 25 'middle-example) (neighbour-lut (input 25 'middle-example) :wrapping-is-allowed? T) :steps 4 :wished-result 'map) nil) (defmethod solution ((day (eql 25)) (variant (eql 'part1)) source) "Number of steps before the two herds of sea cucumbers stop moving while foraging for food." (forage (input day source) (neighbour-lut (input day source) :wrapping-is-allowed? T) :steps nil :wished-result 'counter)) (is 25 'part1 58) ;;Defined since the report does not compute applicable methods. (defmethod solution ((day (eql 25)) (variant (eql 'part2)) source) "The last star is a present." (declare (ignorable day variant source)) 0) (is 25 'part2 0)
6,344
Common Lisp
.lisp
118
43.855932
251
0.60609
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
c2126537774e73b78c523e36cc807674ec06c15eb4c794c4af9d9b613a1db6b1
41,828
[ -1 ]
41,829
03.lisp
b-steger_adventofcode2021/src/03.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule binary-number (and (+ (or #\0 #\1))) (:lambda (input) (let ((number (elt input 0))) (mapcar (lambda (x) (if (string= "1" x) 1 0)) number)))) (parse 'binary-number "00100") (parse 'binary-number "111010111011") (defrule 03-file (+ (and binary-number (? new))) (:lambda (input) (mapcar #'first input))) (defmethod input ((day (eql 3)) source) (parse '03-file (read-file day source))) (input 3 T) (input 3 'full) ;;;; Solution (defun to-decimal (bit-list) "Convert a list of bits (0 or 1) to an integer." (parse-integer (format nil "~{~A~}" bit-list) :radix 2)) ;;Can use (- 1 (most-common-bit ...)) for the inverse as mandated by the spec. (defun most-common-bit (input position) "Returns the most common bit in the column determined by POSITION. INPUT is like puzzle input. Returns 1 if equally common." ;;THINK: #'logcount or #'logxor/#'logbitp with #'mask-field along "vertical numbers"? → Lists are good enough. (if (< (loop for i in input sum (elt i position)) (/ (length input) 2)) 0 1)) (most-common-bit (input 3 T) 0) (most-common-bit '((0) (0) (1) (1)) 0) (defmethod solution ((day (eql 3)) (variant (eql 'part1)) source) "Choose the most common bit of a column, interpret those statistics as integer (called gamma) and additionally bitwise-invert it (called epsilon)." (let* ((input (input 3 source)) (integer-size (length (first input))) (gamma-binary (loop for pos from 0 below integer-size collect (most-common-bit input pos))) (epsilon-binary (loop for x in gamma-binary collect (- 1 x))) (gamma-decimal (to-decimal gamma-binary)) (epsilon-decimal (to-decimal epsilon-binary))) ;;Power consumption. (* gamma-decimal epsilon-decimal))) (is 3 'part1 198) (defun rating (&key input pos scrubber?) "Filter for numbers in INPUT which have the most common bit across all columns at POS if scrubber? is nil (called O2 rating). the least common bit across all columns at POS if scrubber? is non-nil (called scrubber rating)." (if (cdr input) (rating :input (remove-if-not (lambda (x) (= (if scrubber? (- 1 (most-common-bit input pos)) (most-common-bit input pos)) (elt x pos))) input) :pos (1+ pos) :scrubber? scrubber?) (car input))) (rating :input (input 3 T) :pos 0) (rating :input (input 3 T) :pos 0 :scrubber? T) (defmethod solution ((day (eql 3)) (variant (eql 'part2)) source) "The product of the oxygen generator rating and the CO2 scrubber rating." (let ((input (input day source))) (* (to-decimal (rating :input input :pos 0)) (to-decimal (rating :input input :pos 0 :scrubber? T))))) (is 3 'part2 230)
3,691
Common Lisp
.lisp
76
42.815789
251
0.654636
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
34fe3f126188fe77b20ddae77b607887427b94960d7c286c59d4332b5e87d8b8
41,829
[ -1 ]
41,830
04.lisp
b-steger_adventofcode2021/src/04.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule 04-draws (+ (and integer (? #\,))) (:lambda (input) (mapcar #'first input))) (parse '04-draws "1,2,3") (defrule 04-board-line (and white integer white-force integer white-force integer white-force integer white-force integer) (:lambda (input) (let ((first (elt input 1)) (second (elt input 3)) (third (elt input 5)) (fourth (elt input 7)) (fifth (elt input 9))) ;;THINK: vector? → YAGNI (list first second third fourth fifth)))) (parse '04-board-line " 22 13 17 11 0") (defrule 04-board (and 04-board-line new 04-board-line new 04-board-line new 04-board-line new 04-board-line) (:lambda (input) (let ((first (elt input 0)) (second (elt input 2)) (third (elt input 4)) (fourth (elt input 6)) (fifth (elt input 8))) (list first second third fourth fifth)))) (parse '04-board "22 13 17 11 0 8 2 23 4 24 21 9 14 16 7 6 10 3 18 5 1 12 20 15 19") (defrule 04-file (and 04-draws new new (+ (and 04-board (? (+ new))))) (:lambda (input) (let ((draws (elt input 0)) (boards (elt input 3))) (list draws (mapcar #'first boards))))) (defmethod input ((day (eql 4)) source) "Returns the list (list draws boards)" (parse '04-file (read-file day source))) (input 4 T) (input 4 'full) ;;;; Solution (defun marked? (number) "Whether a NUMBER is marked (>=1000) or not." (>= number 1000)) (defun mark! (board number) "Mark all elements in BOARD which are #'= to NUMBER, i.e. increase it by 1000." (loop for row in board collect (loop for col in row collect (if (= number col) (incf col 1000) col)))) (mark! (first (second (input 4 T))) 7) (defun mark-boards! (boards number) "Apply #'mark to all BOARDS." (loop for board in boards collect (mark! board number))) (mark-boards! (second (input 4 T)) 7) (defun row-wins? (board row) "Whether all numbers in a ROW (offset by 0) are marked." (every #'marked? (elt board row))) (let ((a-board '((22 13 17 11 0) (1008 1002 1023 1004 1024) (21 9 14 16 7) (6 10 3 18 5) (1 12 20 15 19)))) (list (row-wins? a-board 0) (row-wins? a-board 1))) (defun column-wins? (board column) "Whether all numbers in a COLUMN (offset by 0) are marked." (every #'marked? (loop for row in board collect (elt row column)))) (let ((a-board '((22 1013 17 11 0) (8 1002 23 4 24) (21 1009 14 16 7) (6 1010 3 18 5) (1 1012 20 15 19)))) (list (column-wins? a-board 0) (column-wins? a-board 1))) (defun board-wins? (board) "Whether a row or a column of BOARD consists solely of marked numbers." (loop for i from 0 below 5 do (when (or (row-wins? board i) (column-wins? board i)) (return T)))) (let ((a-board '((22 1013 17 11 0) (8 1002 23 4 24) (21 1009 14 16 7) (6 1010 3 18 5) (1 1012 20 15 19)))) (board-wins? a-board)) (defun score (board number-called) "Sum all unmarked numbers in a BOARD and multiply this sum by NUMBER-CALLED." (* (loop for row in board summing (loop for x in row unless (marked? x) summing x)) number-called)) (score '((14 21 17 24 4) (10 16 15 9 19) (18 8 23 26 20) (22 11 13 6 5) ( 2 0 12 3 7)) 24) (defun draw-number (remaining-draws boards old-draw) "Unless a winning board is found, go through a list of draws and apply it to BOARDS. Defined recursively." (let ((winner (find-if #'board-wins? boards))) (or (when winner (list winner old-draw)) (if (cdr remaining-draws) ;;Recursive case. (draw-number (cdr remaining-draws) (mark-boards! boards (first remaining-draws)) (first remaining-draws)) ;;Base case. (list (mark-boards! boards (car remaining-draws)) (car remaining-draws)))))) (let ((input (input 4 T))) (draw-number (first input) (second input) (first (first input)))) (defmethod solution ((day (eql 4)) (variant (eql 'part1)) source) "The score of the first winning bingo board." (let* ((input (input 4 source)) (draws (first input)) (boards (second input)) (winner-board (draw-number draws boards (first draws)))) ;;Alternative: #'multiple-value-bind. (score (first winner-board) (second winner-board)))) (is 4 'part1 4512) (defun draw-number-part2 (remaining-draws boards old-draw old-winner last-winner-draw) "Determine the last board which wins." (let* ((a-winner-in-list (find-if #'board-wins? boards)) (a-winner (or a-winner-in-list old-winner)) ;;Remove winning boards before descending. (boards (remove-if #'board-wins? boards))) (if remaining-draws ;;Recursive case. (draw-number-part2 (cdr remaining-draws) (mark-boards! boards (first remaining-draws)) (first remaining-draws) a-winner ;;Retain the called number of the last winner. (if a-winner-in-list old-draw last-winner-draw)) ;;Base case. (list a-winner last-winner-draw)))) (defmethod solution ((day (eql 4)) (variant (eql 'part2)) source) "The score of the last winning bingo board." (let* ((input (input 4 source)) (draws (first input)) (boards (second input)) (winner-board (draw-number-part2 draws boards (first draws) nil nil))) (score (first winner-board) (second winner-board)))) (is 4 'part2 1924)
7,132
Common Lisp
.lisp
170
32.270588
251
0.56548
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
12e54f4cd25cca0fc588c135fc00acb241f972894591a1b873ebdcbbf84c9556
41,830
[ -1 ]
41,831
20.lisp
b-steger_adventofcode2021/src/20.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defun seafloorascii2bit (char) "Converts #\# => 1 and #\. => 0." (if (string= char "#") 1 0)) (defrule enhancement-lut (+ (or #\. #\#)) (:lambda (input) (make-array (list (length input)) :element-type 'bit :initial-contents (mapcar #'seafloorascii2bit input)))) (simple-bit-vector-p (parse 'enhancement-lut "..#.#..##")) (defrule seafloor-map (+ (and (+ (or #\. #\#)) (? new))) (:lambda (input) (mapcar (lambda (x) (mapcar #'seafloorascii2bit x)) (mapcar #'first input))) (:lambda (input) (make-array (list (length input) (length (first input))) :element-type 'bit ;;Reversing because of northing, see parser rule 09-file in 09.lisp. :initial-contents (reverse input)))) (parse 'seafloor-map "#..#. #.... ##..# ..#.. ..###") (defrule 20-file (and enhancement-lut new new seafloor-map) (:lambda (input) (let ((lut (elt input 0)) (map (elt input 3))) (list lut map)))) (parse '20-file (read-file 20 'example)) (defmethod input ((day (eql 20)) source) "An enhancement lookup table (simple bit vector) and a seafloor map (multidimensional array of bits)." (parse '20-file (read-file 20 source))) (input 20 T) (input 20 'full) ;;;; Solution #| There is the possibility that a pixel outside of the map is lit. Which means that the map must be able to accept a buffer of one pixel per step. For 2 steps, a buffer of 2 is enough. For 50 50. |# (defun buffered-map (map buffer initvalue) "Surround the rectangle MAP with zeroes, i.e. copy an array in the middle of a new one with widths/heights increased by (* 2 BUFFER)." (let ((width (array-dimension map 1)) (height (array-dimension map 0)) (new-map (make-array (mapcar (lambda (x) (+ (* buffer 2) x)) (array-dimensions map)) :element-type 'bit ;;See #'enhance-image. :initial-element initvalue))) (loop for northing from 0 below height do (loop for easting from 0 below width do (setf (aref new-map (+ buffer northing) (+ buffer easting)) (aref map northing easting)))) new-map)) (buffered-map (second (input 20 T)) 2 0) (neighbour-lut (buffered-map (second (input 20 T)) 2 0) :lut *8direction-vectors* :positional-neighbours? T) (defun enhance-image (enhancement-lut map &key (steps-after 1)) "Return a new array which is larger since it is buffered with a buffer of size 1. Additionally, every rmindex is the result of a moving window function." (let* ((default (if (and (= 1 (aref enhancement-lut 0)) (= 0 (aref enhancement-lut (1- (array-dimension enhancement-lut 0))))) ;;Steer against flipping. This is needed even though the requested steps are even - the border areas get affected by the surrounding open land. (- 1 (rem steps-after 2)) 0)) (buffered-source-map (buffered-map map 1 default)) ;;Can use any input (of correct size) since all values will get overriden. (buffered-result-map (buffered-map map 1 default)) (neighbour-lut (neighbour-lut buffered-source-map :lut *8direction-vectors* :positional-neighbours? T))) (loop for i from 0 below (array-total-size buffered-source-map) do (setf (row-major-aref buffered-result-map i) (aref enhancement-lut (to-decimal (let ((neighbours (make-array ;;8: number of neighbours in a 2d map. '(8) :initial-contents (mapcar (lambda (x) (if x (row-major-aref buffered-source-map x) default)) (row-major-aref neighbour-lut i))))) ;;The indices 0..8 of the spec refer to directions 315 0 45 270 i 90 225 180 135, respectively. (list (aref neighbours 7) (aref neighbours 0) (aref neighbours 1) (aref neighbours 6) ;;The value itself. (row-major-aref buffered-source-map i) (aref neighbours 2) (aref neighbours 5) (aref neighbours 4) (aref neighbours 3))))))) (if (= 0 steps-after) buffered-result-map (enhance-image enhancement-lut buffered-result-map :steps-after (1- steps-after))))) (let* ((input (input 20 T)) (output (enhance-image (first input) (second input) :steps-after 1))) (format nil "~A" (with-output-to-string (*standard-output*) (loop for line from (1- (array-dimension output 0)) downto 0 do (progn (loop for col from 0 below (array-dimension output 1) do (princ (if (= 0 (aref output line col)) "." "#"))) (terpri)))))) (defun solution-20 (source part2?) "Enhance the map and count the number of light pixels." (let* ((input (input 20 source)) (enhanced (enhance-image (first input) (second input) :steps-after (if part2? 49 1)))) (loop for i from 0 below (array-total-size enhanced) sum (row-major-aref enhanced i)))) (defmethod solution ((day (eql 20)) (variant (eql 'part1)) source) "The number of light pixels after 2 image enhancement steps." (solution-20 source nil)) (is 20 'part1 35) (defmethod solution ((day (eql 20)) (variant (eql 'part2)) source) "The number of light pixels after 50 image enhancement steps." (solution-20 source T)) (is 20 'part2 3351)
7,006
Common Lisp
.lisp
131
40.832061
251
0.570491
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
210dd48a9ec1ccf29e35ad4bacd89ee89a8395e8adfa217275b846f020a4fd75
41,831
[ -1 ]
41,832
05.lisp
b-steger_adventofcode2021/src/05.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule 05-coord (and integer "," integer) (:lambda (input) (let ((x (elt input 0)) (y (elt input 2))) (list x y)))) (parse '05-coord "123,456") (defrule 05-line (and 05-coord " -> " 05-coord) (:lambda (input) (let ((start (elt input 0)) (end (elt input 2))) (list start end)))) (parse '05-line "0,9 -> 5,9") (defrule 05-file (and (+ (and 05-line (? new)))) (:lambda (input) (let ((entries (elt input 0))) (mapcar #'first entries)))) (defmethod input ((day (eql 5)) source) "List of lines. A line is a list of start and end coordinates. A coordinate is a list of x and y." (parse '05-file (read-file day source))) (input 5 T) (input 5 'full) ;;;; Solution (defun coord (x y) "Construct a coordinate." (list x y)) (defun x (coordinate) "The position on the x axis of a coordinate." (first coordinate)) (defun y (coordinate) "The position on the y axis of a coordinate." (second coordinate)) (defun coord= (coordinate-1 coordinate-2) (and (= (x coordinate-1) (x coordinate-2)) (= (y coordinate-1) (y coordinate-2)))) (defun offset (coordinate by-x by-y) "Adds BY-X and BY-Y to COORDINATE." (list (+ (first coordinate) by-x) (+ (second coordinate) by-y))) (offset (list 1 2) 3 4) (defun line (start end) "Construct a line." (list start end)) (defun start (line) "The starting coordinate of a LINE." (first line)) (defun end (line) "The ending coordinate of a LINE." (second line)) (defun direction (number) "Whether a number is positive (return 1), zero (return 0) or negative (return -1)." (cond ((minusp number) -1) ((zerop number) 0) (T 1))) (mapcar #'direction '(-3 0 3)) (defun drawn-pixels (line &optional diagonal-forbidden?) "Returns the coordinates a LINE (format see parser rule '05-line) covers. Contract: LINE has the same x, same y or the same difference." (let* ((start (start line)) (end (end line)) (dist-x (- (x end) (x start))) (dist-y (- (y end) (y start)))) (unless (and diagonal-forbidden? (not (zerop dist-x)) (not (zerop dist-y))) (if (coord= start end) (list end) (cons start (drawn-pixels (line (offset start (direction dist-x) (direction dist-y)) (second line)))))))) (drawn-pixels '((0 0) (4 0)) T) (drawn-pixels '((0 0) (4 0))) (drawn-pixels '((0 0) (0 4))) (drawn-pixels '((0 0) (5 5))) (drawn-pixels '((0 0) (5 5)) T) (drawn-pixels '((0 0) (-5 5))) (drawn-pixels '((0 0) (-5 5)) T) (mapcar (lambda (x) (drawn-pixels x T)) (input 5 T)) (drawn-pixels (elt (input 5 T) 0) T) (defun 05-solution (day source diagonal-forbidden?) "Draw pixels and tally them." (let ((covered-pixels (loop for line in (input day source) append (drawn-pixels line diagonal-forbidden?))) (tally (make-hash-table :test 'equal))) (loop for pixel in covered-pixels do (setf (gethash pixel tally) (if (gethash pixel tally) (incf (gethash pixel tally)) 1))) (loop for entry being the hash-value of tally when (> entry 1) counting entry))) (defmethod solution ((day (eql 5)) (variant (eql 'part1)) source) "The number of intersections of axis-aligned hydrothermal vent groups." (05-solution day source T)) (is 5 'part1 5) (defmethod solution ((day (eql 5)) (variant (eql 'part2)) source) "The number of intersections of diagonal and axis-aligned hydrothermal vent groups." (05-solution day source nil)) (is 5 'part2 12)
4,531
Common Lisp
.lisp
108
36.203704
251
0.628948
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
d41dcbf96ee55e119bda3cfb61a5df63ef99d97936a1ab982f2984041e2f7284
41,832
[ -1 ]
41,833
01.lisp
b-steger_adventofcode2021/src/01.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule 01-file (+ (and integer (? new))) (:lambda (input) (mapcar #'first input))) (defmethod input ((day (eql 1)) source) (parse '01-file (read-file day source))) (input 1 T) ;;;; Solution (defun count-increasing (list &optional lagging) "The number of increasing values in LIST." (if list (+ (if (< (or lagging (first list)) (first list)) 1 0) (count-increasing (rest list) (first list))) 0)) (defmethod solution ((day (eql 1)) (variant (eql 'part1)) source) "Count the number of times a value in a sequence is increasing." (count-increasing (input 1 source))) (is 1 'part1 7) (defun summing-moving-window (list) "Recursive moving window which sums three numbers." (cons (+ (first list) (second list) (third list)) (when (cdddr list) (summing-moving-window (rest list))))) (summing-moving-window (input 1 T)) (defmethod solution ((day (eql 1)) (variant (eql 'part2)) source) "Part 1, but with a summing moving window of size three passing over the input." (count-increasing (summing-moving-window (input 1 source)))) (is 1 'part2 5)
1,938
Common Lisp
.lisp
39
46.153846
251
0.706038
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
6d344739671e979ff91695ccc3e1060c248fd345fc57f0dea38547aa184836a6
41,833
[ -1 ]
41,834
21.lisp
b-steger_adventofcode2021/src/21.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule starting-position (and "Player " integer " starting position: " integer) (:lambda (input) (elt input 3))) (parse 'starting-position "Player 1 starting position: 4") (defrule 21-file (+ (and starting-position (? new))) (:lambda (input) (mapcar #'first input))) (defmethod input ((day (eql 21)) source) "List denoting the starting positions of the two players." (parse '21-file (read-file 21 source))) (input 21 T) ;;;; Solution (loop for i from 0 below 210 collect (1+ (mod i 100))) (defun roll-die (times-rolled) "The sum of rolling the deterministic 100-sided die three times." (let ((roll (mod times-rolled 100))) (reduce #'+ (mapcar (lambda (x) (1+ (mod (+ roll x) 100))) '(0 1 2))))) (roll-die 0) ;;Externally space 3 (internally starting at 0, externally at 1). (1+ (mod (+ (1- 8) (roll-die 3)) 10)) (list (roll-die 98) (roll-die 99) (roll-die 100) (roll-die 198) (roll-die 199) (roll-die 200) (roll-die 201) (roll-die 202)) (defun move-pawn (start-pos-external number-of-times) "Move the pawn on the circular track of size 10." (declare (fixnum start-pos-external number-of-times) (optimize speed)) ;;This externally-internally thing is a form of escaping. (1+ (mod (+ (the fixnum (1- start-pos-external)) number-of-times) 10))) (move-pawn 7 (+ 2 2 1)) (defun dirac-part1 (&key (current-player 1) (space1 0) (space2 0) (score1 0) (score2 0) (times-rolled 0)) "Play the Dirac dice game: roll a die three times, move forward rolled times on a circular board of size 10 and add the board position to the score. The first player with 1000 points wins. The function returns, amongst its final state, the number of times the die was rolled multiplied by the score of the player who did not win. CURRENT-PLAYER is the player ID, i.e. either 1 or 2." (let* ((roll (roll-die times-rolled)) (new-space (move-pawn (if (= 1 current-player) space1 space2) roll)) (new-score (+ (if (= 1 current-player) score1 score2) new-space))) (cond ((>= new-score 1000) (list :current-player current-player :space1 space1 :space2 space2 :score1 score1 :score2 score2 :times-rolled times-rolled :roll roll :new-space new-space :new-score new-score ;;3: TIMES-ROLLED remained unchanged even though the player has made it's turn in the meantime. :part1-number (* (+ times-rolled 3) (if (= 1 current-player) score2 score1)))) (T (dirac-part1 ;;3: Sum of player id 1 and player id 2. :current-player (- 3 current-player) :space1 (if (= 1 current-player) new-space space1) :score1 (if (= 1 current-player) new-score score1) :space2 (if (= 2 current-player) new-space space2) :score2 (if (= 2 current-player) new-score score2) ;;3: The player rolled the die three times. :times-rolled (+ 3 times-rolled)))))) (dirac-part1 :space1 (first (input 21 T)) :space2 (second (input 21 T))) (defmethod solution ((day (eql 21)) (variant (eql 'part1)) source) "Play the Dirac dice game until someone wins. Return the score of the player not winning multiplied by the number of times the die was rolled." (let ((input (input day source))) (getf (dirac-part1 :space1 (first input) :space2 (second input)) :part1-number))) (is 21 'part1 739785) ;;412344 (find (solution 21 'part1 'full) (loop for i from 1 below 11 append (loop for j from 1 below 11 collect (getf (dirac-part1 :space1 i :space2 j) :part1-number)))) ;;; Part2 #| Playing 444356092776315 + 341960390180808 = 786316482957123 games is computationally infeasible, or playing the game 786316482957123 times is not the intention of the puzzle at least. This puzzle must reach the number in a different way and consequently shares similarities with day 6 and day 14. Nevertheless, the tree of dice rolls, which I want to realize through recursive calls, must be visited exhaustively, since every outcome is requested explicitly. This torpedoes any game tree pruning approaches. An analysis of all possible outcomes in the part1 games shows that 30 out of 100 scores are duplicates: |# ;;=> (100 70) (let ((possible-part1-games (loop for i from 1 below 11 append (loop for j from 1 below 11 collect (getf (dirac-part1 :space1 i :space2 j) :part1-number))))) (list (length possible-part1-games) (length (remove-duplicates possible-part1-games)))) #| As a consequence, a reduction must be possible. Idea: the combinations that are requested are partially subsumed under a single turn. A 1-2-3 is the same as a 1-3-2, as it results in the same progress on the board in the same atomic turn. |# (let* ((die-rolls (loop for i from 1 below 4 append (loop for j from 1 below 4 append (loop for k from 1 below 4 collect (+ i j k))))) (expected-number-of-combinations (expt 3 3)) (effective-number-of-combinations (length die-rolls)) (game-tree-leaves (sort (remove-duplicates die-rolls) #'<)) (roll-sum-tally (mapcar (lambda (x) (count-if (lambda (y) (= x y)) die-rolls)) game-tree-leaves))) (list expected-number-of-combinations effective-number-of-combinations game-tree-leaves roll-sum-tally)) (defparameter *all-possible-dirac-3-dice-rolls* ;;'(1 3 6 7 6 3 1): roll-sum-tally in previous form. (loop with game-tree-leaves = '(1 3 6 7 6 3 1) ;;3 and 10: rebuilding game-tree-leaves from previous form. for i from 3 below 10 collect (list i (elt game-tree-leaves (- i 3)))) "List containing lists with the sum a player can throw in a single turn and the combinatorial share (tally).") (declaim (ftype (function (&key (:rolled-sum fixnum) (:player1current? boolean) (:space1 fixnum) (:space2 fixnum) (:score1 fixnum) (:score2 fixnum) (:depth-factor fixnum)) null) dirac-part2)) (defun dirac-part2 (&key rolled-sum (player1current? T) (space1 0) (space2 0) (score1 0) (score2 0) ;;Combine the tallies by multiplying them. (depth-factor 1)) "Construct the dirac game tree and count the number of wins for each player. Expects a context which is set up by #'21-solution-part2." (declare (special *player1sum* *player2sum*) (optimize speed)) (let* ((new-space (the fixnum (move-pawn (if player1current? space1 space2) rolled-sum))) (new-score (+ (if player1current? score1 score2) new-space))) (cond ((>= new-score 21) ;;The current player has won this game. (if player1current? (incf (the fixnum *player1sum*) depth-factor) (incf (the fixnum *player2sum*) depth-factor))) (T (loop for (sum tally) in *all-possible-dirac-3-dice-rolls* do (dirac-part2 :rolled-sum sum :player1current? (not player1current?) :space1 (if player1current? new-space space1) :score1 (if player1current? new-score score1) :space2 (if player1current? space2 new-space) :score2 (if player1current? score2 new-score) :depth-factor (* (the (integer 1 7) tally) (the (integer 1 99999999999) depth-factor))))))) nil) (defun 21-solution-part2 (input) "Set up the context for #'dirac-part2 and return the winner game tree size." (let* ((space1 (first input)) (space2 (second input)) (*player1sum* 0) (*player2sum* 0)) (declare (special *player1sum* *player2sum*) (fixnum space1 space2 *player1sum* *player2sum*)) (loop for (sum tally) in *all-possible-dirac-3-dice-rolls* do (dirac-part2 :rolled-sum sum :player1current? T :space1 space1 :space2 space2 :depth-factor tally)) (max *player1sum* *player2sum*))) (defparameter *puzzle-21-solutions* (make-array '(100) :initial-contents '(32491093007709 27674034218179 48868319769358 97774467368562 138508043837521 157253621231420 141740702114011 115864149937553 85048040806299 57328067654557 27464148626406 24411161361207 45771240990345 93049942628388 131888061854776 149195946847792 133029050096658 106768284484217 76262326668116 49975322685009 51863007694527 45198749672670 93013662727308 193753136998081 275067741811212 309991007938181 273042027784929 214368059463212 147573255754448 92399285032143 110271560863819 91559198282731 193170338541590 404904579900696 575111835924670 647608359455719 568867175661958 444356092776315 303121579983974 187451244607486 156667189442502 129742452789556 274195599086465 575025114466224 816800855030343 919758187195363 807873766901514 630947104784464 430229563871565 265845890886828 175731756652760 146854918035875 309196008717909 647920021341197 920342039518611 1036584236547450 911090395997650 712381680443927 486638407378784 301304993766094 152587196649184 131180774190079 272847859601291 570239341223618 809953813657517 912857726749764 803934725594806 630797200227453 433315766324816 270005289024391 116741133558209 105619718613031 214924284932572 446968027750017 634769613696613 716241959649754 632979211251440 499714329362294 346642902541848 218433063958910 83778196139157 75823864479001 148747830493442 306621346123766 435288918824107 492043106122795 437256456198320 348577682881276 245605000281051 157595953724471 56852759190649 49982165861983 93726416205179 190897246590017 270803396243039 306719685234774 274291038026362 221109915584112 158631174219251 104001566545663)) "Precomputed solutions for the puzzle 21.") (defmethod solution ((day (eql 21)) (variant (eql 'part2)) source) "The size of the winning dirac game tree when a three-sided die is considered." ;;(21-solution-part2 (input day source)) (let ((input (input day source))) (aref *puzzle-21-solutions* (+ (* (1- (first input)) 10) (1- (second input)))))) (is 21 'part2 444356092776315)
11,750
Common Lisp
.lisp
222
43.720721
507
0.657133
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
6e6c6df6b78ded4dbb1fa1fd64beb37ce903275c4fc1206647489b087a0c5273
41,834
[ -1 ]
41,835
common.lisp
b-steger_adventofcode2021/src/common.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) (defrule new (or (and #\Return #\Newline) #\Return #\Newline)) (defrule white-force (+ #\Space)) (defrule white (* white-force)) (defrule integer (+ (character-ranges (#\0 #\9))) (:text x) (:lambda (x) (parse-integer x))) (parse 'integer "0123") (defun read-file (day source) "Read the contents of an input file for a given DAY into a string. Supported SOURCEs see #'solution." (uiop:read-file-string (cl-fad:merge-pathnames-as-file (user-homedir-pathname) "quicklisp/local-projects/adventofcode2021/input/" (cond ((or (eql source 'example) (eql source T)) "example/") ((eql source 'toy-example) "toy-example/") ((eql source 'middle-example) "middle-example/") ((eql source 'full) "full/") (T (error "Unsupported source."))) (format nil "~2,'0D.txt" day)))) ;;(read-file 1 T) ;;THINK: A &key in the LAMBDA-LIST is probably a good idea since later puzzles need to twist the input data in multiple ways simultaneously. (defgeneric input (day source) (:documentation "Return input data in a parsed structure ready for processing. DAY is eql-specialized on the day number. Supported sources see #'solution.") (:method (day (source (eql T))) (input day 'example))) (defgeneric solution (day variant source) (:documentation "Return the solution for a given DAY (eql-specialized on the day number) and VARIANT (specialized on 'part1 or 'part2). Supported sources are 'toy-example 'middle-example 'example and 'full. You can use T as a shorthand for 'example. Toy examples and middle examples are used in the puzzle description in order to describe an aspect of a problem. They are useful for the development of functions which contribute towards a part1 or part2 solution.") (:method (day variant (source (eql T))) (solution day variant 'example))) (defgeneric expect (day variant) (:documentation "What return value is expected for the example.")) (defun is (day variant expect &key (register-expected-value? T)) "Register the expected value and execute #'solution before returning and comparing the value." (when register-expected-value? ;;Yes, this works. (defmethod expect ((day (eql day)) (variant (eql variant))) expect)) (let ((solution (solution day variant T))) (list :equal? (equal expect solution) :expected expect :solution solution)))
3,264
Common Lisp
.lisp
56
53.125
251
0.705569
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
3023c41bbb483fc51cf9d0c912e52ee044f926bd8bc4775fbc716eba10a676e6
41,835
[ -1 ]
41,836
09.lisp
b-steger_adventofcode2021/src/09.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule 09-line (+ (character-ranges (#\0 #\9))) (:lambda (input) (mapcar (lambda (y) (- (char-code y) 48)) input))) (parse '09-line "1294") (defrule 09-file (and (+ (and 09-line (? new)))) (:lambda (input) (let ((entries (elt input 0))) ;;#'reverse: conveniently access elements with (aref array northing easting) (see #'map-lookup). (reverse (mapcar #'first entries))))) (defmethod input ((day (eql 9)) source) "Multidimensional array representing the heightmap with heights [0..9]." (let* ((nested-lists (parse '09-file (read-file day source))) (height (length nested-lists)) (width (length (first nested-lists)))) (make-array (list height width) :initial-contents nested-lists))) (input 9 T) (input 9 'full) ;;;; Solution (defun en2rmindex (map easting northing) "EASTING/NORTHING coordinate to row-major-index (rmindex) conversion. Reduces dimensionality by using the built-in row-order space filling curve." (array-row-major-index map northing easting)) (defparameter *4direction-vectors* '((0 (0 . 1)) (90 (1 . 0)) (180 (0 . -1)) (270 (-1 . 0))) "Mathematical vectors for axis-parallel movement on a 2d grid. Realized as association lists, car is easting, cdr northing.") (defun by-vector (direction &optional (lut *4direction-vectors*)) "The mathematical vector in order to step towards a neighbour in DIRECTION [0..360]. Look-up-table LUT defaults to the dictionary *4direction-vectors*." (cadr (assoc direction lut))) (by-vector 0) (defun easting (map rmindex) "rmindex to easting conversion." (mod rmindex (array-dimension map 1))) (easting (input 9 T) 45) (defun northing (map rmindex) "rmindex to northing conversion." (floor rmindex (array-dimension map 1))) (northing (input 9 T) 45) (defun rm-coord= (rmindex-a rmindex-b) "Whether the two rmindices are #'eq." (eq rmindex-a rmindex-b)) ;;(rm-coord= '(1 . 3) '(1 . 3)) (rm-coord= 45 45) (rm-coord= (en2rmindex (input 9 T) 1 3) (en2rmindex (input 9 T) 1 3)) (defun map-lookup (map rmindex) "Returns the value of the pixel at RMINDEX in MAP." (row-major-aref map rmindex)) (defun clip-move (map start by-vector) "Returns the new coordinates (as an rmindex) after adding BY-VECTOR to START or nil if the shift crosses the borders of the map." ;;TODO: optimize movement with simple additions of array widths etc. (let* ((width (array-dimension map 1)) (height (array-dimension map 0)) (new-easting (+ (easting map start) (car by-vector))) (new-northing (+ (northing map start) (cdr by-vector)))) ;;Using common-lisp:and as control structure. (and (<= 0 new-easting (1- width)) (<= 0 new-northing (1- height)) (en2rmindex map new-easting new-northing)))) (clip-move (input 9 T) (en2rmindex (input 9 T) 2 3) '(1 . 1)) (defun direct-neighbour-values (map location) "Returns the values of the north/east/south/west neighbours for a given location on MAP denoted by EASTING and NORTHING. A neighbour outside map has the value nil. Format of MAP determined by #'input for this day. Coordinate system is rooted at the bottom left corner, EASTING shows right and NORTHING upwards." (flet ((move-by-vector (loc by) (let ((loc (clip-move map loc by))) (when loc (map-lookup map loc))))) (list ;;North. (move-by-vector location (by-vector 0)) ;;East. (move-by-vector location (by-vector 90)) ;;South. (move-by-vector location (by-vector 180)) ;;West. (move-by-vector location (by-vector 270))))) ;;Target: (8 8 NIL NIL). (direct-neighbour-values (input 9 T) (en2rmindex (input 9 T) 0 0)) ;;Target: (7 9 NIL 9). (direct-neighbour-values (input 9 T) (en2rmindex (input 9 T) 1 0)) ;;Target: (5 7 9 7). (direct-neighbour-values (input 9 T) (en2rmindex (input 9 T) 2 1)) ;;Target: (NIL 1 3 NIL). (direct-neighbour-values (input 9 T) (en2rmindex (input 9 T) 0 4)) (defun low-point? (map location) "Whether the value at LOCATION is lower (#'<) than its four/three/two neighbours." (let* ((width (array-dimension map 1)) (height (array-dimension map 0)) (own-value (map-lookup map location)) (neighbours (direct-neighbour-values map location)) ;;Windrose of booleans whether direction is outside of map. (neighbour-outside-anyway? (list ;;North. (= height (1+ (northing map location))) ;;East. (= width (1+ (easting map location))) ;;South. (= 0 (northing map location)) ;;West. (= 0 (easting map location))))) (loop for neighbour in neighbours for outside-anyway? in neighbour-outside-anyway? always (or outside-anyway? (< own-value neighbour))))) (and (low-point? (input 9 T) (en2rmindex (input 9 T) 1 4)) (low-point? (input 9 T) (en2rmindex (input 9 T) 9 4)) (low-point? (input 9 T) (en2rmindex (input 9 T) 2 2)) (low-point? (input 9 T) (en2rmindex (input 9 T) 6 0))) (defun low-points (map) "Return all points on MAP whose neighbours are higher. Point format: rmindex." (let ((width (array-dimension map 1)) (height (array-dimension map 0))) (loop for easting from 0 below width append (loop for northing from 0 below height when (low-point? map (en2rmindex map easting northing)) collect (en2rmindex map easting northing))))) (low-points (input 9 T)) (low-points (input 9 'full)) (defun risk-sum (map) "For each low point in map, add its risk level, which is defined as being height+1, to the returned value." (loop for coord in (low-points map) summing (1+ (map-lookup map coord)))) (risk-sum (input 9 T)) (defmethod solution ((day (eql 9)) (variant (eql 'part1)) source) "Sum all risk levels in the map (the input)." (risk-sum (input day source))) (is 9 'part1 15) #| Part2 solution: flood fill algorithm. Caves a b c d: a,3 ↓ +----------+ | XXX |←b,9 | X X X | |X X X | | X X| |X XXX |←d,9 +----------+ ↑ c,14 |# (defun valid-neighbours (map coord) "Returns a list of neighbours (as rmindex) which do not have height 9." (when coord (remove nil (loop for (dir . (vector)) in *4direction-vectors* collect (let* ((neighbour (clip-move map coord vector)) (n-value (when neighbour (map-lookup map neighbour)))) (when (and n-value (/= 9 n-value)) neighbour)))))) ;;Top left basin of size 3. (valid-neighbours (input 9 T) (en2rmindex (input 9 T) 1 4)) (valid-neighbours (input 9 T) (en2rmindex (input 9 T) 0 4)) (valid-neighbours (input 9 T) (en2rmindex (input 9 T) 0 3)) (valid-neighbours (input 9 T) nil) (defun flood-fill (map start-coord visited-cells) "Flood fill. Determine valid neighbours. If valid (value < 9), add neighbour to VISITED-CELLS in recursive call. If no further fresh possibilites, return VISITED-CELLS. Expects *visited-cells-map*." ;;Pure functional style took prohibitive 10s for a basin of size 83 (statistical profiling showed that the bottleneck was #'rm-coord= for (subsetp valid-neighbours visited-cells) in unvisited-neighbours in the let* below). (declare (special *visited-cells-map*)) (let* ((valid-neighbours (valid-neighbours map start-coord)) (unvisited-neighbours (loop for n in valid-neighbours unless (or (row-major-aref *visited-cells-map* n) (member n visited-cells)) collect n))) (if unvisited-neighbours (loop for n in unvisited-neighbours do (loop for cell in (flood-fill map n (append unvisited-neighbours visited-cells)) do (setf (row-major-aref *visited-cells-map* cell) T))) visited-cells))) (defun basin-size (map start-coord) "The size of a basin of which START-COORD is member of." (let ((*visited-cells-map* (make-array (array-dimensions map) :initial-element nil))) (declare (special *visited-cells-map*)) (flood-fill map start-coord nil) (loop for i from 0 below (array-total-size *visited-cells-map*) count (row-major-aref *visited-cells-map* i)))) (basin-size (input 9 T) (en2rmindex (input 9 T) 1 4)) (basin-size (input 9 T) (en2rmindex (input 9 T) 9 4)) (basin-size (input 9 T) (en2rmindex (input 9 T) 2 2)) (basin-size (input 9 T) (en2rmindex (input 9 T) 6 0)) (defun top-3-basins-product (map) "For each random starting position (determined by #'low-points), apply the flood-fill algorithm. Return the multiplied sizes of the biggest three floods. Returns all possible flood fills since all low-points were determined beforehand. No basin is determined twice (this is verified)." (let* ((basins (mapcar (lambda (x) (basin-size map x)) (low-points map))) (sizes-sorted (sort basins #'>))) (* (or (first sizes-sorted) 1) (or (second sizes-sorted) 1) (or (third sizes-sorted) 1)))) (top-3-basins-product (input 9 'full)) (defmethod solution ((day (eql 9)) (variant (eql 'part2)) source) "Multiply the sizes of the three biggest basins in the map (the input)." (top-3-basins-product (input day source))) (is 9 'part2 1134)
10,555
Common Lisp
.lisp
219
41.246575
251
0.640353
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
3d217e7e642d59f053c6715122116a26fecf061fee2280669a8812cf1618e44c
41,836
[ -1 ]
41,837
16.lisp
b-steger_adventofcode2021/src/16.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defrule 16-hex-letter (character-ranges (#\0 #\9) (#\a #\z) (#\A #\Z)) (:lambda (input) (format nil "~4,'0B" (parse-integer (text input) :radix 16)))) (parse '16-hex-letter "0") (defrule 16-hex (and (+ 16-hex-letter) (? new)) (:lambda (input) ;;Can not distinguish junk from data without parsing from the start. → Use :junk-allowed T. → Design rules with :junk-allowed T in mind. ;;(string-right-trim '(#\0) (text input)) (text (elt input 0)))) (parse '16-hex "38006F45291200") (parse '16-hex "38006F45291200 ") (defrule bit (or #\0 #\1)) (defrule packet (or packet-literal packet-operator)) (defrule packet-literal-group-continuing (and "1" bit bit bit bit) (:lambda (input) (subseq (text input) 1))) (parse 'packet-literal-group-continuing "10111") (defrule packet-literal-group-finishing (and "0" bit bit bit bit) (:lambda (input) (subseq (text input) 1))) (parse 'packet-literal-group-finishing "00101") (defrule packet-literal (and (and bit bit bit) "100" (* packet-literal-group-continuing) packet-literal-group-finishing) (:lambda (input) (let ((version (elt input 0)) (type-id (elt input 1)) (value-continuing (elt input 2)) (value-finishing (elt input 3))) (list :this-is 'packet-literal :version (parse-integer (text version) :radix 2) :type-id (parse-integer (text type-id) :radix 2) :value (parse-integer (format nil "~{~A~}~A" value-continuing value-finishing) :radix 2))))) (parse 'packet-literal (parse '16-hex "D2FE28") :junk-allowed T) (parse 'packet-literal (parse '16-hex "D2FE287") :junk-allowed T) (parse 'packet-literal "010100000010101" :junk-allowed T) (parse 'packet-literal "01010000001000000000" :junk-allowed T) (parse 'packet-literal "01010000001111111111" :junk-allowed T) (defrule packet-length-bits (and "0" bit bit bit bit bit bit bit bit bit bit bit bit bit bit bit) (:lambda (input) (list :this-is 'packet-length-bits :value (parse-integer (text (subseq input 1)) :radix 2)))) (getf (parse 'packet-length-bits "0000000000011011") :this-is) (parse 'packet-length-bits "0000000000011011") (defrule packet-length-count (and "1" bit bit bit bit bit bit bit bit bit bit bit) (:lambda (input) (list :this-is 'packet-length-count :value (parse-integer (text (subseq input 1)) :radix 2)))) (parse 'packet-length-count "100000000011") (defrule packet-length (or packet-length-bits packet-length-count)) (defun parse-subpackets (text position end) "Introduce context sensitivity into parsing with custom rules. This function is called by the rule 'packet-operator and interfaces with Esrap (is a function terminal). In essence, it reads the number of subpackets / number of bits to read and reads them afterwards." (let ((return-pos nil) (success? nil)) (multiple-value-bind (length-indicator new-position) (parse 'packet-length text :start position :end end :junk-allowed T) (cond ((and (listp length-indicator) (eql (getf length-indicator :this-is) 'packet-length-bits)) (values (loop with current-pos = new-position while (and current-pos (< current-pos (+ new-position (getf length-indicator :value)))) collect (multiple-value-bind (result inner-pos inner-success?) (parse 'packet text :start current-pos :junk-allowed T) (setf current-pos inner-pos return-pos inner-pos success? inner-success?) result)) return-pos success?)) ((and (listp length-indicator) (eql (getf length-indicator :this-is) 'packet-length-count)) (values (loop with current-pos = new-position for i from 0 below (getf length-indicator :value) collect (when current-pos (multiple-value-bind (result inner-pos inner-success?) (parse 'packet text :start current-pos :junk-allowed T) (setf current-pos inner-pos return-pos inner-pos success? inner-success?) result))) return-pos success?)) (T (values nil new-position "Expected 'packet-length-bits or 'packet-length-count.")))))) (eval-when (:execute) (list (parse 'packet-operator (parse '16-hex "38006F45291200") :junk-allowed T) (parse 'packet-operator (parse '16-hex "EE00D40C823060") :junk-allowed T) (parse 'packet-operator (parse '16-hex "8A004A801A8002F478") :junk-allowed T) (parse 'packet-operator (parse '16-hex "620080001611562C8802118E34") :junk-allowed T) (parse 'packet-operator (parse '16-hex "C0015000016115A2E0802F182340") :junk-allowed T) (parse 'packet-operator (parse '16-hex "A0016C880162017C3686B18A3D4780") :junk-allowed T))) (defrule packet-operator (and (and bit bit bit) ;;Only "100" is specialized (which is why 'packet-literal must appear before 'packet-operator in the rule 'packet). (and bit bit bit) (function parse-subpackets)) (:lambda (input) (let ((version (elt input 0)) (type-id (elt input 1)) (subpackets (elt input 2))) (list :this-is 'packet-operator :version (parse-integer (text version) :radix 2) :type-id (parse-integer (text type-id) :radix 2) :subpackets subpackets)))) (defmethod input ((day (eql 16)) source) "Decoded transmission." (parse 'packet (parse '16-hex (read-file day source)) :junk-allowed T)) (input 16 T) (input 16 'full) ;;;; Solution (defun 16-part1score (decoded-transmission) "Sums all versions occuring in DECODED-TRANSMISSION." (if (eql 'packet-literal (getf decoded-transmission :this-is)) (getf decoded-transmission :version) ;;Grammar only allows for packet-operator otherwise. (+ (getf decoded-transmission :version) (loop for subpacket in (getf decoded-transmission :subpackets) sum (16-part1score subpacket))))) (eval-when (:execute) (list ;;16 (16-part1score (parse 'packet-operator (parse '16-hex "8A004A801A8002F478") :junk-allowed T)) ;;12 (16-part1score (parse 'packet-operator (parse '16-hex "620080001611562C8802118E34") :junk-allowed T)) ;;23 (16-part1score (parse 'packet-operator (parse '16-hex "C0015000016115A2E0802F182340") :junk-allowed T)) ;;31 (16-part1score (parse 'packet-operator (parse '16-hex "A0016C880162017C3686B18A3D4780") :junk-allowed T)))) (defmethod solution ((day (eql 16)) (variant (eql 'part1)) source) "The sum of the versions in all packets in the parsed input." (16-part1score (input day source))) (is 16 'part1 31) ;;; Solution for part2 ;;(defun code-of-eval-literal (packet type-id) ...) ;;(disassemble 'code-of-eval-literal) (defmethod evaluate-packet (packet (type-id (eql 4))) "The literal packet evaluates to itself." (values (apply #1=#.'#'eval (list (multiple-value-bind (value) (prog1 (read-from-string (format nil (formatter "'~1*~A") '(evaluate-packet packet 4) "value"))) (and (find-method #'print-object '() (mapcar (symbol-function 'find-class) (quote (T T)))) (first (mapcar (funcall (progn (constantly (lambda (and &key &allow-other-keys &aux (in (make-string-input-stream "&rest"))) (identity (setf and (or (cond ((null (not and)) (nth-value 0 and)) (and and nil T) (T (format in (subseq "" (1- (+ (* -1 type-id) (1+ type-id))) (or and (and 0)))))) (unwind-protect (block evaluate-packet (tagbody (go to-the-next-call-frame) and evaluate-packet when (locally (return-from evaluate-packet)) is-in the tagbody ;;Infinite recursion is considered harmful, deactivate it. unless going to-the-next-call-frame always evaluates (tagbody (go evaluate-packet)) again) (not nil)) (not and))))))))) (append (list (cdr (cons (rotatef value value) (let ((value (getf packet :value))) (coerce value (type-of value))))))))))))))) (evaluate-packet (parse 'packet-literal (parse '16-hex "D2FE28") :junk-allowed T) 4) (evaluate-packet (list :value nil) 4) (defun evaluate-each-subpacket-of (packet) "Returns a list of evaluated subpackets found in PACKET." (mapcar (lambda (x) (evaluate-packet x (getf x :type-id))) (getf packet :subpackets))) (defmethod evaluate-packet (packet (type-id (eql 0))) "Sums the subpackets." (reduce #'+ (evaluate-each-subpacket-of packet))) (evaluate-packet (parse 'packet-operator (parse '16-hex "C200B40A82") :junk-allowed T) 0) (defmethod evaluate-packet (packet (type-id (eql 1))) "Computes the product of the subpackets." (reduce #'* (evaluate-each-subpacket-of packet))) (evaluate-packet (parse 'packet-operator (parse '16-hex "04005AC33890") :junk-allowed T) 1) (defmethod evaluate-packet (packet (type-id (eql 2))) "Selects the minimal value out of the subpackets." (apply #'min (evaluate-each-subpacket-of packet))) (evaluate-packet (parse 'packet-operator (parse '16-hex "880086C3E88112") :junk-allowed T) 2) (defmethod evaluate-packet (packet (type-id (eql 3))) "Selects the maximal value out of the subpackets." (apply #'max (evaluate-each-subpacket-of packet))) (evaluate-packet (parse 'packet-operator (parse '16-hex "CE00C43D881120") :junk-allowed T) 3) (defmethod evaluate-packet (packet (type-id (eql 5))) "1 if the first subpacket is greater than the second subpacket, 0 otherwise." (let ((evaluated (evaluate-each-subpacket-of packet))) (if (< (second evaluated) (first evaluated)) 1 0))) (evaluate-packet (parse 'packet-operator (parse '16-hex "D8005AC2A8F0") :junk-allowed T) 5) (defmethod evaluate-packet (packet (type-id (eql 6))) "1 if the first subpacket is less than the second subpacket, 0 otherwise." (let ((evaluated (evaluate-each-subpacket-of packet))) (if (< (first evaluated) (second evaluated)) 1 0))) (evaluate-packet (parse 'packet-operator (parse '16-hex "F600BC2D8F") :junk-allowed T) 6) (defmethod evaluate-packet (packet (type-id (eql 7))) "1 if the first and the second subpackets are #'= , 0 otherwise." (let ((evaluated (evaluate-each-subpacket-of packet))) (if (= (first evaluated) (second evaluated)) 1 0))) (evaluate-packet (parse 'packet-operator (parse '16-hex "9C005AC2F8F0") :junk-allowed T) 7) ;;1 (let ((packet (parse 'packet-operator (parse '16-hex "9C0141080250320F1802104A08") :junk-allowed T))) (evaluate-packet packet (getf packet :type-id))) (defmethod solution ((day (eql 16)) (variant (eql 'part2)) source) "Evaluates the input packet." (let ((input (input day source))) (evaluate-packet input (getf input :type-id)))) (is 16 'part2 54)
12,714
Common Lisp
.lisp
227
45.629956
251
0.61995
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
040ed0f7b409450c7eedd28b7c8151e5e8ee837563d39cd3445a493951ccb006
41,837
[ -1 ]
41,838
07.lisp
b-steger_adventofcode2021/src/07.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defmethod input ((day (eql 7)) source) "Horizontal positions of crab submarines." ;;Reusing format parsed by rule '06-file. (parse '06-file (read-file day source))) (input 7 T) (input 7 'full) ;;;; Solution ;;Problem space is small (1878). (loop for x in (input 7 'full) maximize x) (defun 07-cost-part1 (source target) "The distance between SOURCE and TARGET." (abs (- source target))) (mapcar (lambda (x) (07-cost-part1 x 2)) (input 7 T)) (defun 07-cost (input position &key (cost-function #'07-cost-part1)) "The sum of costs each number has in relation to POSITION." (reduce #'+ (mapcar (lambda (x) (funcall cost-function x position)) input))) ;;=> (37 41 39 71) (list (07-cost (input 7 T) 2) (07-cost (input 7 T) 1) (07-cost (input 7 T) 3) (07-cost (input 7 T) 10)) (defun cheapest-fuel (input positions cost-function) "Simple case: calculate the cost to reach position with COST-FUNCTION. Recursive case: smaller of simple case on the first position on a list - pitted against - the recursive call on the rest of the list." (if (cdr positions) (min (cheapest-fuel input (list (car positions)) cost-function) (cheapest-fuel input (rest positions) cost-function)) (07-cost input (car positions) :cost-function cost-function))) (defun 07-solution (day source cost-function) "Wrapper around #'cheapest-fuel." (cheapest-fuel (input day source) (loop for x below (loop for x in (input day source) maximize x) collect x) cost-function)) ;;=> 37 (07-solution 7 T #'07-cost-part1) (defun 07-cost-part2 (source target) "The area of the triangle determined by (0 0)--(diff+1 0)--(diff+1 diff)." (let ((diff (07-cost-part1 source target))) (/ (* (1+ diff) diff) 2))) ;;=> (168 206) (list (07-cost (input 7 T) 5 :cost-function #'07-cost-part2) (07-cost (input 7 T) 2 :cost-function #'07-cost-part2)) (defmethod solution ((day (eql 7)) (variant (eql 'part1)) source) "The least amount of fuel the linear cost crab submarines have to spend in order to align." (07-solution day source #'07-cost-part1)) (is 7 'part1 37) (defmethod solution ((day (eql 7)) (variant (eql 'part2)) source) "The least amount of fuel the increasing cost crab submarines have to spend in order to align." (07-solution day source #'07-cost-part2)) (is 7 'part2 168)
3,274
Common Lisp
.lisp
66
44.969697
251
0.683782
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
299374546491115a84d2201dacabd98c4b5f3c2f4035fc3b5ae80506cc9d5a9c
41,838
[ -1 ]
41,839
15.lisp
b-steger_adventofcode2021/src/15.lisp
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :adventofcode2021) ;;;; Parser (defmethod input ((day (eql 15)) source) "Multidimensional array representing a weighted graph with cost edges [0..9]. Easting/northing coordinate system from day 9 / day 11 is used." (let* ((nested-lists (parse '09-file (read-file day source))) (height (length nested-lists)) (width (length (first nested-lists)))) (make-array (list height width) :initial-contents nested-lists))) (input 15 T) (input 15 'full) (defun input-15-part2 (input) "Input map, but repeated 5 times along each axis. Value is increased by floor(corrected-northing/height) + floor(easting/width) (wrapped by %9)." (let* ((ori-width (array-dimension input 1)) (ori-height (array-dimension input 0)) (part2-map (make-array (list (* 5 ori-height) (* 5 ori-width))))) (loop for northing from 0 below (array-dimension part2-map 1) do (loop for easting from 0 below (array-dimension part2-map 0) do (setf (aref part2-map northing easting) ;;1+: for the modulo calculation. (1+ (rem (+ (aref input (mod northing ori-height) (mod easting ori-width)) ;;4: zero-indexed maximal position in a tile. ;;#'- :northing axis is reversed. (- 4 (floor northing ori-height)) (floor easting ori-width) ;;-1: for the modulo calculation. -1) 9))))) part2-map)) ;;;; Solution #| Shortest path with cost surface "risk" instead of "length" (a naming issue). → Adapting Dijkstra's algorithm from "Goodrich M. T., Tamassia R., Mount D. Data Structures & Algorithms in C++. John Wiley & Sons Inc., 2nd ed., 2011.", p. 639ff. (ALL simplifying assumptions are equivalent.) I guess the intention of the part2 task is the optimization path from priority queues on unordered lists (p. 331) → queues on ordered lists (p. 332) → queues implemented with heaps (binary trees, p. 344) → Relaxed/Fibonacci heaps (p. 663) → pairing-min-heap (L. Fredman, R. Sedgewick, D. Sleator and R. Tarjan 'The Pairing Heap: A New Form of Self-Adjusting Heap', Algorithmica (1986) 1: 111--129.). Quicklisp package minheap happens to implement the last mentioned. THINK: shortest path quadtree (Foundations of Multidimensional and Metric Data Structures. 2006, section 4.1.6 Nearest Neighbours in a Spatial Network, p. 508)? |# ;;Puzzle 25 calls #'neighbour-lut. (defun wrapping-move (map start by-vector) "Returns the new coordinates (as an rmindex) after adding BY-VECTOR to an rmindexed START. If the shift crosses the borders of the MAP, it will just wrap around, as if the MAP is tiled on an infinite plane." (let* ((width (array-dimension map 1)) (height (array-dimension map 0)) (new-easting (+ width (easting map start) (car by-vector))) (new-northing (+ height (northing map start) (cdr by-vector)))) (en2rmindex map (rem new-easting width) (rem new-northing height)))) ;;Target: (3 1). (let* ((input (input 15 T)) (index (wrapping-move (input 15 T) (en2rmindex (input 15 T) 2 3) (cons (+ (* 10 2) 1) (+ (* 9 4) 2))))) (list (easting input index) (northing input index))) (defun neighbour-lut (map &key (lut *4direction-vectors*) positional-neighbours? wrapping-is-allowed?) "The neighbouring row-major indices for each rmindex in a two-dimensional MAP. Candidates for the directions are *4direction-vectors* (the four direct neighbours) and *8direction-vectors* (all 8 neighbours surrounding an index). Does not remove nil from the neighbour list when POSITIONAL-NEIGHBOURS?. Simulates an infinite map which is repeated in all directions if WRAPPING-IS-ALLOWED?. POSITIONAL-NEIGHBOURS? won't have any influence anymore in such a case. LUT means lookup-table." (let ((width (array-dimension map 1)) (height (array-dimension map 0))) (make-array (array-dimensions map) :initial-contents (loop for northing from 0 below height collect (loop for easting from 0 below width collect (let ((neighbours (loop for (dir . (vector)) in lut collect (funcall (if wrapping-is-allowed? #'wrapping-move #'clip-move) map (array-row-major-index map northing easting) (by-vector dir lut))))) (if positional-neighbours? neighbours (remove nil neighbours)))))))) (neighbour-lut (input 15 T)) #+debug (defmethod print-object ((obj pairing-heap::node) stream) (format stream "Preventing control stack exhaustion.")) (defun shortest-path (graph vertex-rmindex target-vertex-rmindex) "Dijkstra's algorithm on a weighted GRAPH. Return the sum of weights of the shortest path from VERTEX-RMINDEX (excluded) to TARGET-VERTEX-RMINDEX (included)." (let* ((width (array-dimension graph 1)) (height (array-dimension graph 0)) ;;d-label: array storing labels for a vertex - the length of a shortest path from VERTEX-RMINDEX to the respective entry. (d-label (make-array (array-dimensions graph) ;;∞ in (unoptimized) CL??? → An impossible result cost, which is more than the longest path (repeated Zs) with more than a vertex can contribute. :initial-element (* 10 width height))) (queue (make-instance 'pairing-heap:pairing-heap)) (neighbour-lut (neighbour-lut graph))) ;;Set the start by being the next cheapest node (book calls this "bootstrapping trick"). (setf (row-major-aref d-label vertex-rmindex) 0) ;;Initialize the queue. ;;The queue's priority is the edge weight, the queue's returned value is the rmindex. (let* ((nodes (make-array (list (array-total-size graph)) :initial-contents (loop for i from 0 below (array-total-size graph) collect (pairing-heap:insert queue (row-major-aref d-label i) i)))) ;;Avoids circular paths. (visited (make-array (list (array-total-size graph)) :initial-element nil))) (loop with u = nil while (not (pairing-heap:empty-p queue)) do (setf u (pairing-heap:extract-min queue) (aref visited u) T) do (loop for z in (row-major-aref neighbour-lut u) unless (aref visited z) ;;Edge relaxation. do (let ((new-estimate (+ (row-major-aref d-label u) (row-major-aref graph z)))) (when (< new-estimate (row-major-aref d-label z)) (setf (row-major-aref d-label z) new-estimate) ;;UPDATE graph SET label=new_estimate WHERE label=z; for indexed column graph(label). (pairing-heap:decrease-key queue (aref nodes z) new-estimate))))) (row-major-aref d-label target-vertex-rmindex)))) (defun solution-15 (source part2?) "The shortest path cost for the part1/part2 map." (let ((input (if part2? (input-15-part2 (input 15 source)) (input 15 source)))) (shortest-path input ;;The row-major-index (rmindex) of the top left vertex (the start). (array-row-major-index input (1- (array-dimension input 0)) 0) ;;The row-major-index (rmindex) of the bottom right vertex (the end). (array-row-major-index input 0 (1- (array-dimension input 1)))))) (defmethod solution ((day (eql 15)) (variant (eql 'part1)) source) "Shortest path cost with cost surface \"risk\" (unmodified map)." (solution-15 source nil)) (is 15 'part1 40) (defmethod solution ((day (eql 15)) (variant (eql 'part2)) source) "Shortest path cost with cost surface \"risk\" (enlarged map)." (solution-15 source T)) (is 15 'part2 315)
9,201
Common Lisp
.lisp
151
49.430464
466
0.623639
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
c95fdbe2c63913285b215dc1788baa15aedbe42b1cf5b9366ee0a2a4de82feed
41,839
[ -1 ]
41,840
adventofcode2021.asd
b-steger_adventofcode2021/adventofcode2021.asd
;;;; Advent of code 2021 solutions ;;;; Copyright (C) 2022 Benedikt Steger <[email protected]> ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (in-package :cl-user) (defpackage adventofcode2021-asd (:use :cl-user :asdf)) (in-package :adventofcode2021-asd) (defsystem adventofcode2021 :description "Advent of code 2021 solutions" :author "Benedikt Steger" :license "AGPLv3+" :version "25" :serial T :depends-on (:asdf :uiop :esrap :cl-fad :minheap :screamer) :components ((:module "src" :serial T :components ((:file "package") (:file "common") (:file "01") (:file "02") (:file "03") (:file "04") (:file "05") (:file "06") (:file "07") (:file "08") (:file "09") (:file "10") (:file "11") (:file "12") (:file "13") (:file "14") (:file "15") (:file "16") (:file "18") (:file "19") (:file "19-detour") (:file "20") (:file "21") (:file "22") (:file "23") (:file "24") (:file "25") (:file "report")))))
2,352
Common Lisp
.asd
49
29.877551
251
0.450827
b-steger/adventofcode2021
0
0
0
AGPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
a083aff65e571c4da3d1a1c798b5f862ad6981dc1dcdbbb440b609acdb166b0b
41,840
[ -1 ]
41,884
main.lisp
lemondevxyz_cl-scgi/main.lisp
(defpackage :cl-scgi (:use :cl :cl-user)) (in-package :cl-scgi) ;; (ql:quickload '(:babel :str) :silent t) (defun list-of-p (τ thing) "list-of-p is a predicate that checks if a list is of that specific type." (and (listp thing) (every (lambda (x) (typep x τ)) thing))) (deftype list-of (type) "list-of is a type that specifies a list of that exact *type*" (let ((predicate (gensym))) (setf (symbol-function predicate) #'(lambda (seq) (list-of-p type seq))) `(and list (satisfies ,predicate)))) (deftype positive-fixnum () "positive-fixnum names all integers from 1 to *mostpositive-fixnum*" `(integer 1 ,most-positive-fixnum)) (deftype ascii-number () "ascii-number is a number from 30 to 39" `(integer 30 39)) (defun list-to-vector (list) "list-to-vector is a function that converts a (unsigned-byte 8) list to a vector of that same type." (declare (type (list-of (unsigned-byte 8)) list)) (let ((vec (make-array 0 :element-type '(unsigned-byte 8) :initial-element 0 :fill-pointer 0))) (declare (type (vector (unsigned-byte 8) *) vec)) (loop for x in list do (vector-push-extend x vec)) vec)) (defun vector-to-list (vec) "vector-to-list is a function that converts a vector of type (unsigned-byte 8) to a list of that same type" (let ((list nil)) (loop for x from 0 below (length vec) do (setf list (append list (list (elt vec x))))) list)) (defun number-to-ascii-bytes (num) "number-to-ascii-bytes converts a number to ascii bytes that are used for net code. Example: (number-to-ascii-bytes 123456789) ;; => (31 32 33 34 35 36 37 38 39)" (declare (positive-fixnum num)) (let ((arr (list-to-vector '())) (strnum (format nil "~a" num))) (declare (type (vector (unsigned-byte 8) *) arr)) (declare (string strnum)) (loop for index from 0 below (length strnum) do (let* ((digit (elt strnum index)) (ascii (+ (digit-char-p digit) 30))) (declare (character digit)) (declare (ascii-number ascii)) (vector-push-extend ascii arr))) arr)) (defun ascii-bytes-to-number (bytes) "ascii-bytes-to-number converts an array of bytes to a number that's used for net code. Example: (ascii-bytes-to-number '(31 32 33 34 35 36 37 38 39)) ;; => 123456789" (declare (type (vector (unsigned-byte 8) *) bytes)) (let* ((len (length bytes)) (num 0)) (loop for index from 0 below len do (let ((byte (elt bytes index))) (unless (and (>= byte 30) (<= byte 39)) (error "byte must be between 30 and 39")) (let* ((int (- byte 30)) (place (1- (- len index)))) (setf num (+ (* (expt 10 place) int) num))))) num)) (export 'ascii-bytes-to-number) (export 'number-to-ascii-bytes) (defun != (a b) "!= is the inverse of =" (not (= a b))) (defun parse-header (str) "parse-header parses a scgi header. scgi headers are marked by their NUL character after both the key and the value. Example: \"\"CONTENT_LENGTH\" <00> \"27\" <00> \" Note: <00> is the NUL character" (declare (string str)) (let ((spl (str:split (format nil "~a" #\Nul) str))) (unless (= (length spl) 3) (error "bad split length, must be 3")) (values (elt spl 0) (elt spl 1)))) (export 'parse-header) (defun list-to-header (list) "list-to-header creates client-like(web-server) headers through a list. the list must be a list of strings and of even length" (declare (type (list-of string) list)) (unless (evenp (length list)) (error "list must be even")) (let ((str "")) (loop for x from 0 below (length list) by 2 do (setf str (format nil "~a~a~a~a~a" str (elt list x) #\Nul (elt list (1+ x)) #\Nul))) str)) (defun parse-headers (str) "parse-headers is a function that parses all headers from a scgi request. parse-headers returns a hash map because it is more performant than an associated list. Example: \"\"CONTENT_LENGTH\" <00> \"27\" <00> \"SCGI\" <00> \"1\" <00>\" Note: <00> is the NUL character" (declare (string str)) (let ((split (str:split (format nil "~a" #\Nul) str))) (unless (or (zerop (length split)) (oddp (length split))) (error "bad formatting; string must have an extra NUL character")) (let ((hash (make-hash-table :test #'equal) )) (loop for index from 0 below (length split) by 2 do (when (< (1+ index) (length split)) (setf (gethash (elt split index) hash) (elt split (1+ index))))) hash))) (export 'parse-headers) (defun parse-binary-header (binary) "parse-binary-header is a function that parses headers represented in vector of octets" (declare (type (vector (unsigned-byte 8) *) binary)) (parse-headers (babel:octets-to-string binary))) (defun parse-request (request) "parse-request is a function that parses a normal SCGI request. SCGI requests are composed of 4 parts: 1. the header length + seperator(:) 2. the header content 3. the body seperator 4. the body content parse-request is lenient in its design; several checks are not made and are left for the developer. For example, the header \"CONTENT_LENGTH\" doesn't *have to* match the size of the body. Furthermore, parse-request doesn't make any effort to parse the headers, instead it restricts itself to only seperating the body and header from the rest of the request, giving the developer complete freedom over how to deal with the request. parse-request throws an error in one of these cases: 1. the header length is bigger than the request itself 2. the request is malformed in the case of a comma not being present after the last header" (declare (type (vector (unsigned-byte 8) *) request)) (let* ((found nil) (len-bytes (list-to-vector '())) (len-header 0) (header-start -1) (header-end -1) (headers "")) (declare (type (or t nil) found)) (declare (type (vector (unsigned-byte 8) *) len-bytes)) (let ((index 0)) (loop while (not found) do (when (= (elt request index) #x3a) (setf found t)) (unless found (vector-push-extend (elt request index) len-bytes) (setf index (1+ index)))) (setf len-header (ascii-bytes-to-number len-bytes)) (setf header-start (+ index 1)) (setf header-end (+ header-start len-header))) (when (> header-end (length request)) (error "malformed request; header length is bigger than request itself")) (setf headers (subseq request header-start header-end)) (unless (= (elt request header-end) #x2c) (error "malformed request; bytes after headers must be #x2c")) (let ((end (+ header-end 1))) (when (>= end (length request)) (setf end (1- (length request)))) (values headers (subseq request end (- (length request) 1)))))) (export 'parse-request) (defun parse-request-with-headers (request) "parse-request-with-headers is a wrapper around parse-headers that parses the headers and returns them in a hash table Note: this function, by itself, could throw an error if a utf-8 character is invalid. To further debug this issue, see babel:octets-to-string" (declare (type (vector (unsigned-byte 8) *) request)) (multiple-value-bind (headers body) (parse-request request) (values (parse-headers (babel:octets-to-string headers)) body))) (export 'parse-request-with-headers) (defun parse-request-as-string (request) "parse-request-as-string is a wrapper around parse-request-with-headers with one key difference: the body is returned as a string. Note: this function, by itself, could throw an error if a utf-8 character is invalid. To further debug this issue, see babel:octets-to-string" (declare (type (vector (unsigned-byte 8) *) request)) (multiple-value-bind (headers body) (parse-request-with-headers request) (values headers (babel:octets-to-string body)))) (export 'parse-request-as-string)
7,987
Common Lisp
.lisp
181
39.530387
97
0.66941
lemondevxyz/cl-scgi
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
9d97e95e21657bfd5741c2f7ddfd005646ec2ca96f8d2cca361060c19f22a536
41,884
[ -1 ]
41,885
server.lisp
lemondevxyz_cl-scgi/src/server.lisp
(in-package :cl-scgi) (ql:quickload '(:alexandria) :silent t) ;; `server.lisp' is basically a file that's shared between ;; `unix.lisp' and `tcp.lisp'. (deftype request-callback-type () `(function ((vector (unsigned-byte 8)) integer stream))) (defun write-bytes (seq stream) "write-bytes is a function that writes sequences to a stream that only supports write-byte." (declare (type (vector (unsigned-byte 8)) seq)) (declare (type stream stream)) (loop for x from 0 below (length seq) do (write-byte (elt seq x) stream))) (export 'write-bytes) (declaim (type (or request-callback-type null) *continue-callback*)) (defvar *continue-callback* nil "*continue-callback* is a custom function that can be set by outside packages. *continue-callback* is executed whenever a request gets derailed and the user chooses CONTINUE-AND-WRITE.") (defun prompt-new-value (prompt) "prompt-new-value is a function that prompts Common Lisp's console for a value to be inputted by the user." (format *query-io* prompt) (force-output *query-io*) (eval (read *query-io*))) (defun read-until-eof (stream) "DEPRECATED read-until-eof reads a stream until it reaches EOF and then returns a vector of all bytes it read." (declare (stream stream)) (let ((read-input (make-array 0 :element-type '(unsigned-byte 8) :initial-element 0 :fill-pointer 0)) (byte nil)) (declare (type (vector (unsigned-byte 8) *) read-input)) (declare (type (or integer null (eql :eof)) byte)) (loop while (not (equal byte :eof)) do (setf byte (read-byte stream nil :eof)) (unless (equal byte :eof) (vector-push-extend byte read-input))) read-input)) (export 'read-until-eof) (defvar *continue* nil "*continue* is an usused global variable. it is mainly defined to allow `parse-request-or-restart' to stop unix-server or tcp-server from receiving requests.") (defun parse-request-or-restart (stream fn) "parse-request-or-restart is a function that wraps around parse-request. basically, it provides four useful restart functions. 1. STOP: stops the server from listening anymore and closes the client's connection 2. CONTINUE-AND-CLOSE: continues listening but closes the client's connection 3. CONTINUE-AND-EXEC-CALLBACK: continues listening and evaluates *continue-callback* for the client's connection 4. CONTINUE-AND-EVAL: continues listening and evaluates a custom response for the client's request. Do note that this callback will only take in a writable stream without a body or header" (declare (stream stream)) (declare (request-callback-type fn)) ;; because, for some reason (close stream) ;; doesn't update right away, so you have to ;; use another variable to close the stream (let ((closed nil)) (unwind-protect (restart-case (multiple-value-bind (headers content-length) (parse-request-from-stream stream) (funcall fn headers content-length stream)) (stop () :report "Stop accepting connections" (setf *continue* nil) (when (open-stream-p stream) (close stream) (setf closed t))) (continue-and-close () :report "Continue and close this request" (setf *continue* t) (when (open-stream-p stream) (close stream) (setf closed t))) (continue-and-exec-callback () :report "Continue and execute *continue-callback*" :test (lambda () (not (null *continue-callback*))) (funcall *continue-callback* stream)) (continue-and-eval () :report "Continue and eval an expression" :interactive (lambda () (prompt-new-value (format nil "Enter an S-Expression~%"))))) (when (and (open-stream-p stream) (null closed)) (finish-output stream) (close stream))))) (defun format-headers (headers) "format-headers is a function that turns a hash-table into a SCGI-compatible header response." (declare (hash-table headers)) (let ((keys (alexandria:hash-table-keys headers)) (headers-str "") (bytes (make-array 1 :fill-pointer 0 :element-type '(unsigned-byte 8)))) (loop for key in keys do (setf headers-str (format nil "~a~a: ~a~a~a" headers-str key (gethash key headers) #\return #\newline))) (when (> (length headers-str) 0) (let ((octets (babel:string-to-octets headers-str))) (loop for x from 0 below (length octets) do (vector-push-extend (elt octets x) bytes)))) (vector-push-extend (char-code #\Return) bytes) (vector-push-extend (char-code #\Newline) bytes) bytes)) (export 'format-headers) (defun response-string (headers body stream) "response-string is a function that sends a string body with a hash-table of headers." (declare (stream stream)) (declare (hash-table headers)) (declare (string body)) (let ((oldVal (gethash "Content-Length" headers))) (unwind-protect (let () (setf (gethash "Content-Length" headers) (length body)) (write-bytes (format-headers headers) stream) (write-bytes (babel:string-to-octets body) stream))) (setf (gethash "Content-Length" headers) oldVal))) (export 'response-string)
5,465
Common Lisp
.lisp
121
38.289256
98
0.662791
lemondevxyz/cl-scgi
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
72c0c634313b75b057c815cab8ef9a81cf3b261237ab9262d445c65ca3dd5539
41,885
[ -1 ]
41,886
main.lisp
lemondevxyz_cl-scgi/src/main.lisp
(defpackage :cl-scgi (:use :cl :cl-user)) (in-package :cl-scgi) (ql:quickload '(:fast-io :flexi-streams :babel :str :alexandria) :silent t) (defun list-of-p (τ thing) "list-of-p is a predicate that checks if a list is of that specific type." (and (listp thing) (every (lambda (x) (typep x τ)) thing))) (deftype list-of (type) "list-of is a type that specifies a list of that exact *type*" (let ((predicate (gensym))) (setf (symbol-function predicate) #'(lambda (seq) (list-of-p type seq))) `(and list (satisfies ,predicate)))) (deftype positive-fixnum () "positive-fixnum names all integers from 1 to *mostpositive-fixnum*" `(integer 1 ,most-positive-fixnum)) (defun list-to-vector (list) "list-to-vector is a function that converts a (unsigned-byte 8) list to a vector of that same type." (declare (type (list-of (unsigned-byte 8)) list)) (let ((vec (make-array 0 :element-type '(unsigned-byte 8) :initial-element 0 :fill-pointer 0))) (declare (type (vector (unsigned-byte 8) *) vec)) (loop for x in list do (vector-push-extend x vec)) vec)) (defun vector-to-list (vec) "vector-to-list is a function that converts a vector of type (unsigned-byte 8) to a list of that same type" (let ((list nil)) (loop for x from 0 below (length vec) do (setf list (append list (list (elt vec x))))) list)) ;; (defun extract-header (str) ;; "DEPRECATED extract-header is a function that extracts a header key or value string ;; and simultaneously checks if it's valid or not. ;; ;; Example: (extract-header \"\"CONTENT_LENGTH\"\") ; \"CONTENT_LENGTH\" " ;; (unless (and (two-quotes-p str) (wrapped-in-quotes-p str)) ;; (error (format nil "header ~a must be wrapped in quotes" str))) ;; (let ((ret (str:replace-all "\"" "" str))) ;; (unless (> (length ret) 0) ;; (error "header cannot be empty")) ;; ret)) ;; (export 'extract-header) (defun parse-headers (str) "parse-headers is a function that parses all headers from a scgi request. parse-headers returns a hash map because it is more performant than an associated list. Example: \"\"CONTENT_LENGTH\" <00> \"27\" <00> \"SCGI\" <00> \"1\" <00>\" Note: <00> is the NUL character" (declare (string str)) (let ((split (str:split (format nil "~a" #\Nul) str))) (unless (or (zerop (length split)) (oddp (length split))) (error "bad formatting; string must have an extra NUL character")) (let ((hash (make-hash-table :test #'equal) )) (loop for index from 0 below (length split) by 2 do (when (< (1+ index) (length split)) (setf (gethash (elt split index) hash) (elt split (1+ index))))) hash))) (export 'parse-headers) (defun parse-header (str) "DEPRECATED parse-header parses a scgi header. scgi headers are marked by their NUL character after both the key and the value. Example: \"\\\"CONTENT_LENGTH\\\"<00>\\\"27\\\"<00>\" Note: <00> is the NUL character parse-header will throw an error if the key or value weren't wrapped in quotes." (let* ((ret (parse-headers str)) (key (ignore-errors (elt (alexandria:hash-table-keys ret) 0)))) (if key (values key (gethash key ret)) nil))) (export 'parse-header) (defun list-to-header (list) "list-to-header creates client-like(web-server) headers through a list. the list must be a list of strings and of even length" (declare (type (list-of string) list)) (unless (evenp (length list)) (error "list must be even")) (let ((str "")) (loop for x from 0 below (length list) by 2 do (setf str (format nil "~a~a~a~a~a" str (elt list x) #\Nul (elt list (1+ x)) #\Nul))) str)) (defun parse-binary-header (binary) "parse-binary-header is a function that parses headers represented in vector of octets" (declare (type (vector (unsigned-byte 8) *) binary)) (parse-headers (babel:octets-to-string binary))) (export 'parse-binary-header) (defun parse-request-from-stream (stream) "parse-request-from-stream is a function that parses a normal SCGI request from a stream. SCGI requests are composed of 4 parts: 1. the header length + seperator(:) 2. the header content 3. the body seperator (,) 4. the body content parse-request-from-stream is quite strict in its design; several checks are made and aren't left for the developer. For example, the header \"CONTENT_LENGTH\" *must* match the size of the body. Otherwise, extra content ends being unused but no error is thrown. Furthermore, parse-request doesn't make any effort to parse the headers, instead it restricts itself to only seperating the body and header from the rest of the request, giving the developer complete freedom over how to deal with the request. parse-request throws an error in one of these cases: 1. comma isn't present in the packets.. 2. the header length is bigger than the request itself 3. the request is malformed in the case of a comma not being present after the last header 4. the given header length is bigger than the actual header length" (declare (stream stream)) (let* ((header-len-str (make-array 0 :fill-pointer 0 :adjustable t :element-type 'character)) (header-len 0) (content-len-str (make-array 0 :fill-pointer 0 :adjustable t :element-type 'character)) (content-len 0) (header-buf (fast-io:make-octet-vector 0))) (declare (number header-len content-len)) (declare (type (vector character *) header-len-str content-len-str)) (fast-io:with-fast-input (buffer nil stream) (loop for byte = (fast-io:fast-read-byte buffer) until (eq byte #x3a) do (vector-push-extend (code-char byte) header-len-str)) (setf header-len (parse-integer header-len-str)) (setf header-buf (fast-io:make-octet-vector header-len)) (fast-io:fast-read-sequence header-buf buffer 0 header-len) (unless (equal (fast-io:fast-read-byte buffer) #x2c) (error "malformed request; comma must be after headers")) (loop for x from 15 below (length header-buf) until (= content-len -1) do (let ((byte (elt header-buf x))) (if (= byte 0) (setf content-len -1) (vector-push-extend (code-char byte) content-len-str)))) (setf content-len (or (ignore-errors (parse-integer content-len-str)) 0))) (values header-buf content-len))) (export 'parse-request-from-stream) (deftype positive-fixnum () `(integer 0 ,most-positive-fixnum)) (defun read-until-content-length (content-len stream) "read-until-content-length reads from the stream until it reaches content-len" (declare (positive-fixnum content-len)) (declare (stream stream)) (let ((vec (make-array 1 :element-type '(unsigned-byte 8) :fill-pointer 0))) (declare (type (vector (unsigned-byte 8) *) vec)) (loop for x from 0 below content-len do (vector-push-extend (read-byte stream) vec)) vec)) (export 'read-until-content-length) (defun parse-request (request) "DEPRECATED parse-request is a function that wraps around parse-request-from-stream to make it easier to test out parsing requests and also to satsify old users of the library. It takes in a vector of unsigned bytes of size 8 (octet) and returns two vectors of octets in multi-value fashion those values are the header and the body. Do note that these aren't parsed and can be parsed with helper functions like `(parse-header (babel:octets-to-string headers))' and `(babel:octets-to-string body)'" (declare (type (vector (unsigned-byte 8) *) request)) (let ((stream (flexi-streams:make-in-memory-input-stream request))) (multiple-value-bind (headers content-len) (parse-request-from-stream stream) (values headers (read-until-content-length content-len stream))))) (export 'parse-request) (defun parse-request-with-headers (request) "DEPRECATED parse-request-with-headers is a wrapper around parse-headers that parses the headers and returns them in a hash table Note: this function, by itself, could throw an error if a utf-8 character is invalid. To further debug this issue, see babel:octets-to-string" (declare (type (vector (unsigned-byte 8) *) request)) (multiple-value-bind (headers body) (parse-request request) (values (parse-headers (babel:octets-to-string headers)) body))) (export 'parse-request-with-headers) (defun parse-request-as-string (request) "DEPRECATED parse-request-as-string is a wrapper around parse-request-with-headers with one key difference: the body is returned as a string. Note: this function, by itself, could throw an error if a utf-8 character is invalid. To further debug this issue, see babel:octets-to-string" (declare (type (vector (unsigned-byte 8) *) request)) (multiple-value-bind (headers body) (parse-request-with-headers request) (values headers (babel:octets-to-string body)))) (export 'parse-request-as-string)
9,116
Common Lisp
.lisp
191
43
97
0.689748
lemondevxyz/cl-scgi
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
19898bc661ea470c3570a91e97df154038af18a6aeaa0711da2d3a533cc9dcc4
41,886
[ -1 ]
41,887
unix.lisp
lemondevxyz_cl-scgi/src/unix.lisp
(ql:quickload '(:bordeaux-threads :unix-sockets) :silent t) (in-package :cl-scgi) ;; requires server.lisp to work (defun unix-server (path fn &key ((:multi-threaded mt) t) ((:backlog bl) 128)) "unix-server is a function that creates a unix socket, accepts connections, parses the request(error-prone) and finally calls fn to handle the request." (declare (string path)) (declare (request-callback-type fn)) (declare (type (or t nil) mt)) (when (probe-file path) (delete-file path)) (unix-sockets:with-unix-socket (sock (unix-sockets:make-unix-socket path :backlog bl)) (unwind-protect (let* ((*continue* t)) (loop while *continue* do (let* ((conn (unix-sockets:accept-unix-socket sock)) (stream (unix-sockets:unix-socket-stream conn))) (if mt (bt:make-thread (lambda () (parse-request-or-restart stream fn) (unix-sockets:close-unix-socket sock))) (progn (parse-request-or-restart stream fn)))))) (when (probe-file path) (delete-file path)))) (when (probe-file path) (delete-file path))) (export 'unix-server)
1,262
Common Lisp
.lisp
28
35.035714
77
0.593344
lemondevxyz/cl-scgi
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
86d0f8085a9ecbd13ab820138f7e21ff4469991f6e45e3d0d5d72670edb5f4d0
41,887
[ -1 ]
41,888
tcp.lisp
lemondevxyz_cl-scgi/src/tcp.lisp
(in-package :cl-scgi) (ql:quickload '(:usocket :bordeaux-threads) :silent t) ;; requires server.lisp to work (defun tcp-server (host port fn &key ((:reuse-address ra) t) ((:multi-threaded mt) t) ((:backlog bl) 128)) "tcp-server is a function that listens on a tcp socket, accepts connections, parses the request(error-prone) and finally calls fn to handle the request." (declare (string host)) (declare (type (integer 1 65535) port)) (declare (request-callback-type fn)) (declare (type (or t null) ra mt)) (let* ((sock nil)) (declare (type (or null usocket:stream-server-usocket) sock)) (unwind-protect (let ((*continue* t) (conn nil) (stream nil)) (declare (type (or null usocket:stream-usocket) conn)) (declare (type (or null stream) stream)) (setf sock (usocket:socket-listen host port :reuse-address ra :element-type '(unsigned-byte 8) :backlog bl)) (loop while *continue* do (setf conn (usocket:socket-accept sock :element-type '(unsigned-byte 8))) (setf stream (usocket:socket-stream conn)) (if mt (bordeaux-threads:make-thread (lambda () (parse-request-or-restart stream fn))) (parse-request-or-restart stream fn)))) (usocket:socket-close sock))))
1,479
Common Lisp
.lisp
31
36.258065
119
0.57953
lemondevxyz/cl-scgi
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
b0fc15388805984b1cc9e8b7c27646cc64db11465c465de1b140c60683b8d384
41,888
[ -1 ]
41,889
main.lisp
lemondevxyz_cl-scgi/t/main.lisp
(ql:quickload '(:fiveam flexi-streams :fast-io) :silent t) (in-package :fiveam) (defun list-to-header-string (lst) (declare (list lst)) (let ((str "")) (declare (string str)) (loop for x from 0 below (length lst) by 2 do (setf str (format nil "~a~a~a~a~a" str (elt lst x) #\Nul (elt lst (1+ x)) #\Nul))) str)) (def-suite* header-suite) (in-suite header-suite) (test parse-header ;; DEPRECATED ;; parse proper header (is (equal (multiple-value-list (cl-scgi:parse-header (list-to-header-string '("CONTENT_LENGTH" "40")))) '("CONTENT_LENGTH" "40"))) ;; empty header is still valid (finishes (cl-scgi:parse-header "")) (signals simple-error (cl-scgi:parse-header (format nil "\"~a\"~a\"~a\"" "CONTENT_LENGTH" #\Nul "40")))) (test parse-headers (is (equal (alexandria:hash-table-plist (cl-scgi:parse-headers (list-to-header-string '("CONTENT_LENGTH" "40")))) '("CONTENT_LENGTH" "40"))) (finishes (cl-scgi:parse-headers ""))) (defun request-format (headers body) (declare (list headers)) (declare (string body)) (let ((header-len (babel:string-to-octets (format nil "~a" (length (babel:string-to-octets (list-to-header-string headers)))))) (header-bytes (babel:string-to-octets (list-to-header-string headers))) (body-bytes (babel:string-to-octets body))) (concatenate '(vector (unsigned-byte 8)) header-len #(#x3a) header-bytes #(#x2c) body-bytes))) (defmacro multi-bind1 (&body body) `(let* ((headers '("CONTENT_LENGTH" "13")) (body "HELLO WORLDIE") (headers-bytes (babel:string-to-octets (list-to-header-string headers))) (body-bytes (babel:string-to-octets body)) (stream (flexi-streams:make-in-memory-input-stream (request-format headers body)))) (multiple-value-bind (v1 v2) ,@body))) (def-suite* parse-request-suite) (in-suite parse-request-suite) (test parse-request-from-stream (multi-bind1 (cl-scgi:parse-request-from-stream stream) (is (equal (babel:octets-to-string headers-bytes) (babel:octets-to-string v1))) (is (equal (babel:octets-to-string (cl-scgi:read-until-content-length v2 stream)) (babel:octets-to-string body-bytes))))) (defun use (&rest args) (null args) nil) (test parse-request ;; DEPRECATED (multi-bind1 (cl-scgi:parse-request (request-format headers body)) (null stream) (is (equal (babel:octets-to-string body-bytes) (babel:octets-to-string v2))) (is (equal (babel:octets-to-string headers-bytes) (babel:octets-to-string v1))))) (test parse-request-with-headers ;; DEPRECATED (multi-bind1 (cl-scgi:parse-request-with-headers (request-format headers body)) (use stream body-bytes headers-bytes v2) (is-false (null (gethash "CONTENT_LENGTH" v1))))) (test parse-request-as-string ;; DEPRECATED (multi-bind1 (cl-scgi:parse-request-as-string (request-format headers body)) (use stream body-bytes headers-bytes) (is (equal v2 "HELLO WORLDIE")) (is-false (null (gethash "CONTENT_LENGTH" v1))))) (def-suite* read-fn) (in-suite read-fn) (test read-until-eof (let* ((list (babel:string-to-octets "PUT THESE IN BYTES")) (vec (concatenate '(vector (unsigned-byte 8)) list)) (stream (flexi-streams:make-in-memory-input-stream vec))) (is (babel:octets-to-string (cl-scgi:read-until-eof stream)) (babel:octets-to-string vec)))) (test read-until-content-length (let* ((list (babel:string-to-octets "PUT THESE IN BYTES")) (vec (concatenate '(vector (unsigned-byte 8)) list)) (stream (flexi-streams:make-in-memory-input-stream vec))) (is (babel:octets-to-string (cl-scgi:read-until-content-length (length list) stream)) (babel:octets-to-string vec)))) (def-suite* response-writing) (in-suite response-writing) (test write-bytes (let* ((list (babel:string-to-octets "PUT THESE IN BYTES")) (vec (concatenate '(vector (unsigned-byte 8)) list)) (stream (flexi-streams:make-in-memory-output-stream))) (cl-scgi:write-bytes vec stream) (is (equal (babel:octets-to-string (flexi-streams:get-output-stream-sequence stream)) (babel:octets-to-string vec))))) (test format-headers (let* ((hash (make-hash-table :test 'equal))) (setf (gethash "cab" hash) "321") (setf (gethash "bac" hash) "123") (is (equal (babel:octets-to-string (cl-scgi:format-headers hash)) (format nil "bac: 123~a cab: 321~a ~a " #\Return #\Return #\Return))))) (test response-string (let* ((hash (make-hash-table :test 'equal)) (body "hello world") (stream (flexi-streams:make-in-memory-output-stream))) (setf (gethash "cab" hash) "321") (setf (gethash "bac" hash) "123") (cl-scgi:response-string hash body stream) (is (equal (babel:octets-to-string (flexi-streams:get-output-stream-sequence stream)) (format nil "Content-Length: 11~a bac: 123~a cab: 321~a ~a hello world" #\Return #\Return #\Return #\Return)))))
5,207
Common Lisp
.lisp
127
35.07874
122
0.645932
lemondevxyz/cl-scgi
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
2a8bc6acb4d5e81d008c846dee7a59b319ea8dda8533663b5d1c358aaa9aed1a
41,889
[ -1 ]
41,890
cl-scgi.asd
lemondevxyz_cl-scgi/cl-scgi.asd
(defsystem "cl-scgi" :depends-on (#:babel #:alexandria #:flexi-streams #:bordeaux-threads #:usocket #:unix-sockets #:str) :components ((:module "src" :components ((:file "main") (:file "server") (:file "unix" :depends-on ("server"))))) :in-order-to ((test-op (test-op "cl-scgi/tests")))) (defsystem "cl-scgi/tests" :depends-on ("cl-scgi" "fiveam" "flexi-streams") :components ((:module "t" :components ((:file "main")))) :perform (test-op (o c) (symbol call :fiveam '#:run-all-tests :cl-scgi)))
582
Common Lisp
.asd
11
44
102
0.570175
lemondevxyz/cl-scgi
0
0
0
GPL-3.0
9/19/2024, 11:50:50 AM (Europe/Amsterdam)
949dceffd9e89e86b9e12f47c4e070ec5dd7600e200a33e0785eac4f225e36aa
41,890
[ -1 ]
41,913
package.lisp
staudtlex_calcal-lisp/package.lisp
;;;; -*- mode: Lisp; indent-tabs-mode: nil; -*- ;;;; Copyright (C) 2022 Alexander Staudt ;;;; ;;;; This program is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program. If not, see <https://www.gnu.org/licenses/>. ;;;; (in-package :common-lisp) (defpackage :calcal (:import-from :uiop :split-string :command-line-arguments) (:use :cl))
896
Common Lisp
.lisp
20
43.4
75
0.714612
staudtlex/calcal-lisp
0
0
0
GPL-3.0
9/19/2024, 11:50:58 AM (Europe/Amsterdam)
b54c2397c353608df2de00ca5705c3b2b234b3cbaf86afd7dbd4cfd11da306ad
41,913
[ -1 ]