Last active
October 28, 2024 21:56
-
-
Save PEZ/92a4bd13aaa6bffb80d7724de2c8e64d to your computer and use it in GitHub Desktop.
Compress a Sequence – Rich 4Clojure Problem 30 – See: https://github.com/PEZ/rich4clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns rich4clojure.easy.problem-030 | |
(:require [hyperfiddle.rcf :refer [tests]])) | |
;; = Compress a Sequence = | |
;; By 4Clojure user: dbyrne | |
;; Difficulty: Easy | |
;; Tags: [seqs] | |
;; | |
;; Write a function which removes consecutive duplicates | |
;; from a sequence. | |
(def __ :tests-will-fail) | |
(comment | |
) | |
(tests | |
(apply str (__ "Leeeeeerrroyyy")) := "Leroy" | |
(__ [1 1 2 3 3 2 2 3]) := '(1 2 3 2 3) | |
(__ [[1 2] [1 2] [3 4] [1 2]]) := '([1 2] [3 4] [1 2])) | |
;; To participate, fork: | |
;; https://github.com/PEZ/rich4clojure | |
;; Post your solution below, please! |
szalai1
commented
Sep 6, 2021
•
(defn dedup
[s]
(if (empty? s)
'()
(cons (first s)
(->> s
(partition 2 1)
(filter #(not= (first %) (second %)))
(map second)))))
(def __ dedup)
(def __ #(map first (partition-by
identity %)))
with some reference to ClojureDocs.
(def __ #(loop [l (seq %)
res []]
(if (empty? l)
(seq res)
(if (and (not-empty res) (= (last res) (first l)))
(recur (rest l) res)
(recur (rest l) (conj res (first l)))))))
(defn __ [l]
(filter some?
(map-indexed
(fn [idx value] (if (not= value (get l (+ idx 1))) value)) l)))
(def __ (fn [s]
(->> s
(reduce
(fn [acc curr]
(if (= (last acc) curr)
acc
(concat acc (list curr))))
(list)))))
(defn consecutive-duplicates [coll]
(partition-by identity coll))
(defn get-firsts [coll]
(map first coll))
(def __ #(-> % consecutive-duplicates get-firsts))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment