Skip to content

Instantly share code, notes, and snippets.

@djanatyn
Created August 15, 2012 08:46
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save djanatyn/3357700 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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment