Skip to content

Instantly share code, notes, and snippets.

@artlung
Forked from alandipert/gist:585336
Created September 19, 2010 22:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save artlung/587176 to your computer and use it in GitHub Desktop.
challenge in clojure
;;; FIRST CHALLENGE
(defn challenge1
"Given file name f reads it and prints statistics."
[f]
(let [{numbers false letters true} (group-by #(nil? (re-matches #"\d*" %))
(clojure.contrib.duck-streams/read-lines f))
letter-freqs (frequencies letters)
sum (reduce + (map #(Integer/parseInt %)
numbers))]
(println sum)
(doseq [k (keys letter-freqs)]
(println k " = " (get letter-freqs k)))))
;;; Ruby:
;;; numbers, characters = File.new("test.txt").readlines.map(&:chop).partition{|c|c=~/\d/}
;;; puts numbers.map(&:to_i).reduce(:+)
;;; freqs = lambda{|arr| arr.reduce({}.tap{|h| h.default=0}){|xs,y| xs.tap{|h| h[y] += 1}}}
;;; freqs.call(characters).each_pair{|k,v| puts "#{k} = #{v}"}
;;; SECOND CHALLENGE
(defn str-reverse
"Reverse a string."
[s]
(apply str (reverse (str s))))
(defn reverse-sums
"Lazy sequence of n added to its reverse.
ie. (take 5 (reverse-sums 56)) ;=> (56 121 242 484 968)"
[n]
(letfn [(rev-add [a] (+ a (BigInteger. (str-reverse a))))]
(iterate rev-add n)))
(defn palindrome?
"True if n is a palindrome."
[n]
(= (str n)
(str-reverse n)))
(defn candidate?
"True if none the first lim reverse-sums of n are palindromes."
[lim n]
(every? #(not (palindrome? %))
(take lim (reverse-sums n))))
(defn challenge2
"Prints the Lychrel candidates for a given lim, below n."
[lim n]
(println "Candidates: "
(filter (partial candidate? lim)
(range 1 (inc n)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment