Skip to content

Instantly share code, notes, and snippets.

@nbeloglazov
Forked from djanatyn/salesman.clj
Created August 15, 2012 09:17
Show Gist options
  • Save nbeloglazov/3357980 to your computer and use it in GitHub Desktop.
Save nbeloglazov/3357980 to your computer and use it in GitHub Desktop.
salesman
(defn move-to-front [first others]
"Moves an item to the front of the list"
(cons first (remove #(identical? first %) others)))
(defn first-level [list]
"Returns a list of all first-level permutations."
(map #(move-to-front % list) list))
(defn permute-deeper [depth list]
"Takes a list and a depth. Ignores the first few items according to the depth, and returns a list of all permutations for the rest."
(let [head-of-list (take depth list)
rest-of-list (drop depth list)
add-head #(reduce conj % (reverse head-of-list))]
(map #(add-head (move-to-front % rest-of-list)) rest-of-list)))
;; (first-level [1 2 3])
;; ((1 2 3) (2 1 3) (3 1 2))
;; (map #(permute-deeper 1 %) (first-level [1 2 3]))
;; (((1 2 3) (1 3 2)) ((2 1 3) (2 3 1)) ((3 1 2) (3 2 1)))
;; goal:
;; (permute [1 2 3])
;; ((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1))
(defn permute [coll]
(reduce
#(mapcat (partial permute-deeper %2) %)
[coll]
(range (count coll))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment