ローマ数字の正規化?の問題です。
質問は、正規化したときにどれだけ文字数が減るかというものです。
解くにはいろいろ方法がありそうですが、問題の最後の一文に書かれている内容から置換対象が数個に限定されるので、それを数えることで直接減らせる文字数を数えています。
以下コードです。
簡単なので、解説無しです。
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
;; problem 89 | |
;; "Elapsed time: 46.861639 msecs" | |
(require '[clojure.java.io :as io]) | |
(require '[clojure.test :as test]) | |
(defn pe89 [roman-num] | |
(let [check-strings-a "VIIII|LXXXX|DCCCC" ;IX, ID, IM : saves 3 | |
check-strings-b "IIII|XXXX|CCCC" ;IV, IL, ID : saves 2 | |
r-num (str "-" roman-num "-") | |
count-a (dec (count (seq (.split r-num check-strings-a)))) | |
count-b (dec (count (seq (.split r-num check-strings-b))))] | |
(+ (* count-a 3) | |
(* (- count-b count-a) 2)))) | |
(test/is (= (pe89 "III") | |
0)) | |
(test/is (= (pe89 "XVIIII") | |
3)) | |
(test/is (= (pe89 "DDCCCCLXXXIIII") | |
5)) | |
(defn pe-89-with-file [input-file] | |
(with-open [in-file (io/reader input-file)] | |
(reduce #(+ %1 (pe89 %2)) 0 (line-seq in-file)))) | |
(pe-89-with-file "http://projecteuler.net/project/roman.txt") | |
0 コメント:
コメントを投稿