Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current element and the list containing everything else in Clojure?

What is the fastest way to get the list containing pairs of the current element with the list containing every other element? This should be fast as the list could contain a million elements or more.

For example given the list (1 2 3)

I want to get the list ((1 (2 3)) (2 (1 3)) (3 (1 2)))

Thanks for your help!

like image 970
toofarsideways Avatar asked Dec 06 '22 17:12

toofarsideways


1 Answers

This will work without traversing the entire vector over and over:

(defn this-and-that [xs]
  (map-indexed (fn [i x]
                [x (concat (take i xs) 
                           (drop (inc i) xs))])
              xs))

and also works for nils:

user=> (this-and-that [1 2 nil 3])
([1 (2 nil 3)] [2 (1 nil 3)] [nil (1 2 3)] [3 (1 2 nil)])
like image 86
Dave Ray Avatar answered Dec 11 '22 11:12

Dave Ray