From adb051546087d6d436b566dae221f32def68c353 Mon Sep 17 00:00:00 2001 From: Inga Date: Mon, 4 Dec 2023 01:41:08 +0000 Subject: [PATCH] day 1, part 1 --- .gitignore | 2 ++ README.md | 10 ++++++++ day01-easy/main.scm | 61 ++++++++++++++++++++++++++++++++++++++++++++ day01-easy/sample.in | 4 +++ 4 files changed, 77 insertions(+) create mode 100755 day01-easy/main.scm create mode 100644 day01-easy/sample.in diff --git a/.gitignore b/.gitignore index 5dc83e0..7e419b8 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,5 @@ *.scm#* .#*.scm +easy.in +hard.in diff --git a/README.md b/README.md index 8c3baa2..d5fc560 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,12 @@ # AdventOfCode-2023-functional +Solutions to https://adventofcode.com/2023/ + +This is my first experience with Lisp, so the code is probably terrible. + +Requirements: Guile 3 in `/usr/bin`. + +In a folder for a specific day, + +* To run (assuming NuShell): `open sample.in | ./main.scm`; +* To run (assuming bash): `./main.scm < sample.in`. diff --git a/day01-easy/main.scm b/day01-easy/main.scm new file mode 100755 index 0000000..c429173 --- /dev/null +++ b/day01-easy/main.scm @@ -0,0 +1,61 @@ +#!/usr/bin/guile -s +!# + +(use-modules (ice-9 rdelim)) + +(define (read-lines) + (let loop ((line (read-line))) + (if + (eof-object? line) + '() + (cons line (loop (read-line)))))) + +(define (map list mapper) + (if + (null? list) + '() + (cons (mapper (car list)) (map (cdr list) mapper)))) + +(define (first-last-combine current rest) + (if + (null? current) + rest + (if + (null? rest) + current + (cons (car current) (cdr rest))))) + +(define (first-last list predicate) + (if + (null? list) + '() + (first-last-combine + (if + (predicate (car list)) + (cons (car list) (cons (car list) '())) + '()) + (first-last (cdr list) predicate)))) + +(define (sum numbers) + (if + (null? numbers) + 0 + (+ (car numbers) (sum (cdr numbers))) + )) + +(define (solve-line line) + ( + #!(lambda (first-last-result) (sum (map first-last-result (lambda (char) (string->number (string char))))))!# + (lambda (first-last-result) (string->number (list->string first-last-result))) + (first-last + (string->list line) + (lambda (char) (if (char-numeric? char) #t #f))))) + +(define (solve-all lines) + (if + (null? lines) + 0 + (+ (solve-line (car lines)) (solve-all (cdr lines))) + )) + +(display (solve-all (read-lines))) diff --git a/day01-easy/sample.in b/day01-easy/sample.in new file mode 100644 index 0000000..1ba8437 --- /dev/null +++ b/day01-easy/sample.in @@ -0,0 +1,4 @@ +1abc2 +pqr3stu8vwx +a1b2c3d4e5f +treb7uchet \ No newline at end of file