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

45
2020/day02/day02.c Normal file
View file

@ -0,0 +1,45 @@
#include <stdbool.h>
#include <stdio.h>
bool is_valid_part1(int lower, int upper, char key, char *pass) {
int count = 0;
for (char *c = pass; *c != 0; ++c) {
if (*c == key) {
count++;
}
}
return (count >= lower) && (count <= upper);
}
bool is_valid_part2(int pos1, int pos2, char key, char *pass) {
return (pass[pos1 - 1] == key) ^ (pass[pos2 - 1] == key);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <input file>\n", argv[0]);
return 0;
}
FILE *input = fopen(argv[1], "r");
int lower, upper;
char key;
char pass[256];
int count1 = 0;
int count2 = 0;
while (fscanf(input, "%d-%d %c: %s", &lower, &upper, &key, pass) == 4) {
if (is_valid_part1(lower, upper, key, pass)) {
count1++;
}
if (is_valid_part2(lower, upper, key, pass)) {
count2++;
}
}
printf("Part 1: %d\n", count1);
printf("Part 2: %d\n", count2);
return 0;
}

3
2020/day02/day02.dyalog Normal file
View file

@ -0,0 +1,3 @@
p←↑¨{⍵⊆⍨~⍵∊':- '}¨⊃⎕NGET'input'1
+/{((⍎1⌷⍵),1+⍎2⌷⍵)(1=⍸)+/(⊃3⌷⍵)⍷4⌷⍵}¨p ⍝ Part 1
+/{≠/(⊃3⌷⍵)=(4⌷⍵)[⍎¨↓(⊂1 2)⌷⍵]}¨p ⍝ Part 2

61
2020/day02/day02.rkt Normal file
View file

@ -0,0 +1,61 @@
#lang racket
(module+ test
(require rackunit))
(module+ main
(displayln "Day 2"))
(struct policy
(lower upper char)
#:transparent)
(define (parse-line str)
(define lst (string-split str #px"(\\s+|:\\s+|-)"))
(values (policy (string->number (first lst))
(string->number (second lst))
(car (string->list (third lst))))
(last lst)))
(define (read-input filename)
(with-input-from-file filename
(lambda ()
(for/lists (policies passwords)
([line (in-lines)])
(parse-line line)))))
(define (valid? pol pass)
(define cnt (count (λ (x) (equal? x (policy-char pol)))
(string->list pass)))
(and (<= (policy-lower pol) cnt)
(>= (policy-upper pol) cnt)))
(define (part1 filename)
(define-values (policies passwords) (read-input filename))
(for/sum ([pol policies]
[pass passwords]
#:when (valid? pol pass))
1))
(module+ test
(check-equal? (part1 "test") 2))
(module+ main
(displayln (part1 "input")))
(define (new-valid? pol pass)
(xor (equal? (string-ref pass (sub1 (policy-lower pol))) (policy-char pol))
(equal? (string-ref pass (sub1 (policy-upper pol))) (policy-char pol))))
(define (part2 filename)
(define-values (policies passwords) (read-input filename))
(for/sum ([pol policies]
[pass passwords]
#:when (new-valid? pol pass))
1))
(module+ test
(check-equal? (part2 "test") 1))
(module+ main
(displayln (part2 "input")))

1000
2020/day02/input Normal file

File diff suppressed because it is too large Load diff

3
2020/day02/test Normal file
View file

@ -0,0 +1,3 @@
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc