use std::fs; use std::io::{self, BufRead}; // fn subinterval(a0: i32, a1: i32, b0: i32, b1: i32) -> bool { // a0 <= b0 && b1 <= a1 // } fn subcontained(a0: i32, a1: i32, b0: i32, b1: i32) -> bool { // subinterval(a0, a1, b0, b1) || subinterval(b0, b1, a0, a1) ((a0 - b0) * (a1 - b1)) <= 0 } fn overlap(a0: i32, a1: i32, b0: i32, b1: i32) -> bool { a0 <= b1 && b0 <= a1 } fn main() { let file = fs::File::open("input").unwrap(); let lines = io::BufReader::new(file).lines(); let mut subcont = 0; let mut overlaps = 0; for line in lines { let li = line.expect("line"); if let [a0, a1, b0, b1] = li .split(&[',', '-']) .map(|x| x.parse::().unwrap()) .collect::>()[..4] { if subcontained(a0, a1, b0, b1) { subcont += 1 } if overlap(a0, a1, b0, b1) { overlaps += 1 } } else { panic!("Bad line input") }; } assert_eq!(515, subcont); assert_eq!(883, overlaps); println!("All test passed.") } tr>
aboutsummaryrefslogtreecommitdiffstats
blob: bd421d08a169182588d335395913d1ffcbcf767f (plain)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
(ql:quickload :fiveam)

(defun recover-item (bitfield-int)
  (loop for i from 0
        when (logbitp i bitfield-int) return i))

(defun priority (value)
  (if (< value 31) ;; It is a capital letter in range [1;26]
      (+ value 26)
    (- value 32)))

(defun line-priority (str)
  (let ((mid (/ (length str) 2))
        (left-pack 0) (right-pack 0))
    (loop with cross = 0
          for l across (subseq str 0 mid)
          for r across (subseq str mid)
          do (progn
               (setf left-pack (logior left-pack (ash 1 (- (char-code l) 64))))
               (setf right-pack (logior right-pack (ash 1 (- (char-code r) 64))))
               (setf cross (logand left-pack right-pack)))
          when (< 0 cross) return (priority (recover-item cross)))))


(defun prio ()
  (with-open-file (in "input")
    (loop :for l = (read-line in nil nil)
          :while l
          :sum (line-priority l))))

(defun pick-badge (str)
  (loop with stack = 0
        for i across str
        do (setf stack (logior stack (ash 1 (- (char-code i) 64))))
        finally (return stack)))

(defun badge ()
  (with-open-file (in "input")
    (loop :for b = (loop repeat 3 for l = (read-line in nil nil) while l collect (pick-badge l))
          :while b
          :sum (priority (recover-item (apply #'logand b))))))

;; (pick-badge "LdHVLDLDdHdtLMhcqCqGWcWg" )

(fiveam:test intermediate
             (fiveam:is (= 12 (recover-item 4096)))
             (fiveam:is (= 20 (line-priority
                               "gzCjffWZCtCfZZVdqVSqJdvJndSt"))))

(fiveam:test results
  (fiveam:is (= 8072 (prio)))
  (fiveam:is (= 2567 (badge))))