August 24, 2018

Just Juxt #10: Longest Increasing Sub-Seq (4clojure #53)

Increasing size

(ns live.test
  (:require [cljs.test :refer-macros [deftest is testing run-tests]]))
  
(defn longest-increasing-subseq [s]
  (->> s
       (partition 2 1)
       (partition-by #(apply - %))
       (filter (fn [[[x y]]] (= (- y x) 1)))
       (sort-by count)
       last
       ((juxt #(map first (butlast %)) last))
       (apply concat)))

(deftest longest-increasing-subseq-test
  (is (= (longest-increasing-subseq [1 0 1 2 3 0 4 5]) [0 1 2 3]))
  (is (= (longest-increasing-subseq [5 6 1 3 2 7]) [5 6]))
  (is (= (longest-increasing-subseq [2 3 3 4 5]) [3 4 5]))
  (is (= (longest-increasing-subseq [7 6 5 4]) [])))

(run-tests)
(->> [1 0 1 2 3 0 4 5]
     (partition 2 1)
     (partition-by #(apply - %))
     (filter (fn [[[x y]]] (= (- y x) 1)))
     (sort-by count)
     last
     ((juxt #(map first (butlast %)) last))
     (apply concat))

Here it is step by step:

(partition 2 1 [1 0 1 2 3 0 4 5])
(partition-by #(apply - %)
              '((1 0) (0 1) (1 2) (2 3) (3 0) (0 4) (4 5)))
(filter (fn [[[x y]]] (= (- y x) 1)) 
        '(((1 0)) ((0 1) (1 2) (2 3)) ((3 0)) ((0 4)) ((4 5))))
(sort-by count '(((0 1) (1 2) (2 3)) ((4 5))))
(last '(((4 5)) ((0 1) (1 2) (2 3))))
((juxt #(map first (butlast %)) last) '((0 1) (1 2) (2 3)))
(apply concat ['(0 1) '(2 3)])

Here's what's being juxted:

(map first (butlast '((0 1) (1 2) (2 3))))
(last '((0 1) (1 2) (2 3)))
Tags: coding exercises KLIPSE 4clojure Cryogen juxt