Skip to content

Instantly share code, notes, and snippets.

@cljforge
Created December 22, 2015 10:50
Show Gist options
  • Save cljforge/20083e662952af691cdd to your computer and use it in GitHub Desktop.
Save cljforge/20083e662952af691cdd to your computer and use it in GitHub Desktop.
Raw method of grouping IP addresses. Desctructive operation.
(defn group-ips [ips]
(if (> (count ips) 1)
(let [ips (->> ips distinct sort-ips)
to-array (fn [ip-str] (str/split ip-str #"\."))]
(reduce
(fn [acc el]
(condp #(re-matches %1 %2) (last acc)
#"^$" [el]
#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
(let [arr-l (map parse-int (to-array (last acc)))
arr-r (map parse-int (to-array el))]
(if (and
(= (take 3 arr-l) (take 3 arr-r))
(= (inc (last arr-l)) (last arr-r)))
(conj (vec (butlast acc)) (str (last acc) "-" (last arr-r)))
(conj (vec acc) el)))
#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}-\d{1,3}"
(let [arr-l (to-array (last acc))
arr-r (map parse-int (to-array el))]
(if (and
(= (take 3 (map parse-int arr-l)) (take 3 arr-r))
(= (-> arr-l last last str parse-int inc) (last arr-r)))
(conj (vec (butlast acc)) (str (-> (last acc) butlast str/join) (last arr-r)))
(conj (vec acc) el)))
(conj (vec acc) el)))
[""] ips))
ips))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment