Created
October 1, 2011 14:47
-
-
Save ypsilon-takai/1256135 to your computer and use it in GitHub Desktop.
Code Jam Japan Prelim Problem C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(require '[clojure.contrib.io :as io]) | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
;; Main funcs | |
;; find digits pair for a and b | |
;; returns [<total bit count> <carry>] | |
(defn check-one-digit [tgt-digit carry is-msb] | |
(if (zero? carry) | |
(if (zero? tgt-digit) | |
[2 1] ;; carry 0, digit 0 -> 1 1 | |
[1 0]) ;; carry 0, digit 1 -> 1 0 | |
(if (zero? tgt-digit) | |
[1 1] ;; carry 1, digit 0 -> 1 0 | |
(if is-msb | |
[0 0] ;; carry 1, digit 1, msb yes -> 0 0 | |
[2 1]))));; carry 1, digit 1, msb no -> 1 1 | |
;; Get last digit | |
(defn lsb [n] | |
(rem n 2)) | |
;; Top digit or not | |
(defn msb? [n] | |
(= n 1)) | |
;; Main func | |
(defn gcj-pC [n] | |
(loop [tgt-n n | |
bit-count 0 | |
carry 0] | |
(if (zero? tgt-n) | |
bit-count | |
(let [[bits carr] (check-one-digit (lsb tgt-n) carry (msb? tgt-n))] | |
(recur (bit-shift-right tgt-n) | |
(+ bit-count bits) | |
carr))))) | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
;; Support funcs | |
;; get args from the question file. | |
;; returns them as | |
;; ((1 N1) (2 N2) ........)) | |
(defn get-gcj-args-list [file-name] | |
(map list | |
(iterate inc 1) | |
(map (fn [line-dat] | |
(map (fn [s] (BigInteger. s)) | |
(.split line-dat " "))) | |
(drop 1 (io/read-lines file-name))))) | |
(defn gcj-get-ans [file-name f] | |
(pmap (fn [[num args]] [num (apply f args)]) | |
(get-gcj-args-list file-name))) | |
;; Get answer : for 1 line data | |
(defn gcj-create-ans [in-file out-file f] | |
(with-open [bw (io/writer out-file)] | |
(io/with-out-writer bw | |
(dorun | |
(for [[num ans] (gcj-get-ans in-file f)] | |
(println (str "Case #" num ": " ans))))))) | |
;;(gcj-create-ans "C-large-practice.in" "C-large_practice.out" gcj-pC) | |
;; "Elapsed time: 67.20944 msecs" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment