Guest User

Untitled

a guest
Jun 17th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. ;;
  2. ;; Note - I had this palindrome code in my files from an earlier project, but I didn't write.
  3. ;; unfortunatly, I've lost the source. This is a nice solution for O(n) time and space
  4. ;; complexity
  5.  
  6. (defn longest-palendrome
  7. [text]
  8. (letfn [(final-centers
  9. [n tcenters centers]
  10. (cond
  11. (<= n 1)
  12. centers
  13. :default
  14. (let [n (dec n)]
  15. (recur n
  16. (rest tcenters)
  17. (concat (vector
  18. (min (first tcenters) n))
  19. centers)))))
  20.  
  21. (ext-centers
  22. [strn n centers tcenters cdist]
  23. (cond
  24. (= 0 cdist)
  25. #(ext-tail strn (inc n) 1 centers)
  26. (= (dec cdist) (first tcenters))
  27. #(ext-tail strn n (first tcenters) centers)
  28. true
  29. #(ext-centers strn n
  30. (concat
  31. (vector (min (first tcenters) (dec cdist)))
  32. centers)
  33. (rest tcenters) (dec cdist))))
  34.  
  35. (ext-tail
  36. [strn n curr-tail centers]
  37. (cond
  38. (> n (dec (count strn)))
  39. #(final-centers curr-tail centers
  40. (concat (vector curr-tail) centers))
  41. (= (- n curr-tail) 0)
  42. #(ext-centers strn n
  43. (concat (vector curr-tail) centers)
  44. centers curr-tail)
  45. (= (nth strn n) (nth strn (- n curr-tail 1)))
  46. #(ext-tail strn (inc n) (+ 2 curr-tail) centers)
  47. true
  48. #(ext-centers strn n
  49. (concat (vector curr-tail) centers)
  50. centers curr-tail)))
  51.  
  52. (pal-around-centers
  53. [strn]
  54. (reverse (trampoline #(ext-tail strn 0 0 []))))]
  55. (pal-around-centers text)))
  56.  
  57. (defn longest-pal-str [strn seq]
  58. (if (empty? seq)
  59. ""
  60. (let* [len (reduce max seq)
  61. pos (.indexOf (ArrayList. seq) len)
  62. start (- (/ pos 2) (/ len 2))
  63. end (+ (/ pos 2) (/ len 2))]
  64. (subs strn start end))))
  65.  
  66. (defn find-password []
  67. (let [txt (slurp "./gettysburg.txt")]
  68. (longest-pal-str txt (longest-palendrome txt))))
Add Comment
Please, Sign In to add comment