Created
December 14, 2012 13:35
-
-
Save ponkore/4285505 to your computer and use it in GitHub Desktop.
Project Euler Problem 4
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
;;;A palindromic number reads the same both ways. | |
;;;The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99. | |
;;;Find the largest palindrome made from the product of two 3-digit numbers. | |
;;;左右どちらから読んでも同じ値になる数を回文数という。 2桁の数の積で表される回文数のうち、 | |
;;;最大のものは 9009 = 91 × 99 である。 | |
;;;では、3桁の数の積で表される回文数のうち最大のものはいくらになるか。 | |
(ns projecteuler.problem-4 | |
(:require [clojure.string :as str]) | |
(:use clojure.test)) | |
(defn palindromic? | |
"回文判定をする。" | |
[s] (= s (str/reverse s))) | |
(defn nseq | |
"n桁の数値シーケンスを作る。" | |
[n] | |
(let [seq-min (int (Math/pow 10 (dec n))) | |
seq-max (* seq-min 10)] | |
(range seq-min seq-max))) | |
(defn problem-4 | |
"n桁×n桁の結果が回文数となる値を求める。" | |
([] (problem-4 3)) | |
([n] (let [dig-seq (nseq n)] | |
(->> (for [x dig-seq y dig-seq] (* x y)) | |
(filter (comp palindromic? str)) | |
(apply max))))) | |
(time (problem-4)) | |
;=> ??? | |
;=> "Elapsed time: 255.488 msecs" | |
(time (problem-4 4)) | |
;=> "Elapsed time: 24204.772 msecs" | |
;=> 99000099 | |
;;; 回文判定のテスト | |
(are [x y] (= y (palindromic? x)) | |
"abc" false | |
"aba" true | |
"aaba" false | |
"aabaa" true | |
"a" true | |
"" true) | |
;;; nseqのテスト | |
(is (= (nseq 1) (range 1 10))) | |
(is (= (nseq 2) (range 10 100))) | |
(is (= (nseq 3) (range 100 1000))) |
clojure.core の関数やマクロって、ちょうど良いくらいに世話を焼いてくれるなーと思います。
「ちょうど良い」って,私も同じように感じています.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
clojure.core
の関数やマクロって、ちょうど良いくらいに世話を焼いてくれるなーと思います。単独ではそれほど複雑な処理ができないけれど、各自を組み合わせることで力を発揮するようなものが多い。
「ここはあの関数でああして……」というように試行錯誤そのものが楽しいです。