Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Created November 29, 2021 14:53
Show Gist options
  • Save ericnormand/6cc9a64238b4929510bb3d3025d60151 to your computer and use it in GitHub Desktop.
Save ericnormand/6cc9a64238b4929510bb3d3025d60151 to your computer and use it in GitHub Desktop.
452 PurelyFunctional.tv Newsletter

Consecutive numbers

Write a function that determines whether a sequence of integers can be rearranged into a sequence of consecutive numbers without duplicates. The function should return the sequence of consecutive numbers or nil if it is not possible.

Examples

(consec []) ;=> () ;; trivially true
(consec [1]) ;=> (1) ;; ditto
(consec [3 1 2]) ;=> (1 2 3)
(consec [5 3 2 1]) ;=> nil ;; non-consecutive (4 is missing)
(consec [7 8 9 7]) ;=> nil ;; 7 repeats

Thanks to this site for the problem idea, where it is rated Hard in Java. The problem has been modified.

Please submit your solutions as comments on this gist.

To subscribe: https://purelyfunctional.tv/newsletter/

@harto
Copy link

harto commented Nov 29, 2021

(defn consec [coll]
  (let [sorted (sort coll)
        pairs (partition 2 1 sorted)]
    (if (every? (fn [[a b]] (= b (inc a))) pairs)
      sorted)))

@brunchboy
Copy link

(defn consec
  "If its argument can be sorted into a sequence of consecutive integers
  without duplicates, return the sorted list, or nil if it cannot."
  [s]
  (let [sorted (sort s)]
    (when (every? #{-1} (map (partial apply -) (partition 2 1 sorted)))
      sorted)))

@alex-gerdom
Copy link

alex-gerdom commented Nov 30, 2021

(defn consec [xs]
  (let [sorted-xs (sort xs)
        needed-xs (take (count xs)
                        (iterate inc (first sorted-xs)))]
    (when (= sorted-xs needed-xs)
      sorted-xs)))

@dhoboy
Copy link

dhoboy commented Dec 1, 2021

(defn consec
  "function that determines whether a sequence of integers
  can be rearranged into a sequence of consecutive numbers
  without duplicates."
  [vect]
  (if (< (count vect) 2)
    vect    
    (let [unique-vect (into #{} vect)
          sorted-vect (sort vect)
          step-check (loop [[val1 val2 & rest] sorted-vect]
                       (let [diff (- val2 val1)]
                         (cond 
                           (and (nil? rest) (= diff 1)) true
                           (= diff 1) (recur (cons val2 rest))
                           :else nil)))]
    (if (and
          (= (count vect) (count unique-vect))
          step-check)
      sorted-vect
      nil))))

@KingCode
Copy link

KingCode commented Dec 4, 2021

(defn consec [xs]
  (let [sxs (sort xs)]
    (when-not 
        (->> sxs (partition 2 1)
             (reduce (fn [misfit? [x y]]
                       (if misfit? 
                         (reduced true)
                         (not= 1 (- y x))))
                     false))
      sxs)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment