Skip to content

Instantly share code, notes, and snippets.

@pradeepbishnoi
Last active December 2, 2021 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pradeepbishnoi/5e1a6fe2ab5c0d5f0e651935185e1b97 to your computer and use it in GitHub Desktop.
Save pradeepbishnoi/5e1a6fe2ab5c0d5f0e651935185e1b97 to your computer and use it in GitHub Desktop.
Advent Of Code 2021 - Clojure Solutions
;; Advent Of Code 2021
;; Author : Pradeep Bishnoi
;; Solution for Problem 1a and 1b
;; Done via REPL, will polish them sooner.
(def depth '(199 200 208 210 200 207 240 269 260 263))
(def depth-file
(clojure.string/split-lines (slurp "/tmp/advent/1a.txt")))
(defn tuple-compare [tuple]
;; tuple = (199, 200)
(when (< (first tuple)
(last tuple))
true))
(defn sum-my-tuple [tuple]
(apply + tuple))
;; Solution for 1a
(->> depth-file
(map #(Integer/parseInt %))
(partition 2 1) ;; ((199 200) (200 208) (208 210) (200 207) ...)
(filter tuple-compare)
count)
;; Solution for 1b
(->> depth-file
(map #(Integer/parseInt %))
(partition 3 1) ;; ((199 200 208) (200 208 210) (208 210 200) ...)
(map sum-my-tuple) ;; (607 618 618 617 647 ...)
(partition 2 1) ;; ((607 618) (617 647) (647 716) (716 769) ...)
(filter tuple-compare)
count)
@brdloush
Copy link

brdloush commented Dec 1, 2021

You can omit the when, it's unnecessary and due to it, your function returns true/nil (instead of true/false) which is a bit weird (although it works fine). Also, you can use destructing instead of first/last

(defn tuple-compare [tuple]
  ;; tuple = (199, 200)
    (when (< (first tuple) 
             (last tuple))
        true))
(defn tuple-compare [[a b]]
  (< a b))

@pradeepbishnoi
Copy link
Author

@brdloush thanks for your comments. This was done to quickly try my hands on this problem and as mentioned in comment - yet to be polished.
Using when instead of if was intentional and filter method only rely on true predicate. Also I understand it is generally recommended way. Yes destructing is a good idea and should have used that in first place.

@brdloush
Copy link

brdloush commented Dec 1, 2021

when instead of if is absolutely fine if you're ok with nil being returned. But in this specific case neither when nor if is really needed. You can simply return the result of < function call directly. < itself returns true/false, so there's no need to wrap if or when around it.

@pradeepbishnoi
Copy link
Author

yes, valid point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment