Skip to content

Instantly share code, notes, and snippets.

@svdberg
Created March 23, 2011 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svdberg/882976 to your computer and use it in GitHub Desktop.
Save svdberg/882976 to your computer and use it in GitHub Desktop.
Attempt to solve the stacking boxes problem
(ns user.core
(:use [clojure.contrib.duck-streams :only (read-lines)]))
(declare lcs) ; Declare the memoized lcs
(def *file-name* "/Users/svdberg/boxes.txt")
(defn longest [xs ys] (if (> (count xs) (count ys)) xs ys))
(defn undecorated-lcs [seqx seqy]
(cond (empty? seqx) seqx
(empty? seqy) seqy
true (let [[x & xs] (seq seqx), [y & ys] (seq seqy)]
(if (= x y)
(cons x (lcs xs ys))
(longest (lcs seqx ys) (lcs xs seqy))))))
; Make a memoized version of lcs
(def lcs (memoize undecorated-lcs))
(defn number-a-seq
[seq]
(map-indexed (fn [a b] {:index a :seq b}) seq))
(defn compare-func
"input: 2 seq of equal size, output: -1 if a<b, 0 iff a==b, 1 if a>b"
[list-a list-b]
(compare list-a list-b))
(defn seq-sel
[a]
(:seq a))
(defn sort-numbered-sequence
"sort a sequence in the form {index: 1 seq: [1 2 3]}"
[num-seq]
(let [key-fn seq-sel
comp-fn compare-func]
(sort-by key-fn compare-func num-seq)))
;; read the file
(defn get-boxes
"read the boxes from a textfile, returning a list of lists"
[]
(let [file-lines (read-lines *file-name*)
string-seq (map #(re-seq #"[\d.]+" % ) file-lines)
config-line (map read-string (first string-seq))
dimension (last config-line)
nr-of-boxes (first config-line)
boxes (take nr-of-boxes (drop 1 string-seq))]
(vec (map #(vec (map (fn [a] (read-string a)) % )) boxes))))
(defn normalized-boxes
[]
(vec (sort (vec (map #(vec (sort %)) (get-boxes))))))
(defn transpose
"rotates a matrix such that rows become columns"
[matrix]
(vec (apply map vector matrix)))
;; wrong approach.. ?
(defn lis-seq
[]
(let [bb (get-boxes)
sbb (vec (map #(vec (sort %)) bb))
sns (sort-numbered-sequence (number-a-seq sbb))]
(map (fn [a] (lcs (nth bb (:index a)) (:seq a))) sns)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment