Skip to content

Instantly share code, notes, and snippets.

@ppsdatta
Last active April 21, 2022 06:06
Show Gist options
  • Save ppsdatta/09544876ad5ac441f67905b8b8507991 to your computer and use it in GitHub Desktop.
Save ppsdatta/09544876ad5ac441f67905b8b8507991 to your computer and use it in GitHub Desktop.
Various Algorithms
;;; Lisp - top 2 in a list
(defun top-2 (a)
(let ((ls (reduce
#'(lambda (vs n)
(if (null (third vs))
(list
n
(second vs)
n)
(let* ((m1 (first vs))
(m2 (second vs))
(p (third vs))
(mx (max m1 n p))
(my (cond
((= mx n) (max p m2))
((= mx p) (max n m2))
(t (max n p m2)))))
(list mx my n))))
a
:initial-value '(-999 -999 nil))))
(list (first ls)
(second ls))))
;; Top - 2 algorithm in Clojure
(defn top-2
[ns]
(let [rs (reduce
(fn [vs n]
(cond
(nil? (vs 2)) [n (vs 1) n]
:else (let [m1 (vs 0)
m2 (vs 1)
p (vs 2)
mx (max m1 n p)
my (cond
(= mx n) (max p m2)
(= mx p) (max n m2)
:else (max n p m2))]
[mx my n])))
[Integer/MIN_VALUE
Integer/MIN_VALUE
nil]
ns)]
[(rs 0)
(rs 1)]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment