Skip to content

kata - condensing characters #12

Open
@practicalli-johnny

Description

@practicalli-johnny

Convert
("WWWWW" "BB" "BBBB" "W")
into
("5W" "2B" "4B" "W")

A possibly overcomplicated way to do this would be

(defn foo [things]
  (mapcat
    (fn [[k vs]]
      (map
        #(str (if (= k 1) "" k) (first %))
        vs))
    (group-by count things)))

(foo '("WWWWW" "BB" "BBBB" "W" "AA" "BB" "CC"))
("5W" "2B" "2A" "2B" "2C" "4B" "W")

A simple way without a transducer (not as efficient)
(def data '("WWWWW" "BB" "BBBB" "W"))
(->> data (map (juxt count first)) (map #(apply str %)))
("5W" "2B" "4B" "1W")

(def data ["WW" "BB" "CC"])
(->> a (map (juxt count first)) (map #(apply str %)))
("2W" "2B" "2C")

Using a transducer

(into [] (comp (map (juxt count first)) (map #(apply str %))) data)
["2W" "2B" "2C"]
(def data '("WWWWW" "BB" "BBBB" "W"))
(into [] (comp (map (juxt count first)) (map #(apply str %))) data)
["5W" "2B" "4B" "1W"]

Needs a conditional to return just W instead of 1W - or use another map in the transducer version

(map (fn [[n c :as pair]] (if (= n 1) [c] pair)))

Putting that map function in the transducer version of the solution:

"W" for the single letter case so I'd need an extra little transformation in my suggestion

(into [] (comp (map (juxt count first)) 
                      (map (fn [[n c :as pair]] (if (= 1 n) [c] pair))) 
                      (map #(apply str %))) a)

["5W" "2B" "4B" "W"]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions