On May 30, 2011, at 3:55 PM, joshua-choi wrote:

> Let's say that I have a set of strings, each three English letters
> long.
> 
> How can I determine which strings differ only at one location (e.g.
> "xxe" and "xbe")?
> 
> Right now, I'm writing a loop that sequentially compares every string
> to every other string. I think that there's a better way, but I don't
> know where to start.


I haven't given too much thought to performance here, but this collects all 
strings which differ only at one position. The program removes successive 
characters from each string and groups those that are the same after that 
deletion. For example,
"abc", "dbc", "zbc" are all reduced to "bc" when the first letter is removed. 
Thus, all three strings would be grouped together rather than pairwise. 
'match-position' groups related strings and weeds out singletons.

(defn remove-nth [s n]
  (str (subs s 0 n)
       (subs s (inc n))))

(defn match-position [words i]
  (remove (fn [coll] (= (count coll) 1))
          (map (fn [[key val]] (map second val))
               (group-by first
                         (map (fn [s] [(remove-nth s i) s])
                              words)))))

(match-position ["abc" "abd" "aed" "axf" "zqr" "zbc" "aqd"] 0) => (("abc" 
"zbc"))
(match-position ["abc" "abd" "aed" "axf" "zqr" "zbc" "aqd"] 1) => (("abd" "aed" 
"aqd"))
(match-position ["abc" "abd" "aed" "axf" "zqr" "zbc" "aqd"] 2) => (("abc" 
"abd"))

(match-position ["abc" "abd" "aed" "axf" "zqr" "zbc" "aqd" "qbd" "tbd" "tqr"] 
0) => (("abc" "zbc") ("abd" "qbd" "tbd") ("zqr" "tqr"))


Have all good days,
David Sletten




-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to