Initial commit

This commit is contained in:
Dimitri Lozeve 2024-11-12 21:43:32 +01:00
commit f242d2b0df
420 changed files with 62521 additions and 0 deletions

3
2021/day03/day03.bqn Normal file
View file

@ -0,0 +1,3 @@
in-'0'¨•FLines"input"
D2B2×+˜´
•Show ×´D2B¨(1-)(+´>÷2˙)in # part 1

35
2021/day03/day03.c Normal file
View file

@ -0,0 +1,35 @@
#include <stdio.h>
#define N 1000
#define M 12
int main() {
char c = 0;
int i = 0, j = 0;
char in[N][M] = {0};
while ((c = getchar()) != EOF) {
switch (c) {
case '\n': i++; j = 0; break;
case '1': in[i][j] = 1; j++; break;
case '0': j++; break;
default: fprintf(stderr, "unknown digit %c", c); return 1;
}
}
// Part 1
int counts[M] = {0};
for (i = 0; i < N; ++i) {
for (j = 0; j < M; ++j) {
counts[j] += in[i][j];
}
}
int gamma = 0, epsilon = 0;
for (j = 0; j < M; ++j) {
gamma = (gamma << 1) + (counts[j] > N/2);
epsilon = (epsilon << 1) + (counts[j] <= N/2);
}
printf("%d\n", gamma * epsilon);
return 0;
}

47
2021/day03/day03.scm Normal file
View file

@ -0,0 +1,47 @@
(import (chicken io)
(chicken bitwise)
srfi-1
srfi-13)
(define (binary-string->list s)
(map (lambda (c) (- (char->integer c) (char->integer #\0)))
(string->list s)))
(define (list->binary-string l)
(string-concatenate (map number->string l)))
(define (read-input #!optional (port (current-input-port)))
(map binary-string->list (read-lines port)))
(define (part1 l)
(let* ((n (/ (length l) 2))
(counts (apply map + l))
(most-common (map (lambda (x) (if (> x n) 1 0)) counts))
(gamma (string->number (list->binary-string most-common) 2))
(epsilon (string->number (list->binary-string (map (lambda (d) (- 1 d)) most-common)) 2)))
(* gamma epsilon)))
(define (o2-rating numbers i)
(if (= 1 (length numbers))
(car numbers)
(let* ((digits (map (lambda (l) (list-ref l i)) numbers))
(most-common (if (>= (apply + digits) (/ (length numbers) 2)) 1 0))
(new-numbers (filter (lambda (n) (= (list-ref n i) most-common)) numbers)))
(o2-rating new-numbers (+ 1 i)))))
(define (co2-rating numbers i)
(if (= 1 (length numbers))
(car numbers)
(let* ((digits (map (lambda (l) (list-ref l i)) numbers))
(least-common (if (>= (apply + digits) (/ (length numbers) 2)) 0 1))
(new-numbers (filter (lambda (n) (= (list-ref n i) least-common)) numbers)))
(co2-rating new-numbers (+ 1 i)))))
(define (part2 l)
(let ((o2 (string->number (list->binary-string (o2-rating l 0)) 2))
(co2 (string->number (list->binary-string (co2-rating l 0)) 2)))
(* o2 co2)))
(let ((in (read-input)))
(print (part1 in))
(print (part2 in)))

1000
2021/day03/input Normal file

File diff suppressed because it is too large Load diff