Skip to content

Instantly share code, notes, and snippets.

@cbilson
Created April 27, 2012 13:38
Show Gist options
  • Select an option

  • Save cbilson/2509287 to your computer and use it in GitHub Desktop.

Select an option

Save cbilson/2509287 to your computer and use it in GitHub Desktop.
My solution to Google Code Jam problem #3
(ns RecycledNumbers.core)
;; This is the version I _wish_ I had submitted. It took about 1 minute to
;; add a single high level pmap (see comment below) and I would have completed
;; the problem in time.
;; Luckily, I qualified anyway, so maybe this lesson will come in handy in tonight's
;; competition.
(defn cycles [n]
(cond
(< n 10) (list n)
:default
(let [s (str n)
l (.length s)]
(->> (vec s)
(repeat 2)
flatten
(partition l 1)
(take l)
(map #(apply str %))
(map #(Integer/parseInt %))))))
(defn recycled-pair? [n m]
(some #(= n %) (cycles m)))
(defn recycled-pairs [a b]
(when (< a b)
(lazy-seq
(let [pairs (->> (cycles a)
(filter #(< a %))
(filter #(>= b %))
distinct
(map #(vector a %)))]
(concat pairs (recycled-pairs (inc a) b))))))
(defn count-recycled-pairs [a b]
(count (recycled-pairs a b)))
(defn process-line [line]
(->> (.split line " ")
(map #(Integer/parseInt %))
(apply count-recycled-pairs)))
(defn -main
[filename]
(println "Processing " filename)
(with-open [rdr (clojure.java.io/reader filename)
wtr (clojure.java.io/writer (str filename ".out"))]
;; SOLUTION: By simply using pmap here it finishes the big data set for
;; problem #3 in "Elapsed time: 272033.643 msecs" (about 5 minutes) on my
;; computer. Doh!
(let [lines (drop 1 (line-seq rdr))
results (pmap process-line lines)]
(loop [[r & rs] results
i 1]
(println "Working on Case #" i)
(.write wtr (str "Case #" i ": " r "\n"))
(if (not (empty? rs))
(recur rs (inc i)))))))
@cbilson
Copy link
Author

cbilson commented Apr 27, 2012

This is the version that would have won. See previous version for the one I actually submitted, which was too slow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment